问:
MultiAutoCompleteTextView android restrict user from selecting same value multiple times
MultiAutoCompleteTextView android how to restrict user from selecting same value multiple times? </p>

答:
You could check the values which selected in ItemClick event.

I make a code sample for you.

layout2.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<MultiAutoCompleteTextView
android:id="@+id/multiAutoCompleteTextView1"
                         android:layout_width="match_parent"
                         android:layout_height="wrap_content"/>
</LinearLayout>
</code>```

MainActivity.cs

```<code> var multiAutoCompleteTextView1 = FindViewById<MultiAutoCompleteTextView>(Resource.Id.multiAutoCompleteTextView1);

        string[] arraydata = { "apple1", "apple2", "shanghai1", "shanghai2" };

        ArrayAdapter<string> adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, arraydata);
        multiAutoCompleteTextView1.Adapter = adapter;
        multiAutoCompleteTextView1.SetTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());

        string PreviousText = string.Empty;

        multiAutoCompleteTextView1.ItemClick += (s, e) =>
        {
            var currentText = multiAutoCompleteTextView1.Text;
            var currentList = currentText.Replace(" ","").Split(',');
            var length = currentList.Length;
            if (length > 2)
            {
                for (int i = 0; i < length - 1; i++)
                {
                    if (i < length - 2)
                    {
                        if (currentList[i] == currentList[length - 2])
                        {
                            multiAutoCompleteTextView1.Text = PreviousText;
                            //do the something when you select the same value
                        }
                    }

                }

            }

            PreviousText = multiAutoCompleteTextView1.Text;
        };
</code>```

In the sample code, i reset the value of MultiAutoCompleteTextView when select the same value.

Body:
You could check the values which selected in ItemClick event.

I make a code sample for you.

layout2.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<MultiAutoCompleteTextView
android:id="@+id/multiAutoCompleteTextView1"
                         android:layout_width="match_parent"
                         android:layout_height="wrap_content"/>
</LinearLayout>

MainActivity.cs

 var multiAutoCompleteTextView1 = FindViewById<MultiAutoCompleteTextView>(Resource.Id.multiAutoCompleteTextView1);

        string[] arraydata = { "apple1", "apple2", "shanghai1", "shanghai2" };

        ArrayAdapter<string> adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, arraydata);
        multiAutoCompleteTextView1.Adapter = adapter;
        multiAutoCompleteTextView1.SetTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());

        string PreviousText = string.Empty;

        multiAutoCompleteTextView1.ItemClick += (s, e) =>
        {
            var currentText = multiAutoCompleteTextView1.Text;
            var currentList = currentText.Replace(" ","").Split(',');
            var length = currentList.Length;
            if (length > 2)
            {
                for (int i = 0; i < length - 1; i++)
                {
                    if (i < length - 2)
                    {
                        if (currentList[i] == currentList[length - 2])
                        {
                            multiAutoCompleteTextView1.Text = PreviousText;
                            //do the something when you select the same value
                        }
                    }

                }

            }

            PreviousText = multiAutoCompleteTextView1.Text;
        };

In the sample code, i reset the value of MultiAutoCompleteTextView when select the same value.


来源: stackexchange

问:
Cypress .trigger commands with mousedown, mousemove & mouseup do not work
Is there some secret method to get this working?

We are using the draggable library to do this in the UI.

https://github.com/Shopify/draggable/tree/master/src/Draggable

I am trying to drag one column to the next using the Cypress automation runner.

This is my code:

```<code>cy.get(dataExplorerTableAttributeDraggable)
      .eq(0)
      .trigger('mousedown', { which: 1 });
    cy.get(dataExplorerTableAttributeDraggable)
      .eq(1)
      .trigger('mousemove')
      .trigger('mouseup');
</code>```

Executing this code has no visible result whatsoever.

Also tried this:

```<code>cy.get(dataExplorerTableAttributeDraggable)
      .eq(2)
      .trigger('mousedown', { which: 1 })
      .trigger('dragstart', {})
      .trigger('drag', {});
    cy.get(dataExplorerTableAttributeDraggable)
      .eq(0)
      .trigger('dragover')
      .trigger('drop')
      .trigger('dragend')
      .trigger('mouseup');
</code>```

I must make it clear that I need the automation to actually DO the drag & drop, not just trigger events.

What am I missing?

答:
Problem description

I have came across with same issue but I wasn't using any library.

Problem was that somewhere in code I had type check for event, like this:

```<code>if (event instanceof MouseEvent) {
    /* this never gets executed in Cypress but works fine when manually testing in browser */
}
</code>```

After some debugging, I found out that mousedown event (fired from Cypress) is instance of Event but from different environment (event instanceof Event always returned false). I never dug deep into this, so I could be wrong about that.

Anyway, solution for me was to fire native JavaScript event in Cypress using MouseEvent from cy.window().

Potential solution for your case

Now after looking around a bit that library that you are using, I see it uses events such as DragMouseEvent which might be same problem like I had.
If that is the case, I guess that following code would get it working (I haven't tested):

```<code>cy.window().then(win => {
    cy.get(dataExplorerTableAttributeDraggable)
      .eq(0)
      .then($element => $element[0].dispatchEvent(new win.MouseEvent('mousedown', {button: 1, clientX: 100, clientY: 100})));
    cy.get(dataExplorerTableAttributeDraggable)
      .eq(1)
      .then($element => $element[0].dispatchEvent(new win.MouseEvent('mousemove', {clientX: 100, clientY: 100})))
      .then($element => $element[0].dispatchEvent(new win.MouseEvent('mouseup', {clientX: 100, clientY: 100})));
})
</code>```

Please note that $element is jQuery wrapped element. Also clientX and clientY should have proper position values of element in page that you want to drag (100 is just placeholder).

Alternative solution for my problem above is to perform duck-type check in code like this:

```<code>if (event.pageX && event.pageY) {
    /* this now gets executed in Cypress and when manually testing in browser */
}
</code>```

This would work only if you are writing your own code (not using library).

ContentLicense: CC BY-SA 4.0

Body:
Is there some secret method to get this working?

We are using the draggable library to do this in the UI.

https://github.com/Shopify/draggable/tree/master/src/Draggable

I am trying to drag one column to the next using the Cypress automation runner.

This is my code:

cy.get(dataExplorerTableAttributeDraggable)
      .eq(0)
      .trigger('mousedown', { which: 1 });
    cy.get(dataExplorerTableAttributeDraggable)
      .eq(1)
      .trigger('mousemove')
      .trigger('mouseup');

Executing this code has no visible result whatsoever.

Also tried this:

cy.get(dataExplorerTableAttributeDraggable)
      .eq(2)
      .trigger('mousedown', { which: 1 })
      .trigger('dragstart', {})
      .trigger('drag', {});
    cy.get(dataExplorerTableAttributeDraggable)
      .eq(0)
      .trigger('dragover')
      .trigger('drop')
      .trigger('dragend')
      .trigger('mouseup');

I must make it clear that I need the automation to actually DO the drag & drop, not just trigger events.

What am I missing?

Body:
Problem description

I have came across with same issue but I wasn't using any library.

Problem was that somewhere in code I had type check for event, like this:

if (event instanceof MouseEvent) {
    /* this never gets executed in Cypress but works fine when manually testing in browser */
}

After some debugging, I found out that mousedown event (fired from Cypress) is instance of Event but from different environment (event instanceof Event always returned false). I never dug deep into this, so I could be wrong about that.

Anyway, solution for me was to fire native JavaScript event in Cypress using MouseEvent from cy.window().

Potential solution for your case

Now after looking around a bit that library that you are using, I see it uses events such as DragMouseEvent which might be same problem like I had.
If that is the case, I guess that following code would get it working (I haven't tested):

cy.window().then(win => {
    cy.get(dataExplorerTableAttributeDraggable)
      .eq(0)
      .then($element => $element[0].dispatchEvent(new win.MouseEvent('mousedown', {button: 1, clientX: 100, clientY: 100})));
    cy.get(dataExplorerTableAttributeDraggable)
      .eq(1)
      .then($element => $element[0].dispatchEvent(new win.MouseEvent('mousemove', {clientX: 100, clientY: 100})))
      .then($element => $element[0].dispatchEvent(new win.MouseEvent('mouseup', {clientX: 100, clientY: 100})));
})

Please note that $element is jQuery wrapped element. Also clientX and clientY should have proper position values of element in page that you want to drag (100 is just placeholder).

Alternative solution for my problem above is to perform duck-type check in code like this:

if (event.pageX && event.pageY) {
    /* this now gets executed in Cypress and when manually testing in browser */
}

This would work only if you are writing your own code (not using library).


问:
React + Material UI
I have a problem, and I don't know how to solve it!

I am using react with material-ui, the background color of the site is dark and when I put a Date type TextField the icon appears in black which makes it difficult to see!

Does anyone know how I can change the icon color to white?

EDIT:
Here is my code extract

```<code><TextField
       id="date2"
       label="Data fim"
       type="date"
       className={classes.margRight2}
       value={this.state.EndDate}
       onChange={this.handleChange('EndDate')}
       InputLabelProps={{ shrink: true, }}
/>
</code>```

答:
As I'm checking Material-UI uses SVG icons, so you can change its colour by using the "color" CSS property to the svg tag.

Check this Codesandbox for my solution: https://codesandbox.io/s/material-ui-date-picker-nnzgv?fontsize=14&hidenavigation=1&theme=dark

Pay attention to the styles in "index.html" and the "demo.js" line 60. I assign my datetime picker a class and then I use the svg selector to set the white color.

Hope it helps.

Title: React + Material UI

Body:
I have a problem, and I don't know how to solve it!

I am using react with material-ui, the background color of the site is dark and when I put a Date type TextField the icon appears in black which makes it difficult to see!

Does anyone know how I can change the icon color to white?

EDIT:
Here is my code extract

<TextField
       id="date2"
       label="Data fim"
       type="date"
       className={classes.margRight2}
       value={this.state.EndDate}
       onChange={this.handleChange('EndDate')}
       InputLabelProps={{ shrink: true, }}
/>


问:
How to plot small floating numbers properly
How to plot the set of numbers like (first column is x-axis, second column is y-axis):

```<code>1 3.4335e-14
2 5.8945e-28
3 6.7462e-42
4 5.7908e-56
5 3.9765e-70
6 2.2756e-84
7 1.1162e-98
8 4.7904e-113
9 1.8275e-127
10 6.2749e-142
11 1.9586e-156
12 5.6041e-171
13 1.4801e-185
14 3.6300e-200
15 8.3091e-215
16 1.7831e-229
17 3.6013e-244
18 6.8694e-259
19 1.2414e-273
</code>```

For now I get:

And I can't figure out how to make it properly. It means no flat line from 2 to the end and correct y-axis values. I read these values from the file with:

```<code>x_values.append(line.split(' ')[0])
y_values.append(float(line.split(' ')[1]))
</code>```

答:
You may wish to switch the yscale to "log" scale, e.g.:

```<code>import matplotlib.ticker as mtick
_,ax = plt.subplots()
plt.plot(x,y)
plt.xticks(x)
plt.yscale("log")
ax.yaxis.set_major_formatter(mtick.FormatStrFormatter('%.2e'));
</code>```

Body:
How to plot the set of numbers like (first column is x-axis, second column is y-axis):

1 3.4335e-14
2 5.8945e-28
3 6.7462e-42
4 5.7908e-56
5 3.9765e-70
6 2.2756e-84
7 1.1162e-98
8 4.7904e-113
9 1.8275e-127
10 6.2749e-142
11 1.9586e-156
12 5.6041e-171
13 1.4801e-185
14 3.6300e-200
15 8.3091e-215
16 1.7831e-229
17 3.6013e-244
18 6.8694e-259
19 1.2414e-273

For now I get:

And I can't figure out how to make it properly. It means no flat line from 2 to the end and correct y-axis values. I read these values from the file with:

x_values.append(line.split(' ')[0])
y_values.append(float(line.split(' ')[1]))

Body:
You may wish to switch the yscale to "log" scale, e.g.:

import matplotlib.ticker as mtick
_,ax = plt.subplots()
plt.plot(x,y)
plt.xticks(x)
plt.yscale("log")
ax.yaxis.set_major_formatter(mtick.FormatStrFormatter('%.2e'));


问:
How to get values without key from JSON object in JavaScript(HTML)

                 [17/02/2020]      [18/02/2020]    [19/02/2020]
itemseq    1 Allocated        2             6              7
itemname   2 Out Of Order     0             0              0```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>success: function (result) {
                    debugger;
                    var Item1 = JSON.parse(result.Item1)

                    if (Item1.length == 0) {
                        $('<tr><td colspan="4">No Record Found</td></tr>').appendTo($('#Tablev'));
                    }
                    $('#Tablev tr:not(:first)').empty();

                        $('<tr>' +
                            '<th ' + item.itemseq+ '</th>' +
                            '<th>' + item.itemname + '</th>' +
                            (need to get the Date and date values like we got the above 2 things)

                            '</tr>').appendTo($('#Tablev'));
                    });</code>```

I'm trying to add  key values for eg-(dates "16/02/2020"): and the value it contains(0) and show them on a grid, I managed to get the itemseq and itemname but I have no idea how to get the other two key values.The dates and value are received from mssql on user input date ranges.

JSON string in JavaScript I receive is (the json string keeps ongoing on this is half of the code)

```<code>[
  {
    "itemseq": 1,
    "itemname": "Allocated",
    "17/02/2020": 2,
    "18/02/2020": 6,
    "19/02/2020": 7,
    "20/02/2020": 3,
    "21/02/2020": 7,
    "22/02/2020": 6,
    "23/02/2020": 2,
    "24/02/2020": 5
  },
  {
    "itemseq": 2,
    "itemname": "Out Of Order",
    "17/02/2020": 0,
    "18/02/2020": 0,
    "19/02/2020": 0,
    "20/02/2020": 0,
    "21/02/2020": 0,
    "22/02/2020": 0,
    "23/02/2020": 0,
    "24/02/2020": 0
  },
  {
    "itemseq": 3,
    "itemname": "Daily Occupancy %",
    "17/02/2020": 28.57,
    "18/02/2020": 85.71,
    "19/02/2020": 100,
    "20/02/2020": 42.85,
    "21/02/2020": 100,
    "22/02/2020": 85.71,
    "23/02/2020": 28.57,
    "24/02/2020": 71.42
  }
]
</code>```

How could i take the dates and the values of the dates it contains
"(date)18/02/2020": (value)85.71,

when we are using the string we can break the string and get the values like
(item.itemseq item.itemname) and i want to know how could i get the values of dates and the date values because these data are passed to a grid and gonna be used there..

eg-
columns- the dates [18/02/2020] [19/02/2020]
and the rows wise we have the [Allocated][Out Of Order] for the specific date it should contains the value that date has [85.71][100]

Body:
                 [17/02/2020]      [18/02/2020]    [19/02/2020]
itemseq    1 Allocated        2             6              7
itemname   2 Out Of Order     0             0              0

success: function (result) {
                    debugger;
                    var Item1 = JSON.parse(result.Item1)

                    if (Item1.length == 0) {
                        $('
No Record Found
').appendTo($('#Tablev'));
                    }
                    $('#Tablev tr:not(:first)').empty();

                        $('
' +
                            '<th ' + item.itemseq+ '	' +
                            '' + item.itemname + '	' +
                            (need to get the Date and date values like we got the above 2 things)

                            '
').appendTo($('#Tablev'));
                    });

I'm trying to add  key values for eg-(dates "16/02/2020"): and the value it contains(0) and show them on a grid, I managed to get the itemseq and itemname but I have no idea how to get the other two key values.The dates and value are received from mssql on user input date ranges.

JSON string in JavaScript I receive is (the json string keeps ongoing on this is half of the code)

[
  {
    "itemseq": 1,
    "itemname": "Allocated",
    "17/02/2020": 2,
    "18/02/2020": 6,
    "19/02/2020": 7,
    "20/02/2020": 3,
    "21/02/2020": 7,
    "22/02/2020": 6,
    "23/02/2020": 2,
    "24/02/2020": 5
  },
  {
    "itemseq": 2,
    "itemname": "Out Of Order",
    "17/02/2020": 0,
    "18/02/2020": 0,
    "19/02/2020": 0,
    "20/02/2020": 0,
    "21/02/2020": 0,
    "22/02/2020": 0,
    "23/02/2020": 0,
    "24/02/2020": 0
  },
  {
    "itemseq": 3,
    "itemname": "Daily Occupancy %",
    "17/02/2020": 28.57,
    "18/02/2020": 85.71,
    "19/02/2020": 100,
    "20/02/2020": 42.85,
    "21/02/2020": 100,
    "22/02/2020": 85.71,
    "23/02/2020": 28.57,
    "24/02/2020": 71.42
  }
]

How could i take the dates and the values of the dates it contains
"(date)18/02/2020": (value)85.71,

when we are using the string we can break the string and get the values like
(item.itemseq item.itemname) and i want to know how could i get the values of dates and the date values because these data are passed to a grid and gonna be used there..

eg-
columns- the dates [18/02/2020] [19/02/2020]
and the rows wise we have the [Allocated][Out Of Order] for the specific date it should contains the value that date has [85.71][100]

Body:
If you mean add a value to each item you can try this

let data = [
    {"itemseq":1,"itemname":"Allocated","17/02/2020":2.0000,"18/02/2020":6.0000,"19/02/2020":7.0000,"20/02/2020":3.0000,"21/02/2020":7.0000,"22/02/2020":6.0000,"23/02/2020":2.0000,"24/02/2020":5.0000},
    {"itemseq":2,"itemname":"Out Of Order","17/02/2020":0.0000,"18/02/2020":0.0000,"19/02/2020":0.0000,"20/02/2020":0.0000,"21/02/2020":0.0000,"22/02/2020":0.0000,"23/02/2020":0.0000,"24/02/2020":0.0000},
    {"itemseq":3,"itemname":"Daily Occupancy %","17/02/2020":28.5700,"18/02/2020":85.7100,"19/02/2020":100.0000,"20/02/2020":42.8500,"21/02/2020":100.0000,"22/02/2020":85.7100,"23/02/2020":28.5700,"24/02/2020":71.4200}
];

let copy = [];
data.forEach((item) => {
    item["16/02/2020"] = 0;
    copy.push(item);
});
console.log(copy);

"16/02/2020" index is added with value : 0 to each item


问:
ExtJs Menu Binding from database
Please provide some sample code or idea about , How to bind menu dynamically from Json results
I get results from database as json ,so how to bind menu from json (Parent and childs)

Thanks in advance

答:
Its pretty easy actually. When you return the data from the server all you need to do is include a metaData field in your JSON that defines the record structure.

See this documentation:  http://dev.sencha.com/deploy/ext-3.3.1/docs/?class=Ext.data.JsonReader

The example from the docs is as follows:

```<code>{

    metaData: {
        "idProperty": "id",
        "root": "rows",
        "totalProperty": "results"
        "successProperty": "success",
        "fields": [
            {"name": "name"},
            {"name": "job", "mapping": "occupation"}
        ],
        // used by store to set its sortInfo
        "sortInfo":{
           "field": "name",
           "direction": "ASC"
        },
        // paging data (if applicable)
        "start": 0,
        "limit": 2,
        // custom property
        "foo": "bar"
    },
    // Reader's configured successProperty
    "success": true,
    // Reader's configured totalProperty
    "results": 2000,
    // Reader's configured root
    // (this data simulates 2 results per page)
    "rows": [ // *Note: this must be an Array
        { "id": 1, "name": "Bill", "occupation": "Gardener" },
        { "id": 2, "name":  "Ben", "occupation": "Horticulturalist" }
    ]
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: ExtJs Menu Binding from database

Body:
Its pretty easy actually. When you return the data from the server all you need to do is include a metaData field in your JSON that defines the record structure.

See this documentation:  http://dev.sencha.com/deploy/ext-3.3.1/docs/?class=Ext.data.JsonReader

The example from the docs is as follows:

{

    metaData: {
        "idProperty": "id",
        "root": "rows",
        "totalProperty": "results"
        "successProperty": "success",
        "fields": [
            {"name": "name"},
            {"name": "job", "mapping": "occupation"}
        ],
        // used by store to set its sortInfo
        "sortInfo":{
           "field": "name",
           "direction": "ASC"
        },
        // paging data (if applicable)
        "start": 0,
        "limit": 2,
        // custom property
        "foo": "bar"
    },
    // Reader's configured successProperty
    "success": true,
    // Reader's configured totalProperty
    "results": 2000,
    // Reader's configured root
    // (this data simulates 2 results per page)
    "rows": [ // *Note: this must be an Array
        { "id": 1, "name": "Bill", "occupation": "Gardener" },
        { "id": 2, "name":  "Ben", "occupation": "Horticulturalist" }
    ]
}


问:
set default tab active when page loads Angular 8
After successful login, it redirects to lochalhost:4200/feature. I want to make the 'dashboard' link active in this state. When i click on dashboard, test suit and logs links active works fine.

```<code><li routerLink="dashboard"  [ngClass]="{'active': router.isActive('feature')}" routerLinkActive="active">
            <i class="img-sprite dashboard-icon"></i>
           <a  > Dashboard</a>
        </li>
        <li routerLink="test-suit" routerLinkActive="active" >
                <i class="img-sprite testsuit-icon"></i>
            <a>Test Suite</a>
        </li>
        <li routerLink="logs" routerLinkActive="active">
                <i class="img-sprite logs-icon"></i>
                <a>Logs</a></li>
</code>```

Problem is after adding ngClass, active class is not removing from 'dashboard' link.

These are the urls:

```<code>http://localhost:4200/feature     (default page url where i want to give active class as this url loads dashboard component)
http://localhost:4200/feature/dashboard    (active works fine)
http://localhost:4200/feature/test-suite   (active works fine)
http://localhost:4200/feature/logs   (active works fine)
</code>```

答:
Due same route active is not working.

here is soln:

```<code> <li routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}" >
</li>
</code>```

Here is the reference:
https://angular.io/api/router/RouterLinkActive

Body:
After successful login, it redirects to lochalhost:4200/feature. I want to make the 'dashboard' link active in this state. When i click on dashboard, test suit and logs links active works fine.

            Dashboard

            Test Suite

                Logs

Problem is after adding ngClass, active class is not removing from 'dashboard' link.

These are the urls:

http://localhost:4200/feature     (default page url where i want to give active class as this url loads dashboard component)
http://localhost:4200/feature/dashboard    (active works fine)
http://localhost:4200/feature/test-suite   (active works fine)
http://localhost:4200/feature/logs   (active works fine)

Body:
Due same route active is not working.

here is soln:

 <li routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}" >
</li>

Here is the reference:
https://angular.io/api/router/RouterLinkActive


问:
Randomly Generate a unique Number grid
I have a 2D integer array, 5x5, and I have made a solution that randomly generates the numbers 1 - 5 in each of the array cells:

```<code>public int[,] generateGrid()
{
    int seed = DateTime.Now.Second; // generate seed
    Random rand = new Random(seed); // initialise random number with seed

    int[,] grid = new int[_gridSize, _gridSize]; // create 2D array for grid

    for (int i = 0; i < _gridSize; i++) // loop through rows
    {
        for (int j = 0; j < _gridSize; j++) // loop throug columns
        {
            int value = 0; // initialise the value to be entered into cell

            while (value == 0) // while value is invalid ( "0" ) keep generating new number
            {
                value = rand.Next() % _gridSize + 1; // generate value from 0 - gridsize
                grid[i, j] = value; // input value. Note: if value = 0, the loop will regenerate a new value
            }

        }
    }
    return grid;
}
</code>```

Now this code does it's job. (Not sure about efficiency -- any extra advice on efficiency would be helpful.)

But my problem is, each column and each row can only contain the number 1-5 once! (rather like Sudoku.) and I'm not sure about how to do this (or the best way to do it).

My first idea was to make a stack, and push all the values created per row in the stack, then check it to see if the row already contains that value. if it does, generate a new value, check again etc.
But iterating the stack is a bad idea, also, that's good for checking the rows, but when it comes to checking the columns for uniqueness, it gets a bit difficult!

So basically, how can I make all rows and columns unique, but still be able to generate randomly each time. And what would be the best way to do this?

答:
I guess you may have to do this a bit like solving a Sudoku. In other words initially each cell can contain any of the 5 values: so you set the first cell randomly, with no restrictions. Then set the next cell: now there is a restriction, it cannot have the value for the first cell (it's in the same row), so you may need to take a few goes to get a valid number.

Just keep working along each row and column, always checking back to the left (lower column index) for the values already set on this row, and checking up (lower row index) for the values already set on this column. If you try to set a cell to a value already used on this row or column just try again.

This should be expandable if you need to use different-sized grids. I will leave it to you how to optimise it if necessary (hint: setting the last cell may end up taking a longer than any other cell, even though it is the one which has only one possible value).

Title: Randomly Generate a unique Number grid

Body:
I have a 2D integer array, 5x5, and I have made a solution that randomly generates the numbers 1 - 5 in each of the array cells:

public int[,] generateGrid()
{
    int seed = DateTime.Now.Second; // generate seed
    Random rand = new Random(seed); // initialise random number with seed

    int[,] grid = new int[_gridSize, _gridSize]; // create 2D array for grid

    for (int i = 0; i < _gridSize; i++) // loop through rows
    {
        for (int j = 0; j < _gridSize; j++) // loop throug columns
        {
            int value = 0; // initialise the value to be entered into cell

            while (value == 0) // while value is invalid ( "0" ) keep generating new number
            {
                value = rand.Next() % _gridSize + 1; // generate value from 0 - gridsize
                grid[i, j] = value; // input value. Note: if value = 0, the loop will regenerate a new value
            }

        }
    }
    return grid;
}

Now this code does it's job. (Not sure about efficiency -- any extra advice on efficiency would be helpful.)

But my problem is, each column and each row can only contain the number 1-5 once! (rather like Sudoku.) and I'm not sure about how to do this (or the best way to do it).

My first idea was to make a stack, and push all the values created per row in the stack, then check it to see if the row already contains that value. if it does, generate a new value, check again etc.
But iterating the stack is a bad idea, also, that's good for checking the rows, but when it comes to checking the columns for uniqueness, it gets a bit difficult!

So basically, how can I make all rows and columns unique, but still be able to generate randomly each time. And what would be the best way to do this?


问:
What is the fastest way to merge N unsorted arrays into 1 sorted array in JavaScript?
I'm having trouble merging N unsorted arrays into 1 sorted array in JavaScript.

I know I can quickly concat then sort, but efficiency is important here.

I have arrays I'm getting back from an api (I can't ensure they arrive sorted) that need to end up in 1 sorted array. My first instinct was to try and not reinvent the wheel and try to find a way to reliably sort these into an output array. I figured I would try to sort each one, and then take advantage of the algorithm on GeeksForGeeks. This requires the arrays to be in sorted order, so I sort the arrays first individually

I haven't spent much time in C++, so I spent some time trying to reimplement this in JavaScript:

const TinyQueue = require('tinyqueue'); // const Heap = require('heap');

//typedef pair<int, pair<int, int> > ppi;
const pair = (val1, val2) => ({ first: val1, second: val2 });
const ppi = (val1, [val2a, val2b]) => pair(val1, pair(val2a, val2b));
//console.log(ppi('a', ['b', 'c'])) -> { first: 'a', second: { first: 'b', second: 'c' } }

// This function takes an array of arrays as an
// argument and all arrays are assumed to be
// sorted. It merges them together and prints
// the final sorted output.
function mergeKArrays(arr) {
  const output = [];
  queue = new TinyQueue();

  for (var i = 0, len = arr.length; i < len; i++) queue.push(ppi(arr[i][0], [i, 0]));

  while(queue.length) {
    let curr = queue.pop();
    // i ==> Array Number
    // j ==> Index in the array number
    let i = curr.second.first;
    let j = curr.second.second;

    output.unshift(curr.first);

    // The next element belongs to same array as current.
    if (j + 1 < arr[i].length) queue.push(ppi( arr[i][j + 1], [ i, j + 1]));
  }

  return output;
}
// -- Test Data --
const unsortedArrays = [
  [12, 2, 6],
  [9, 1],
  [2000, 23, 34, 90]
];
const sortedArrays = unsortedArrays.map(array => array.sort((a,b) => a - b));

console.log(sortedArrays);
const mergedArr = mergeKArrays(sortedArrays);

console.log(mergedArr);
```

The Geeks for Geeks algorithm. This code shared on repl.it.

So the input is [ [ 2, 6, 12 ], [ 1, 9 ], [ 23, 34, 90, 2000 ] ]

Expected output is [ 1, 2, 6, 9, 12, 23, 34, 90, 2000 ]

Actual output is [ 9, 2000, 1, 90, 12, 34, 6, 23, 2 ]

What is going wrong here? If this worked, is there a more efficient way to merge N unsorted arrays into 1 sorted one?

答:
I would flatten the array first then sort

```<code> let input = [ [ 2, 6, 12 ], [ 1, 9 ], [ 23, 34, 90, 2000 ] ];
 let output = input.reduce((complete, next) => complete.concat(next), []) // to flatten
      .sort((a,b) => a-b) //to sort
</code>```

according to this article for big arrays google's V8 engine uses Quicksort, which takes roughly O(n.log(n))

Body:
I'm having trouble merging N unsorted arrays into 1 sorted array in JavaScript.

I know I can quickly concat then sort, but efficiency is important here.

I have arrays I'm getting back from an api (I can't ensure they arrive sorted) that need to end up in 1 sorted array. My first instinct was to try and not reinvent the wheel and try to find a way to reliably sort these into an output array. I figured I would try to sort each one, and then take advantage of the algorithm on GeeksForGeeks. This requires the arrays to be in sorted order, so I sort the arrays first individually

I haven't spent much time in C++, so I spent some time trying to reimplement this in JavaScript:

const TinyQueue = require('tinyqueue'); // const Heap = require('heap');

//typedef pair<int, pair<int, int> > ppi;
const pair = (val1, val2) => ({ first: val1, second: val2 });
const ppi = (val1, [val2a, val2b]) => pair(val1, pair(val2a, val2b));
//console.log(ppi('a', ['b', 'c'])) -> { first: 'a', second: { first: 'b', second: 'c' } }

// This function takes an array of arrays as an
// argument and all arrays are assumed to be
// sorted. It merges them together and prints
// the final sorted output.
function mergeKArrays(arr) {
  const output = [];
  queue = new TinyQueue();

  for (var i = 0, len = arr.length; i < len; i++) queue.push(ppi(arr[i][0], [i, 0]));

  while(queue.length) {
    let curr = queue.pop();
    // i ==> Array Number
    // j ==> Index in the array number
    let i = curr.second.first;
    let j = curr.second.second;

    output.unshift(curr.first);

    // The next element belongs to same array as current.
    if (j + 1 < arr[i].length) queue.push(ppi( arr[i][j + 1], [ i, j + 1]));
  }

  return output;
}
// -- Test Data --
const unsortedArrays = [
  [12, 2, 6],
  [9, 1],
  [2000, 23, 34, 90]
];
const sortedArrays = unsortedArrays.map(array => array.sort((a,b) => a - b));

console.log(sortedArrays);
const mergedArr = mergeKArrays(sortedArrays);

console.log(mergedArr);

The Geeks for Geeks algorithm. This code shared on repl.it.

So the input is [ [ 2, 6, 12 ], [ 1, 9 ], [ 23, 34, 90, 2000 ] ]

Expected output is [ 1, 2, 6, 9, 12, 23, 34, 90, 2000 ]

Actual output is [ 9, 2000, 1, 90, 12, 34, 6, 23, 2 ]

What is going wrong here? If this worked, is there a more efficient way to merge N unsorted arrays into 1 sorted one?

Body:
I would flatten the array first then sort

 let input = [ [ 2, 6, 12 ], [ 1, 9 ], [ 23, 34, 90, 2000 ] ];
 let output = input.reduce((complete, next) => complete.concat(next), []) // to flatten
      .sort((a,b) => a-b) //to sort

according to this article for big arrays google's V8 engine uses Quicksort, which takes roughly O(n.log(n))


问:
Including a variable value in a XSL select path is not working
I can't quite get my head around this.

So I have this external XML data file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<Translations xmlns="http://www.publictalksoftware.co.uk/msa">
  <en>
    <Chairman>Chairman</Chairman>
    <Conductor>Conductor</Conductor>
    <Hospitality>Hospitality</Hospitality>
    <Prayer>Prayer</Prayer>
    <PublicTalk>Public Talk</PublicTalk>
    <Reader>Reader</Reader>
    <ServiceTalk>Service Talk</ServiceTalk>
    <Speaker>Speaker</Speaker>
    <Theme>Theme</Theme>
    <WTStudy>Watchtower Study</WTStudy>
  </en>
</Translations>
</code>```

It is referenced in my master XSL script like this:

```<code><xsl:variable name="Translations" select="document('Workbook-S-140-Compact_2020_v2_Translations.XML')"/>
</code>```

I am able to extract values from this XML file like this:

```<code><xsl:value-of select="$Translations/msa:Translations/msa:en/msa:ServiceTalk"/>
</code>```

The above will pull out the English translation. Here is the thing, in my main XML data file I have the following at the top:

```<code><?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="Workbook-S-140-Compact_2020_v2.xsl"?>
<MeetingWorkBook>
    <Settings>
        <LanguageCode>en</LanguageCode>
        <Direction>ltr</Direction>
        <EditorMode>1</EditorMode>
        <ForeignGroupMode>0</ForeignGroupMode>
        <Now Day="20" Month="2" Year="2020"/>
    </Settings>
</code>```

Notice the LanguageCode entry? I wanted to make use of this so that my transformation was based on the language code. So I initially added a second variable to my XSL file:

```<code>  <xsl:variable name="LangCode">
    msa:<xsl:value-of select="//Settings//LanguageCode"/>
  </xsl:variable>
</code>```

And adjusting my path like this:

```<code><xsl:value-of select="$Translations/msa:Translations/{$LangCode}/msa:ServiceTalk"/>
</code>```

But it doesn't like it. I can't work out how to insert the language code into the path query. I have lots of these translation lines so I am looking for a simple solution if possible.

I have also tried saving the variable as:

```<code>  <xsl:variable name="LangCode">
    <xsl:value-of select="//Settings//LanguageCode"/>
  </xsl:variable>
</code>```

And then using:

```<code><xsl:value-of select="$Translations/msa:Translations/msa:{$LangCode}/msa:ServiceTalk"/>
</code>```

It still fails.

Is it possible to adjust this line:

```<code><xsl:variable name="Translations" select="document('Workbook-S-140-Compact_2020_v2_Translations.XML')"/>
</code>```

So that $Translations is pointing to the Translations/langcode node? Make sense?

答:
To expand on @Tomalak's correct answer, you made several mistakes:

Firstly:

```<code>  <xsl:variable name="LangCode">
    msa:<xsl:value-of select="//Settings//LanguageCode"/>
  </xsl:variable>
</code>```

There are several things wrong here. First, the whitespace that precedes "msa:" is part of the value of the variable, and will cause matching to fail. Secondly, using paths with multiple "//" operators is quite unnecessarily expensive. Thirdly, you're constructing a result tree fragment when it would be much simpler to construct a string:

```<code><xsl:variable name="LangCode" select="concat('msa:', //Settings/LanguageCode)"/>
</code>```

Next, you're misunderstanding the way variables work in XPath. Variables represent values, not parts of expression text (it's not a macro language like a shell script, it's an expression language like Javascript). Your variable can be used wherever you might use a string literal in quotes, for example [contains(., 'fred')] can become contains(., $var). It can't be used in place of parts of the expression where a string literal wouldn't be allowed. And curly braces for textual substitution work only in a few well-defined contexts, they are never used to replace parts of an expression (at least, not until you get to shadow variables in XSLT 3.0, but that's an advanced topic...)

Body:
I can't quite get my head around this.

So I have this external XML data file:

<?xml version="1.0" encoding="UTF-8"?>
<Translations xmlns="http://www.publictalksoftware.co.uk/msa">
  <en>
    <Chairman>Chairman</Chairman>
    <Conductor>Conductor</Conductor>
    <Hospitality>Hospitality</Hospitality>
    <Prayer>Prayer</Prayer>
    <PublicTalk>Public Talk</PublicTalk>
    <Reader>Reader</Reader>
    <ServiceTalk>Service Talk</ServiceTalk>
    <Speaker>Speaker</Speaker>
    <Theme>Theme</Theme>
    <WTStudy>Watchtower Study</WTStudy>
  </en>
</Translations>

It is referenced in my master XSL script like this:

<xsl:variable name="Translations" select="document('Workbook-S-140-Compact_2020_v2_Translations.XML')"/>

I am able to extract values from this XML file like this:

<xsl:value-of select="$Translations/msa:Translations/msa:en/msa:ServiceTalk"/>

The above will pull out the English translation. Here is the thing, in my main XML data file I have the following at the top:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="Workbook-S-140-Compact_2020_v2.xsl"?>
<MeetingWorkBook>
    <Settings>
        <LanguageCode>en</LanguageCode>
        <Direction>ltr</Direction>
        <EditorMode>1</EditorMode>
        <ForeignGroupMode>0</ForeignGroupMode>
        <Now Day="20" Month="2" Year="2020"/>
    </Settings>

Notice the LanguageCode entry? I wanted to make use of this so that my transformation was based on the language code. So I initially added a second variable to my XSL file:

  <xsl:variable name="LangCode">
    msa:<xsl:value-of select="//Settings//LanguageCode"/>
  </xsl:variable>

And adjusting my path like this:

<xsl:value-of select="$Translations/msa:Translations/{$LangCode}/msa:ServiceTalk"/>

But it doesn't like it. I can't work out how to insert the language code into the path query. I have lots of these translation lines so I am looking for a simple solution if possible.

I have also tried saving the variable as:

  <xsl:variable name="LangCode">
    <xsl:value-of select="//Settings//LanguageCode"/>
  </xsl:variable>

And then using:

<xsl:value-of select="$Translations/msa:Translations/msa:{$LangCode}/msa:ServiceTalk"/>

It still fails.

Is it possible to adjust this line:

<xsl:variable name="Translations" select="document('Workbook-S-140-Compact_2020_v2_Translations.XML')"/>

So that $Translations is pointing to the Translations/langcode node? Make sense?

Body:
To expand on @Tomalak's correct answer, you made several mistakes:

Firstly:

  <xsl:variable name="LangCode">
    msa:<xsl:value-of select="//Settings//LanguageCode"/>
  </xsl:variable>

There are several things wrong here. First, the whitespace that precedes "msa:" is part of the value of the variable, and will cause matching to fail. Secondly, using paths with multiple "//" operators is quite unnecessarily expensive. Thirdly, you're constructing a result tree fragment when it would be much simpler to construct a string:

<xsl:variable name="LangCode" select="concat('msa:', //Settings/LanguageCode)"/>

Next, you're misunderstanding the way variables work in XPath. Variables represent values, not parts of expression text (it's not a macro language like a shell script, it's an expression language like Javascript). Your variable can be used wherever you might use a string literal in quotes, for example [contains(., 'fred')] can become contains(., $var). It can't be used in place of parts of the expression where a string literal wouldn't be allowed. And curly braces for textual substitution work only in a few well-defined contexts, they are never used to replace parts of an expression (at least, not until you get to shadow variables in XSLT 3.0, but that's an advanced topic...)


答:
I don't think you need to care about efficiency in such a small grid (not even in a bigger one).

Simplest solution would be to check the current row and column for the value you're about to write into that cell, by simply iterating over the grid.

Title: Randomly Generate a unique Number grid


问:
How do I tell Alexa to prompt user for input
I need to tell alexa to prompt user for input then store that input in a variable to be used in my code.

InvocationName: send mail

Alexa: Tell me mail subject

User: Test email

Alexa: Okay, tell me message body.

User: This is just a sample test

Alexa, okay, tell me receiver email

User: test@gmail.com

Below is my intent schema:

```<code>{
    "interactionModel": {
        "languageModel": {
            "invocationName": "send mail",
            "intents": [
                {
                    "name": "AMAZON.CancelIntent",
                    "samples": []
                },
                {
                    "name": "AMAZON.HelpIntent",
                    "samples": []
                },
                {
                    "name": "AMAZON.StopIntent",
                    "samples": []
                },
                {
                    "name": "AMAZON.FallbackIntent",
                    "samples": []
                },
                {
                    "name": "AMAZON.NavigateHomeIntent",
                    "samples": []
                },
                {
                    "name": "SendMailIntent",
                    "slots": [
                        {
                            "name": "ReceiverEmail",
                            "type": "AMAZON.SearchQuery"
                        }
                    ],
                    "samples": [
                        "mail",
                        "send mail"
                    ]
                }
            ],
            "types": []
        },
        "dialog": {
            "intents": [
                {
                    "name": "SendMailIntent",
                    "confirmationRequired": false,
                    "prompts": {},
                    "slots": [
                        {
                            "name": "ReceiverEmail",
                            "type": "AMAZON.SearchQuery",
                            "confirmationRequired": false,
                            "elicitationRequired": true,
                            "prompts": {
                                "elicitation": "Elicit.Slot.838288524310.965699312002"
                            }
                        }
                    ]
                }
            ],
            "delegationStrategy": "ALWAYS"
        },
        "prompts": [
            {
                "id": "Elicit.Slot.838288524310.965699312002",
                "variations": [
                    {
                        "type": "PlainText",
                        "value": "Enter subject"
                    }
                ]
            }
        ]
    }
}

and below is the code I have been able to come up with:

</code>```

```<code>// sets up dependencies
const Alexa = require('ask-sdk-core');
const i18n = require('i18next');
const languageStrings = require('./languageStrings');

const SendMailHandler = {
  canHandle(handlerInput) {
   const request = handlerInput.requestEnvelope.request;
   // var code = this.event.request.intent.slots.code.value;
    //console.log(code)

    // checks request type
    return request.type === 'LaunchRequest'
      || (request.type === 'IntentRequest'
        && request.intent.name === 'SendMailIntent');
  },
  handle(handlerInput) {
    const speechText = 'Ok. Tell me the mail subject'

    const response =  handlerInput.responseBuilder
      .speak(speechText)
      .reprompt(speechText) // <--- Here is our reprompt
      .getResponse();
      console.log(response)
      return response;
  },
};

// Omitted default Alexa handlers
const skillBuilder = Alexa.SkillBuilders.custom();

exports.handler = skillBuilder
  .addRequestHandlers(
   SendMailHandler,
  )
  .lambda();
</code>```

答:
You should use dialog management with 2 slots.

As I can see currently you only collect one slot (ReceiverEmail) with dialoge management.
But you need also to create a slot for the text you want to send.
Later in your code you need to check if the dialogue is in status COMPLETED.

See the example https://github.com/alexa/skill-sample-nodejs-petmatch/ or this video: https://www.youtube.com/watch?v=u99WMljnQXI

Body:
I need to tell alexa to prompt user for input then store that input in a variable to be used in my code.

InvocationName: send mail

Alexa: Tell me mail subject

User: Test email

Alexa: Okay, tell me message body.

User: This is just a sample test

Alexa, okay, tell me receiver email

User: test@gmail.com

Below is my intent schema:

{
    "interactionModel": {
        "languageModel": {
            "invocationName": "send mail",
            "intents": [
                {
                    "name": "AMAZON.CancelIntent",
                    "samples": []
                },
                {
                    "name": "AMAZON.HelpIntent",
                    "samples": []
                },
                {
                    "name": "AMAZON.StopIntent",
                    "samples": []
                },
                {
                    "name": "AMAZON.FallbackIntent",
                    "samples": []
                },
                {
                    "name": "AMAZON.NavigateHomeIntent",
                    "samples": []
                },
                {
                    "name": "SendMailIntent",
                    "slots": [
                        {
                            "name": "ReceiverEmail",
                            "type": "AMAZON.SearchQuery"
                        }
                    ],
                    "samples": [
                        "mail",
                        "send mail"
                    ]
                }
            ],
            "types": []
        },
        "dialog": {
            "intents": [
                {
                    "name": "SendMailIntent",
                    "confirmationRequired": false,
                    "prompts": {},
                    "slots": [
                        {
                            "name": "ReceiverEmail",
                            "type": "AMAZON.SearchQuery",
                            "confirmationRequired": false,
                            "elicitationRequired": true,
                            "prompts": {
                                "elicitation": "Elicit.Slot.838288524310.965699312002"
                            }
                        }
                    ]
                }
            ],
            "delegationStrategy": "ALWAYS"
        },
        "prompts": [
            {
                "id": "Elicit.Slot.838288524310.965699312002",
                "variations": [
                    {
                        "type": "PlainText",
                        "value": "Enter subject"
                    }
                ]
            }
        ]
    }
}

and below is the code I have been able to come up with:

// sets up dependencies
const Alexa = require('ask-sdk-core');
const i18n = require('i18next');
const languageStrings = require('./languageStrings');

const SendMailHandler = {
  canHandle(handlerInput) {
   const request = handlerInput.requestEnvelope.request;
   // var code = this.event.request.intent.slots.code.value;
    //console.log(code)

    // checks request type
    return request.type === 'LaunchRequest'
      || (request.type === 'IntentRequest'
        && request.intent.name === 'SendMailIntent');
  },
  handle(handlerInput) {
    const speechText = 'Ok. Tell me the mail subject'

    const response =  handlerInput.responseBuilder
      .speak(speechText)
      .reprompt(speechText) // <--- Here is our reprompt
      .getResponse();
      console.log(response)
      return response;
  },
};

// Omitted default Alexa handlers
const skillBuilder = Alexa.SkillBuilders.custom();

exports.handler = skillBuilder
  .addRequestHandlers(
   SendMailHandler,
  )
  .lambda();


问:
Kotlin - Scroll Detection issue in Recyclerview
Using below code to check that whether RecyclerView reached to bottom or not..

Means Checking that last item of the Recyclerview is visible or not..

For that I have googled and added Scroll listener in Recyclerview.

Using below code:

```<code>MyRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
       override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
           super.onScrollStateChanged(recyclerView, newState)
       }

       override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
           super.onScrolled(recyclerView, dx, dy)
           if (!MyRecyclerView.canScrollVertically(1)) {
               Toast.makeText(mContext, "Last", Toast.LENGTH_LONG).show();
           }
       }
   })
</code>```

Here, I am trying to check that Recyclerview reached to bottom or not.

Toast is not displaying when I scroll recyclerview to the bottom.

But, Toast displayed suddenly when items in the recyclerview binds first time. It should toast only when user scroll up to the bottom of the Recyclerview.

What might be the issue ?
Please guide. Thanks.

答:
```<code>  rvPlayers?.addOnScrollListener(object : RecyclerView.OnScrollListener() {
        override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
            super.onScrolled(recyclerView, dx, dy)
            if (dy > 0) {
                if (isLastVisable()) {
                   //code here
                }
            }
        }
    })

 private fun isLastVisable(): Boolean {
    val layoutManager = rvPlayers.layoutManager as LinearLayoutManager
    val pos = layoutManager.findLastCompletelyVisibleItemPosition()
    val numItems = adapter.itemCount
    return (pos >= numItems - 1)
}
</code>```

Body:
Using below code to check that whether RecyclerView reached to bottom or not..

Means Checking that last item of the Recyclerview is visible or not..

For that I have googled and added Scroll listener in Recyclerview.

Using below code:

MyRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
       override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
           super.onScrollStateChanged(recyclerView, newState)
       }

       override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
           super.onScrolled(recyclerView, dx, dy)
           if (!MyRecyclerView.canScrollVertically(1)) {
               Toast.makeText(mContext, "Last", Toast.LENGTH_LONG).show();
           }
       }
   })

Here, I am trying to check that Recyclerview reached to bottom or not.

Toast is not displaying when I scroll recyclerview to the bottom.

But, Toast displayed suddenly when items in the recyclerview binds first time. It should toast only when user scroll up to the bottom of the Recyclerview.

What might be the issue ?
Please guide. Thanks.


问:
how do I properly set up data validation?
I have a DRF class which receives JSON date  and after it has been processed, create new database instances.

```<code>class CsvToDatabase(APIView):

    def post(self, request, format=None):
        data = request.data
        print()
        for _, vendor in data.items():
            v = Vendors(
                vendor_name=vendor['Vendor'],
                country=vendor['Country'],
                nda=vendor['NDA date'],

            )
            try:
                v.full_clean()
            except ValidationError as e:
                data = ({'status': str(e)})
                return Response(data, content_type='application/json')
            v.save()
        return Response({'received data': request.data,
                         'message': 'Vendors from vendors_list were successfully added to the database'})
</code>```

models.py

```<code>class Vendors(models.Model):
    COUNTRY_CHOICES = tuple(countries)

    ...
    country = models.CharField(max_length=45, choices=COUNTRY_CHOICES)
    nda = models.DateField(blank=True, null=True)
    ...
</code>```

tuple(countries) looks like:

```<code>(..., ('AR', 'Argentina'), ('AM', 'Armenia'), ('AW', 'Aruba'), ('AU', 'Australia'), ('AT', 'Austria'), ('AZ', 'Azerbaijan'), ('BS', 'Bahamas'), ('BH', 'Bahrain'), ('BD', 'Bangladesh'), ('BB', 'Barbados'), ('BY', 'Belarus'), ('BE', 'Belgium'), ...)
</code>```

Received JSON data may or may not contain the value of the nda field. An example of an incoming data format is as follows

```<code>{
    "1": {
        "Vendor": "Firstvendortestname",
        "Country": "Belgium,",
        "NDA date": "",
        "Primary Contact Name": "Jack Jhonson",
        "Primary Contact Email": "jack@gmail.com",
        "Secondary Contact Name": "Jack2 Jhonson",
        "Secondary Contact Email": "jack2@gmail.com",
        "Modules": "Module1, Module2"
    },
    "2": {
        "Vendor": "Secondvendortestname",
        "Country": "Belarus",
        "NDA date": "2019-12-24",
        "Primary Contact Name": "Sandra Bullock",
        "Primary Contact Email": "sandra@gmail.com",
        "Secondary Contact Name": "Sandra Bullock",
        "Secondary Contact Email": "sandra@gmail.com",
        "Modules": "Module1, Module2"
    }
}
</code>```

What's the problem.

A first one - "Country": "Belgium," get me error

```<code>{
    "status": "{'country': [\"Value 'Belgium' is not a valid choice.\"]}"
}
</code>```

But if I change to "Country": "BE," it works.

A second one - "NDA date": "", get me error

```<code>ValidationError at /api/v1/vendors/from_csv_create/
["'' value has an invalid date format. It must be in YYYY-MM-DD format."]

Request Method: POST
Request URL: http://127.0.0.1:8000/api/v1/vendors/from_csv_create/
Django Version: 2.2.9
....
.....
</code>```

But at models I have null=True and blank=True. And what is strange is that the second error is printed in text format instead of json as the first. Although in the exception, I specify return Response(data, content_type='application/json').

How do I get the ability to work with an empty nda field and set up my work with?

答:
For the 1st problem, it's because "Belgium" is not in your choices. Choice tuples are basically (accepted_value, human_readable_value). So when you write ("BE", "Belgium"), only "BE" will be considered as a valid choice. And it will be SHOWN as "Belgium" in your admin.

If you wanted to accept both (which might not be necessary), there are several ways to go:

Add more tuples : (("BE", "Belgium"), ("Belgium", "Belgium"))

Create a custom validator for the field

For your 2nd error "" is not valid date, it's because an empty string is not a valid value for a Date object in Django. Check out this topic, who had the same issue : DateTime Field shows invalid format error while passing empty value through form

Basically, you should either OMIT the field, or replace the "" value with None before pushing it

Body:
I have a DRF class which receives JSON date  and after it has been processed, create new database instances.

class CsvToDatabase(APIView):

    def post(self, request, format=None):
        data = request.data
        print()
        for _, vendor in data.items():
            v = Vendors(
                vendor_name=vendor['Vendor'],
                country=vendor['Country'],
                nda=vendor['NDA date'],

            )
            try:
                v.full_clean()
            except ValidationError as e:
                data = ({'status': str(e)})
                return Response(data, content_type='application/json')
            v.save()
        return Response({'received data': request.data,
                         'message': 'Vendors from vendors_list were successfully added to the database'})

models.py

class Vendors(models.Model):
    COUNTRY_CHOICES = tuple(countries)

    ...
    country = models.CharField(max_length=45, choices=COUNTRY_CHOICES)
    nda = models.DateField(blank=True, null=True)
    ...

tuple(countries) looks like:

(..., ('AR', 'Argentina'), ('AM', 'Armenia'), ('AW', 'Aruba'), ('AU', 'Australia'), ('AT', 'Austria'), ('AZ', 'Azerbaijan'), ('BS', 'Bahamas'), ('BH', 'Bahrain'), ('BD', 'Bangladesh'), ('BB', 'Barbados'), ('BY', 'Belarus'), ('BE', 'Belgium'), ...)

Received JSON data may or may not contain the value of the nda field. An example of an incoming data format is as follows

{
    "1": {
        "Vendor": "Firstvendortestname",
        "Country": "Belgium,",
        "NDA date": "",
        "Primary Contact Name": "Jack Jhonson",
        "Primary Contact Email": "jack@gmail.com",
        "Secondary Contact Name": "Jack2 Jhonson",
        "Secondary Contact Email": "jack2@gmail.com",
        "Modules": "Module1, Module2"
    },
    "2": {
        "Vendor": "Secondvendortestname",
        "Country": "Belarus",
        "NDA date": "2019-12-24",
        "Primary Contact Name": "Sandra Bullock",
        "Primary Contact Email": "sandra@gmail.com",
        "Secondary Contact Name": "Sandra Bullock",
        "Secondary Contact Email": "sandra@gmail.com",
        "Modules": "Module1, Module2"
    }
}

What's the problem.

A first one - "Country": "Belgium," get me error

{
    "status": "{'country': [\"Value 'Belgium' is not a valid choice.\"]}"
}

But if I change to "Country": "BE," it works.

A second one - "NDA date": "", get me error

ValidationError at /api/v1/vendors/from_csv_create/
["'' value has an invalid date format. It must be in YYYY-MM-DD format."]

Request Method: POST
Request URL: http://127.0.0.1:8000/api/v1/vendors/from_csv_create/
Django Version: 2.2.9
....
.....

But at models I have null=True and blank=True. And what is strange is that the second error is printed in text format instead of json as the first. Although in the exception, I specify return Response(data, content_type='application/json').

How do I get the ability to work with an empty nda field and set up my work with?


问:
how to get firebase time in firebase
I needed in my app firebase (server) time millisecond. because my local time will be change by mobile date time setting,

i will be see this question by not so helpful,
Flutter Firestore Server side Timestamp

```<code>var timestamp=FieldValue.serverTimestamp();

print("timestamp"+timestamp.toString());
</code>```

but they print below value

```<code>====>Instance of 'FieldValue'
</code>```

答:
Before reading the timestamp you have to set it to the server since you are generating it from there. According to this

serverTimestamp() Returns a sentinel for use with set() or update() to include a server-generated timestamp in the written data.

so first set it

```<code>Firestore.instance.collection('timestamp').document('docId').setData({'time' : FieldValue.serverTimestamp()});
</code>```

then get it using basic firestore query. Finally, check out this answer on the details of the why.

For more general way of getting timestamp

```<code>    getTimestamp() async{
      await Firestore.instance.collection('timestamp').document('docId').setData({'time' : FieldValue.serverTimestamp()});
      DocumentSnapshot doc = await Firestore.instance.collection('timestamp').document('docId').get();
      Timestamp timestamp = doc['time'];
      var timestampInMilliSeconds = timestamp.millisecondsSinceEpoch;
      return timestampInMilliSeconds;
      /* here you can call setState to your own variable before returning and keep in mind this method is async so it will return a Future.  */
    }
</code>```

Title: how to get firebase time in firebase

Body:
I needed in my app firebase (server) time millisecond. because my local time will be change by mobile date time setting,

i will be see this question by not so helpful,
Flutter Firestore Server side Timestamp

var timestamp=FieldValue.serverTimestamp();

print("timestamp"+timestamp.toString());

but they print below value

====>Instance of 'FieldValue'

Body:
Before reading the timestamp you have to set it to the server since you are generating it from there. According to this

serverTimestamp() Returns a sentinel for use with set() or update() to include a server-generated timestamp in the written data.

so first set it

Firestore.instance.collection('timestamp').document('docId').setData({'time' : FieldValue.serverTimestamp()});

then get it using basic firestore query. Finally, check out this answer on the details of the why.

For more general way of getting timestamp

    getTimestamp() async{
      await Firestore.instance.collection('timestamp').document('docId').setData({'time' : FieldValue.serverTimestamp()});
      DocumentSnapshot doc = await Firestore.instance.collection('timestamp').document('docId').get();
      Timestamp timestamp = doc['time'];
      var timestampInMilliSeconds = timestamp.millisecondsSinceEpoch;
      return timestampInMilliSeconds;
      /* here you can call setState to your own variable before returning and keep in mind this method is async so it will return a Future.  */
    }


问:
Ionic native push registration format changed?
I am not sure why but it seems that the interface for push registration changed?

My app follows the logic from

https://ionicframework.com/docs/v3/native/push/

with

```<code>pushObject.on('registration').subscribe((registration: any) => console.log('Device registered', registration));
</code>```

where registration used to be of below type

```<code>export interface PushDevice{
    registrationId: string;
    registrationType: string;
}
</code>```

but now I am getting

```<code>{"registrationId":"{length=32,bytes=0x459ca46ab66f4fe790220809215176d6...21b3436d13e78c64}","registrationType":"APNS"}
</code>```

registrationID used to be a string, but now is a dictionary. How shall I handle this ID now? I have to convert it to a push token somehow... What changed? I looked into the phone gap plugin code but I can not find it...
https://github.com/phonegap/phonegap-plugin-push/blob/master/src/ios/PushPlugin.m

答:
I faced the same issue in my ionic 1 app. Had to upgrade version of push plugin to 2.3.0 from 2.2.3. Moreover i also upgraded cordova-support-google-services to 1.3.2 to make it work. Although it was related to android but still had to do it. This plugin (phonegap-plugin-multidex) should have a version greater than or equal to 1.0.0
The plugins through which push notifications work fine for me are as follows:

phonegap-plugin-multidex 1.0.0 "Multidex"

phonegap-plugin-push 2.3.0 "PushPlugin"

cordova-support-google-services 1.3.2 "cordova-support-google-services"

Hoepfully this helps

Body:
I am not sure why but it seems that the interface for push registration changed?

My app follows the logic from

https://ionicframework.com/docs/v3/native/push/

with

pushObject.on('registration').subscribe((registration: any) => console.log('Device registered', registration));

where registration used to be of below type

export interface PushDevice{
    registrationId: string;
    registrationType: string;
}

but now I am getting

{"registrationId":"{length=32,bytes=0x459ca46ab66f4fe790220809215176d6...21b3436d13e78c64}","registrationType":"APNS"}

registrationID used to be a string, but now is a dictionary. How shall I handle this ID now? I have to convert it to a push token somehow... What changed? I looked into the phone gap plugin code but I can not find it...
https://github.com/phonegap/phonegap-plugin-push/blob/master/src/ios/PushPlugin.m


问:
jQuery Show/Hide Div when Section is in Viewport
My code at the moment is here: http://www.jaygeorge.co.uk/gwennan-sage

You'll see two green arrows that are in a fixed position at the bottom of the page.
I'm having trouble getting jQuery to hide these divs (#timeline-buttons) when the Timeline section is NOT in view, preferably using the fade() technique.

I've tried a Viewport plugin but can't get it to work properly with if statements, I'm sure it can be done with normal jQuery by measuring div heights somehow.

Any advice appreciated, thanks in advance.

答: Move these arrows into #gwennan-header and remove the fixed css attribute and set the z-index. That way you won't need any Javascript at all.


问:
How to paste the text from clipboard into textbox and assert in testcafe?
I have a text field in a table and I want to copy the contents of the clipboard to textfield

As paste option is not available in testcafe, so tried the below:

```<code>const execPaste = ClientFunction(() => document.execCommand("paste"));
t..click(Selector(".table > tbody > tr:nth-child(5) > td:nth-child(3)"))
    .typeText(
      Selector(".table > tbody > tr:nth-child(5) > td:nth-child(3)"),
      JSON.stringify(execPaste())
    );
console.log(JSON.stringify(execPaste()));
</code>```

and in the console log I see "{"_then":[],"_taskPromise":null}" and not the value which is copied from the clipboard

Please help

答:
The ClientFunction returns a Promise, so to get the ClientFunction value, you need to await this promise:

JSON.stringify(await execPaste())
```

<p>To paste a value from the clipboard, you can focus the element where you are going to paste the value and then call the <code>document.execCommand("paste")</code> method. If I understand your code correctly, the first <code>click</code> is supposed to focus the target element.
Please try to change your code example in the following way:</p>

<pre class="lang-js prettyprint-override"><code>    const execPaste = ClientFunction(() => document.execCommand("paste"));

    await t.click(Selector(".table > tbody > tr:nth-child(5) > td:nth-child(3)"));
    await execPaste();
</code>```

Body:
I have a text field in a table and I want to copy the contents of the clipboard to textfield

As paste option is not available in testcafe, so tried the below:

const execPaste = ClientFunction(() => document.execCommand("paste"));
t..click(Selector(".table > tbody > tr:nth-child(5) > td:nth-child(3)"))
    .typeText(
      Selector(".table > tbody > tr:nth-child(5) > td:nth-child(3)"),
      JSON.stringify(execPaste())
    );
console.log(JSON.stringify(execPaste()));

and in the console log I see "{"_then":[],"_taskPromise":null}" and not the value which is copied from the clipboard

Please help

Body:
The ClientFunction returns a Promise, so to get the ClientFunction value, you need to await this promise:

JSON.stringify(await execPaste())

To paste a value from the clipboard, you can focus the element where you are going to paste the value and then call the document.execCommand("paste") method. If I understand your code correctly, the first click is supposed to focus the target element.
Please try to change your code example in the following way:

    const execPaste = ClientFunction(() => document.execCommand("paste"));

    await t.click(Selector(".table > tbody > tr:nth-child(5) > td:nth-child(3)"));
    await execPaste();


问:
React. How to pass an arg to a function called by an onClick without autotriggering it
I have this piece of code.
Where the problem I am facing is that  is missing a prop which I want to be an id, obtained inside the map function.
Since I am unable to find a way to send the id to the component outside map, I figured I would do this:

This is my render function

```<code>render() {
    var users = this.state.userList;

    const Table = Reactable.Table,
          Td = Reactable.Td,
          Tr = Reactable.Tr;

    if (users.length === 0) {
        return <p>loading</p>
    }

    return (

        <div class="maincontainer">
            <div className="content-landing">

                <Table
                     className="table"
                     filterable={['Email']}
                     itemsPerPage={8}
                     currentPage={0}
                     sortable={true}
                >
                    {users.map((row) => {
                        return (

                            <Tr className={row.className}>
                                <Td column="Email">{row.email}</Td>
                                <Td column="Edit" ><FontAwesomeIcon className="editIcon" onClick={this.showModal(row.id)} icon={faEdit} /></Td> //----THIS.SHOWMODAL IS BEING AUTOEXECUTED WITHOUT ACCOUNTING FOR THE CLICKING

                            </Tr>

                        )
                    })}
                </Table>
                 <EditUserModal show={this.state.showModal} close={this.closeModal} row={this.state.rowId}/> //---I WANT THIS TO RECEIVE A row.id FROM THE ABOVE MAP

            </div>
        </div>

    )
}
</code>```

I have written a couple comments in the parts where I want to make the changes.
I also thought about putting <EditUserModal> , inside the  , but since its an external npm module it crashes, it only admits text.

So my solution was, to pass the row.id to the showModal function, and try to set is a state from there.

```<code>showModal(rowId) {
    // console.log("showmodal state before any click")
    // console.log(this.state.showModal)
    console.log("triggered show modal")
    console.log(rowId)
    this.setState({
        showModal: true,
        rowId: rowId
    }, () => {
        // console.log("clicked show modal")
        // console.log(this.state.showModal)
    });

}
</code>```

I think it should work, but since the function has a () , it auto executes without waiting for any click, making my app to crash.

答:
In your code you are executing the function directly: this.showModal(row.id).

You have to use a callBack function to pass row.id something like:

onClick={()=> this.showModal(row.id)}

This should solve your problem.

Body:
I have this piece of code.
Where the problem I am facing is that  is missing a prop which I want to be an id, obtained inside the map function.
Since I am unable to find a way to send the id to the component outside map, I figured I would do this:

This is my render function

render() {
    var users = this.state.userList;

    const Table = Reactable.Table,
          Td = Reactable.Td,
          Tr = Reactable.Tr;

    if (users.length === 0) {
        return
loading

    }

    return (

                    {users.map((row) => {
                        return (

                                {row.email}
                                <FontAwesomeIcon className="editIcon" onClick={this.showModal(row.id)} icon={faEdit} />	 //----THIS.SHOWMODAL IS BEING AUTOEXECUTED WITHOUT ACCOUNTING FOR THE CLICKING

                        )
                    })}

                 <EditUserModal show={this.state.showModal} close={this.closeModal} row={this.state.rowId}/> //---I WANT THIS TO RECEIVE A row.id FROM THE ABOVE MAP

    )
}

I have written a couple comments in the parts where I want to make the changes.
I also thought about putting <EditUserModal> , inside the  , but since its an external npm module it crashes, it only admits text.

So my solution was, to pass the row.id to the showModal function, and try to set is a state from there.

showModal(rowId) {
    // console.log("showmodal state before any click")
    // console.log(this.state.showModal)
    console.log("triggered show modal")
    console.log(rowId)
    this.setState({
        showModal: true,
        rowId: rowId
    }, () => {
        // console.log("clicked show modal")
        // console.log(this.state.showModal)
    });

}

I think it should work, but since the function has a () , it auto executes without waiting for any click, making my app to crash.


问:
How to look into code generated by webpack programmatically to search for strings such as Component, useState, or render?
The code expected to check if a webpage is using ReactJS:

```<code>if(!!window.React ||
   !!document.querySelector('[data-reactroot], [data-reactid]'))
  console.log('React.js');
</code>```

doesn't work for a simple app created by using npx create-react-app my-app.

Can we look into code generated by webpack, to determine if it has React code in it?  For example, is it true that even if the code is obfuscated, some API or property / method names will stay there, such as Component, render, useState, and useEffect?  Is there a way to look into webpack generated code programmatically to search for these strings?  Can we do it once and simply in dev console, without searching in all the different script files? Some website may be linking to 35 .js files).

(and better yet, if we can find out the version number.  There is a version property in the React object but I am not sure if it'd be obfuscated -- property names probably are not obfuscated?)

答: You should take a look at source-map, which allows you to include the original source mapped to the 'obfuscated' webpack code. This will allow you to see the original source code in your brower, and facilitate debugging.

Body:
The code expected to check if a webpage is using ReactJS:

if(!!window.React ||
   !!document.querySelector('[data-reactroot], [data-reactid]'))
  console.log('React.js');

doesn't work for a simple app created by using npx create-react-app my-app.

Can we look into code generated by webpack, to determine if it has React code in it?  For example, is it true that even if the code is obfuscated, some API or property / method names will stay there, such as Component, render, useState, and useEffect?  Is there a way to look into webpack generated code programmatically to search for these strings?  Can we do it once and simply in dev console, without searching in all the different script files? Some website may be linking to 35 .js files).

(and better yet, if we can find out the version number.  There is a version property in the React object but I am not sure if it'd be obfuscated -- property names probably are not obfuscated?)


问:
Gitlab pipeline description doesn't match as expected
I am trying to write my first GitLab pipeline description. I use the needs parameter, and I still don't know why I get this mashed connection setup. Does anyone know what I am doing wrong? Here is what I want to achieve`.

But instead this is what I get:

```<code>foo:
    stage: build

bar:
    stage: build

foo-test:
    stage: test
    needs: ["foo"]

bar-test:
    stage: test
    needs: ["bar"]
</code>```

答:
Nothing is wrong with this. You should be seeing that bar-test starts immediately after bar is done.

The UI is currently going through an overhaul as they released this before doing that, hence you're still seeing the joined up pipeline graph.

There's an open issue discussing how to resolve this for the future on GitLab.

Body:
I am trying to write my first GitLab pipeline description. I use the needs parameter, and I still don't know why I get this mashed connection setup. Does anyone know what I am doing wrong? Here is what I want to achieve`.

But instead this is what I get:

foo:
    stage: build

bar:
    stage: build

foo-test:
    stage: test
    needs: ["foo"]

bar-test:
    stage: test
    needs: ["bar"]


问:
Given that i have loop my worksheets to produce some data , how to sort these data in a more organised manner?
So how my program works is that it will loop through all these worksheets to find invalid/fail data and after that the final result will be paste starting from row 1 column A. The count/countini/countinv represents the number of rel/initial/invalid fails respectively. Lets just assume i have 4 worksheets namely "devicea","deviceb","devicec" and "deviced" to loop on to get the number of rel/initial/invalid fails data (the numbers shown on the extreme left of column A) in each worksheet. How can i extract the worksheet name that lies in the same cell as the count's name like example if count's name is "rel"(at column A row5), how do i extract the name of the worksheet device d not just for my case but for all cases and organise them like the one i shown in after portion of the picture?

```<code>If Count >= 1 Then
Sheets(1).Cells(Rows.Count, 19).End(xlUp).Offset(1, 0) = Count & " REL Failures in " & ActiveSheet.Name & " !"

If countini >= 1 Then
Sheets(1).Cells(Rows.Count, 19).End(xlUp).Offset(1, 0) = countini & " Initial Failures in " & ActiveSheet.Name & " !"
end if

If countinv >= 1 Then
Sheets(1).Cells(Rows.Count, 19).End(xlUp).Offset(1, 0) = countinv & " Invalid Data points in " & ActiveSheet.Name & " !"
endif
</code>```

' ^ the above chunk of lines used to generate output at column A. Just need to know the variables; Count = no of rel failures, countini = no of initial failures, countinv = no of invalid data points. Well the below codes are the one that i am concern and need help for it..

```<code>Dim lastrow1 As Long

lastrow1 = Sheets(1).Range("A" & Rows.Count).End(xlUp).Row

For Row = 2 To lastrow1

mytext1 = Count & Sheets(1).Range("A" & Row).Value
' for the case of rel fails

If mytext1(2) = "rel" Then

'get the worksheetname that lies the same cell as "REL"
mytext1(4)=
</code>```

答:
This is what I meant in my comment, just create the table at the same time as the text on the left. I assume Count/countini/countinv are not empty but instead 0? If not, you need to do an if statement or something.</p>

```<code>If Count >= 1 Then
Sheets(1).Cells(Rows.Count, 19).End(xlUp).Offset(1, 0) = Count & " REL Failures in " & ActiveSheet.Name & " !"
'You sure, you dont need an end if here?

If countini >= 1 Then
Sheets(1).Cells(Rows.Count, 19).End(xlUp).Offset(1, 0) = countini & " Initial Failures in " & ActiveSheet.Name & " !"
end if

If countinv >= 1 Then
Sheets(1).Cells(Rows.Count, 19).End(xlUp).Offset(1, 0) = countinv & " Invalid Data points in " & ActiveSheet.Name & " !"
endif

'This creates the table
Sheets(1).Cells(Rows.Count, 3).End(xlUp).Offset(1, 0) = ActiveSheet.Name

'edited in after your comment:
If Count Like "" Then Count = 0
If countini Like "" Then countini = 0
If countinv Like "" Then countinv = 0

Sheets(1).Cells(Rows.Count, 4).End(xlUp).Offset(1, 0) = Count
Sheets(1).Cells(Rows.Count, 5).End(xlUp).Offset(1, 0) = countini
Sheets(1).Cells(Rows.Count, 6).End(xlUp).Offset(1, 0) = countinv
</code>```

Body:
So how my program works is that it will loop through all these worksheets to find invalid/fail data and after that the final result will be paste starting from row 1 column A. The count/countini/countinv represents the number of rel/initial/invalid fails respectively. Lets just assume i have 4 worksheets namely "devicea","deviceb","devicec" and "deviced" to loop on to get the number of rel/initial/invalid fails data (the numbers shown on the extreme left of column A) in each worksheet. How can i extract the worksheet name that lies in the same cell as the count's name like example if count's name is "rel"(at column A row5), how do i extract the name of the worksheet device d not just for my case but for all cases and organise them like the one i shown in after portion of the picture?

If Count >= 1 Then
Sheets(1).Cells(Rows.Count, 19).End(xlUp).Offset(1, 0) = Count & " REL Failures in " & ActiveSheet.Name & " !"

If countini >= 1 Then
Sheets(1).Cells(Rows.Count, 19).End(xlUp).Offset(1, 0) = countini & " Initial Failures in " & ActiveSheet.Name & " !"
end if

If countinv >= 1 Then
Sheets(1).Cells(Rows.Count, 19).End(xlUp).Offset(1, 0) = countinv & " Invalid Data points in " & ActiveSheet.Name & " !"
endif

' ^ the above chunk of lines used to generate output at column A. Just need to know the variables; Count = no of rel failures, countini = no of initial failures, countinv = no of invalid data points. Well the below codes are the one that i am concern and need help for it..

Dim lastrow1 As Long

lastrow1 = Sheets(1).Range("A" & Rows.Count).End(xlUp).Row

For Row = 2 To lastrow1

mytext1 = Count & Sheets(1).Range("A" & Row).Value
' for the case of rel fails

If mytext1(2) = "rel" Then

'get the worksheetname that lies the same cell as "REL"
mytext1(4)=

Body:
This is what I meant in my comment, just create the table at the same time as the text on the left. I assume Count/countini/countinv are not empty but instead 0? If not, you need to do an if statement or something.

If Count >= 1 Then
Sheets(1).Cells(Rows.Count, 19).End(xlUp).Offset(1, 0) = Count & " REL Failures in " & ActiveSheet.Name & " !"
'You sure, you dont need an end if here?

If countini >= 1 Then
Sheets(1).Cells(Rows.Count, 19).End(xlUp).Offset(1, 0) = countini & " Initial Failures in " & ActiveSheet.Name & " !"
end if

If countinv >= 1 Then
Sheets(1).Cells(Rows.Count, 19).End(xlUp).Offset(1, 0) = countinv & " Invalid Data points in " & ActiveSheet.Name & " !"
endif

'This creates the table
Sheets(1).Cells(Rows.Count, 3).End(xlUp).Offset(1, 0) = ActiveSheet.Name

'edited in after your comment:
If Count Like "" Then Count = 0
If countini Like "" Then countini = 0
If countinv Like "" Then countinv = 0

Sheets(1).Cells(Rows.Count, 4).End(xlUp).Offset(1, 0) = Count
Sheets(1).Cells(Rows.Count, 5).End(xlUp).Offset(1, 0) = countini
Sheets(1).Cells(Rows.Count, 6).End(xlUp).Offset(1, 0) = countinv


问:
Response.isSuccessfull() is false
Help me out.
I am using retrofit for my project and I am totally new on it. I am getting the following error. Why I am getting a false response?

```<code>2020-02-20 15:35:26.230 22602-22602/q.goaldiggers.auth_api_testing
D/Ayush: Response
2020-02-20 15:35:26.230 22602-22602/q.goaldiggers.auth_api_testing
D/Ayush:
Response{protocol=http/1.1, code=402, message=Payment Required,
url=https://quizziyapa.herokuapp.com/getTopics}
2020-02-20 15:35:26.230 22602-22602/q.goaldiggers.auth_api_testing
D/Ayush: Payment Required
2020-02-20 15:35:26.230 22602-22602/q.goaldiggers.auth_api_testing
D/Ayush: okhttp3.ResponseBody$1@647c751
2020-02-20 15:35:26.230 22602-22602/q.goaldiggers.auth_api_testing
D/Ayush: null
2020-02-20 15:35:26.230 22602-22602/q.goaldiggers.auth_api_testing
D/Ayush: false
2020-02-20 15:35:26.230 22602-22602/q.goaldiggers.auth_api_testing
D/Ayush: retrofit2.OkHttpCall$NoContentResponseBody@4f0bbb6
[Error][1]
</code>```

JSON Structure

This is my json structure.

```<code>{
    "topics": [
        {
            "_id": 2,
            "topic": "abc",
            "imageUrl": "abc12345"
        },
        {
            "_id": 3,
            "topic": "abc",
            "imageUrl": "abc12345"
        }
    ]
}
</code>```

Topic.java

My Model class

```<code>public class Topic {
    int _id;
    String topic;
    String imageUrl;

    public Topic(int _id, String topic, String imageUrl) {
        this._id = _id;
        this.topic = topic;
        this.imageUrl = imageUrl;
    }

    public int getId() {
        return _id;
    }

    public String getTopic() {
        return topic;
    }

    public String getImageUrl() {
        return imageUrl;
    }
}
</code>```

TopicResponse.java

JSON response class

```<code>public class TopicResponse {
    @SerializedName("topics")
    Topic[] topics;

    public TopicResponse(Topic[] topics) {
        this.topics = topics;
    }

    public Topic[] getTopics() {
        return topics;
    }
}
</code>```

IUserApi.java (API Interface)

```<code>public interface IUserApi {
    @GET("getTopics")
    Call<TopicResponse> getTop();
}
</code>```

MainActivity.java

```<code>Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://quizziyapa.herokuapp.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        IUserApi api =  retrofit.create(IUserApi.class);
        Call<TopicResponse> call= api.getTop();
        call.enqueue(new Callback<TopicResponse>() {
            @Override
            public void onResponse(Call<TopicResponse> call, Response<TopicResponse> response) {
                Log.d("Ayush", "Response");
                Log.d("Ayush", String.valueOf(response));
                Log.d("Ayush", String.valueOf(response.message()));
                Log.d("Ayush", String.valueOf(response.errorBody()));
                Log.d("Ayush", String.valueOf(response.body()));
                Log.d("Ayush", String.valueOf(response.isSuccessful()));
                Log.d("Ayush", String.valueOf(response.raw().body()));
            }

            @Override
            public void onFailure(Call<TopicResponse> call, Throwable t) {
                Log.d("Ayush", "Failed \n"+t.getMessage());
            }
        });
</code>```

Help me out what should I do to solve this issue?

答:
Well, from the looks of it, the problem is not with the code. The response you are receiving is not a success message rather a 402 errorCode with the message stating "Payment Required".

The reason for this as per the official docs of the API you are using says

either the account has become delinquent as a result of non-payment, or the account’s payment method must be confirmed to continue

Check the image below for reference.

.

So basically its the server returning you an error code. and your response.isSuccessful will ultimately be false unless you get a success message in response i.e one of the statuses shown in the image.

Title: Response.isSuccessfull() is false

Body:
Help me out.
I am using retrofit for my project and I am totally new on it. I am getting the following error. Why I am getting a false response?

2020-02-20 15:35:26.230 22602-22602/q.goaldiggers.auth_api_testing
D/Ayush: Response
2020-02-20 15:35:26.230 22602-22602/q.goaldiggers.auth_api_testing
D/Ayush:
Response{protocol=http/1.1, code=402, message=Payment Required,
url=https://quizziyapa.herokuapp.com/getTopics}
2020-02-20 15:35:26.230 22602-22602/q.goaldiggers.auth_api_testing
D/Ayush: Payment Required
2020-02-20 15:35:26.230 22602-22602/q.goaldiggers.auth_api_testing
D/Ayush: okhttp3.ResponseBody$1@647c751
2020-02-20 15:35:26.230 22602-22602/q.goaldiggers.auth_api_testing
D/Ayush: null
2020-02-20 15:35:26.230 22602-22602/q.goaldiggers.auth_api_testing
D/Ayush: false
2020-02-20 15:35:26.230 22602-22602/q.goaldiggers.auth_api_testing
D/Ayush: retrofit2.OkHttpCall$NoContentResponseBody@4f0bbb6
[Error][1]

JSON Structure

This is my json structure.

{
    "topics": [
        {
            "_id": 2,
            "topic": "abc",
            "imageUrl": "abc12345"
        },
        {
            "_id": 3,
            "topic": "abc",
            "imageUrl": "abc12345"
        }
    ]
}

Topic.java

My Model class

public class Topic {
    int _id;
    String topic;
    String imageUrl;

    public Topic(int _id, String topic, String imageUrl) {
        this._id = _id;
        this.topic = topic;
        this.imageUrl = imageUrl;
    }

    public int getId() {
        return _id;
    }

    public String getTopic() {
        return topic;
    }

    public String getImageUrl() {
        return imageUrl;
    }
}

TopicResponse.java

JSON response class

public class TopicResponse {
    @SerializedName("topics")
    Topic[] topics;

    public TopicResponse(Topic[] topics) {
        this.topics = topics;
    }

    public Topic[] getTopics() {
        return topics;
    }
}

IUserApi.java (API Interface)

public interface IUserApi {
    @GET("getTopics")
    Call<TopicResponse> getTop();
}

MainActivity.java

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://quizziyapa.herokuapp.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        IUserApi api =  retrofit.create(IUserApi.class);
        Call<TopicResponse> call= api.getTop();
        call.enqueue(new Callback<TopicResponse>() {
            @Override
            public void onResponse(Call<TopicResponse> call, Response<TopicResponse> response) {
                Log.d("Ayush", "Response");
                Log.d("Ayush", String.valueOf(response));
                Log.d("Ayush", String.valueOf(response.message()));
                Log.d("Ayush", String.valueOf(response.errorBody()));
                Log.d("Ayush", String.valueOf(response.body()));
                Log.d("Ayush", String.valueOf(response.isSuccessful()));
                Log.d("Ayush", String.valueOf(response.raw().body()));
            }

            @Override
            public void onFailure(Call<TopicResponse> call, Throwable t) {
                Log.d("Ayush", "Failed \n"+t.getMessage());
            }
        });

Help me out what should I do to solve this issue?


问:
using Recyclerview in fragment and coroutines not work
hi im using recyclerview in a fragment and coroutine, but recyclerview not update and is empty

this is my code that fetch data from web and i wrote that in OnCreateView

```<code>launch {
            val operation = async(Dispatchers.IO) {
                Log.d("asdasdasd", "start")
                var doc: Document = Jsoup.connect("http://5743.zanjan.medu.ir").timeout(0).maxBodySize(0).ignoreHttpErrors(true).get()
                val table: Elements = doc.select("table[class=\"table table-striped table-hover\"]")
                for (myTable in table) {
                    val rows: Elements = myTable.select("tr")
                    for (i in 1 until rows.size) {
                        val row: Element = rows.get(i)
                        val cols: Elements = row.select("td")
                        val href: Elements = row.select("a")
                        val strhref: String = href.attr("href")
                        itemsData.add(CircularModel(cols.get(2).text(),strhref,"2019",""))
                    }
                }
            }
            operation.await() // wait for result of I/O operation without blocking the main thread

            // update views
            activity?.runOnUiThread{
                adapter = CircularAdapter(itemsData, this@CircularFragment)
                adapter.notifyDataSetChanged()
                rc.adapter = adapter
            }
        }
</code>```

i checked and itemsData isnt empty but i dont know why recyclerview not updated

答: Try to call adapter.notifyDataSetChanged() after setting adapter to your Recycler

Body:
hi im using recyclerview in a fragment and coroutine, but recyclerview not update and is empty

this is my code that fetch data from web and i wrote that in OnCreateView

launch {
            val operation = async(Dispatchers.IO) {
                Log.d("asdasdasd", "start")
                var doc: Document = Jsoup.connect("http://5743.zanjan.medu.ir").timeout(0).maxBodySize(0).ignoreHttpErrors(true).get()
                val table: Elements = doc.select("table[class=\"table table-striped table-hover\"]")
                for (myTable in table) {
                    val rows: Elements = myTable.select("tr")
                    for (i in 1 until rows.size) {
                        val row: Element = rows.get(i)
                        val cols: Elements = row.select("td")
                        val href: Elements = row.select("a")
                        val strhref: String = href.attr("href")
                        itemsData.add(CircularModel(cols.get(2).text(),strhref,"2019",""))
                    }
                }
            }
            operation.await() // wait for result of I/O operation without blocking the main thread

            // update views
            activity?.runOnUiThread{
                adapter = CircularAdapter(itemsData, this@CircularFragment)
                adapter.notifyDataSetChanged()
                rc.adapter = adapter
            }
        }

i checked and itemsData isnt empty but i dont know why recyclerview not updated


问:
Simulate click with setTimeout in Javascript
How would I simulate a click event with setTimeout? Something like:</p>

```<code><script>
    window.onload=setTimeout(document.getElementById('mk1').click(),1000);
</script>

<a id="mk1" href="some url">click me</a>
</code>```

答:
Currently your code calls click() immediately and passes the return value to setTimeout. You instead want to pass a function reference to setTimeout:

```<code>window.onload = function() {
  setTimeout(function() {
    document.getElementById('mk1').click();
  }, 1000);
};
</code>```

Edit: As @ThiefMaster points out, you also want to pass a function to onload; even though it might seem to work otherwise, it wouldn't do what it really should be doing.

Body:
How would I simulate a click event with setTimeout? Something like:

click me

Body:
Currently your code calls click() immediately and passes the return value to setTimeout. You instead want to pass a function reference to setTimeout:

window.onload = function() {
  setTimeout(function() {
    document.getElementById('mk1').click();
  }, 1000);
};

Edit: As @ThiefMaster points out, you also want to pass a function to onload; even though it might seem to work otherwise, it wouldn't do what it really should be doing.


问:
How to export the queries from an ms-access database and closing the msaccess.exe-process afterwards?
This is the C# code I use to export the queries from an ms-access-database:

```<code>var appClass = new ApplicationClass();
appClass.Visible = false;
appClass.UserControl = false;
appClass.OpenCurrentDatabase(@"C:\RadLokal\trunk\Test\Access\Test.accdb", false, "");
var db = appClass.CurrentDb();
var queryDefs = db.QueryDefs;
for (int i = 0; i < queryDefs.Count; i++)
{
    var item = queryDefs[i];
    const string QueryPrefix = "Query_";
    var filename = Path.Combine(@"c:\Temp", QueryPrefix + item.Name + ".txt");
    File.WriteAllText(filename, item.SQL);
    item.Close();
}
db.Close();
appClass.CloseCurrentDatabase();
appClass.Quit(AcQuitOptionWrapper.acQuitSaveNone);
</code>```

The database is opened and all the queries are exported. But unfortionally a empty ms-access instance stays open. It is not possible to close this instance by hand (via the x). It can only get closed with the task manager. It is closed automaticly when I close the host process.

Things I tried to solve my problem:

Set the db to null and call GC.Collect afterwards => no change

comment out line: File.WriteAllText: => no change

set the queryDefs to null and call GC.Collect() afterwards => ms-access seems to close but the task manager says otherwise. There is still an open msaccess.exe process

答:
I had to set all my variables to null and call GC.Collect afterwards. This is the code that worked for me:</p>

```<code>var appClass = new ApplicationClass();
appClass.Visible = false;
appClass.UserControl = false;
appClass.OpenCurrentDatabase(@"C:\RadLokal\trunk\Test\Access\Test.accdb", false, "");
var db = appClass.CurrentDb();
var queryDefs = db.QueryDefs;
for (int i = 0; i < queryDefs.Count; i++)
{
    var item = queryDefs[i];
    const string QueryPrefix = "Query_";
    var filename = Path.Combine(@"c:\Temp", QueryPrefix + item.Name + ".txt");
    File.WriteAllText(filename, item.SQL);
    item.Close();
    item = null;
}
queryDefs = null;
db.Close();
db = null;

appClass.CloseCurrentDatabase();
appClass.Quit(AcQuitOption.acQuitSaveNone);
appClass = null;
GC.Collect();
</code>```

Body:
This is the C# code I use to export the queries from an ms-access-database:

var appClass = new ApplicationClass();
appClass.Visible = false;
appClass.UserControl = false;
appClass.OpenCurrentDatabase(@"C:\RadLokal\trunk\Test\Access\Test.accdb", false, "");
var db = appClass.CurrentDb();
var queryDefs = db.QueryDefs;
for (int i = 0; i < queryDefs.Count; i++)
{
    var item = queryDefs[i];
    const string QueryPrefix = "Query_";
    var filename = Path.Combine(@"c:\Temp", QueryPrefix + item.Name + ".txt");
    File.WriteAllText(filename, item.SQL);
    item.Close();
}
db.Close();
appClass.CloseCurrentDatabase();
appClass.Quit(AcQuitOptionWrapper.acQuitSaveNone);

The database is opened and all the queries are exported. But unfortionally a empty ms-access instance stays open. It is not possible to close this instance by hand (via the x). It can only get closed with the task manager. It is closed automaticly when I close the host process.

Things I tried to solve my problem:

Set the db to null and call GC.Collect afterwards => no change

comment out line: File.WriteAllText: => no change

set the queryDefs to null and call GC.Collect() afterwards => ms-access seems to close but the task manager says otherwise. There is still an open msaccess.exe process

Body:
I had to set all my variables to null and call GC.Collect afterwards. This is the code that worked for me:

var appClass = new ApplicationClass();
appClass.Visible = false;
appClass.UserControl = false;
appClass.OpenCurrentDatabase(@"C:\RadLokal\trunk\Test\Access\Test.accdb", false, "");
var db = appClass.CurrentDb();
var queryDefs = db.QueryDefs;
for (int i = 0; i < queryDefs.Count; i++)
{
    var item = queryDefs[i];
    const string QueryPrefix = "Query_";
    var filename = Path.Combine(@"c:\Temp", QueryPrefix + item.Name + ".txt");
    File.WriteAllText(filename, item.SQL);
    item.Close();
    item = null;
}
queryDefs = null;
db.Close();
db = null;

appClass.CloseCurrentDatabase();
appClass.Quit(AcQuitOption.acQuitSaveNone);
appClass = null;
GC.Collect();