答:
With this much information I can only assume that you are using some kind of json middleware that parse the incoming data.

Unfortunately, the data you sent via postman is not in a valid json format. Ironically enough, only valid number are accepted as value without the need of quotation mark (excluding array and  object).

A solution maybe to send the data as pure text to your api and then run in through your validation before converting it into a number.

You can verify the json format yourself here: https://jsonformatter.curiousconcept.com/

Title: Server crashes when testing app expecting a number. Express, NodeJS

Body:
Prevent server from crashing.

I am testing an API with Postman where I am expecting a number with or without decimal places.

But it happens that at the time of testing if I enter a sign like this in Postman: " ) " the server crashes automatically and it seems that it does not reach my validator.

Postman:

{
        "concept": "Text",
        "incomeAmount": 1)0000,
        "expenseAmount": 89,
        "description":"Text"
}

Failed response:

SyntaxError: Unexpected token ) in JSON at position 73
at JSON.parse ()
at parse (C:\project\node_modules\body-parser\lib\types\json.js:89:19)
at C:\project\node_modules\body-parser\lib\read.js:121:18
at invokeCallback (C:\project\node_modules\raw-body\index.js:224:16)
at done (C:\project\node_modules\raw-body\index.js:213:7)
at IncomingMessage.onEnd (C:\project\node_modules\raw-body\index.js:273:7)
at IncomingMessage.emit (node:events:402:35)
at IncomingMessage.emit (node:domain:475:12)
at endReadableNT (node:internal/streams/readable:1343:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21)

I am using express validator like this:

router.post('/new-income',
    [
        check('incomeAmount', 'El Monto del Ingreso debe ser Númerico').isNumeric().not().isEmpty(),
        check('expenseAmount', 'El Monto del Egreso debe ser Númerico').isNumeric().optional({ checkFalsy: true }),

    ],
    validation,
    newItem
);

And in the controller, I use Regex to verify that it is a positive number without symbols, but apparently neither the request nor the route arrives.

const regAmount = new RegExp('^[+]?([1-9][0-9]*(?:[\.][0-9]*)?|0*\.0*[1-9][0-9]*)(?:[eE][+-][0-9]+)?$');

        if (!regAmount.test(incomeAmount)) {
            return res.json ( {
                'msg': 'Only positive numbers without signs are allowed'
            } );
        }

Thanks for your help!


来源: stackexchange

问:
using setState inside the callback of another setState hook
When using useState hooks in React I have a scenario in which I would like to use it like so:

```<code>const [count, setCount] = useState(0);
const [page, setPage] = useState(0);

setCount(currentCount => {
  if (currentCount > 0) {
    setPage(0);
    return 0;
  }
  return currentCount + 1;
});
</code>```

Is it considered bad practice to use them nested like this? If so, are there any documentation on why this would be bad practice?

答:
Try something like this:</p>
```<code>const [count, setCount] = useState(0);
const [page, setPage] = useState(0);

useEffect(() => {
  if (count > 0) {
    setPage(0);
    setCount(0);
  }
}, [count]);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
When using useState hooks in React I have a scenario in which I would like to use it like so:

const [count, setCount] = useState(0);
const [page, setPage] = useState(0);

setCount(currentCount => {
  if (currentCount > 0) {
    setPage(0);
    return 0;
  }
  return currentCount + 1;
});

Is it considered bad practice to use them nested like this? If so, are there any documentation on why this would be bad practice?

Body:
Try something like this:

const [count, setCount] = useState(0);
const [page, setPage] = useState(0);

useEffect(() => {
  if (count > 0) {
    setPage(0);
    setCount(0);
  }
}, [count]);


答:
You are setting the count to undefined in the outer callback: you are not using the return keyword, and functions which exit without a returned value return undefined in JavaScript. In the inner invocation of the state setter, you are closing around the value of currentCount from the outer callback, and creating an expression which evaluates to 1 greater than that value.

This is potentially a bug, for two reasons:

undefined will cause a problem for any code in your program which relies on a number type for the state

State updates may be asynchronous, so it is not guaranteed that  the outer callback will finish execution either before or after the inner invocation of the state setter.

Instead this pattern will provide deterministic behavior:

setCount(currentCount => {
  const useZero = currentCount > 0;
  if (useZero) setPage(0);
  return useZero ? 0 : currentCount + 1;
});
```

Title: using setState inside the callback of another setState hook


问:
Associating certain file extension to my android application
I'm having trouble associating my custom file extension to my android application that I am developing. In my android manifest file I have the following:

```<code><data android:scheme="file" android:mimeType="*/*" android:pathPattern="*.*\\.myFileExt" />
<data android:scheme="content" android:mimeType="*/*" android:pathPattern="*.*\\.myFileExt" />
</code>```

It kinda works. Let me explain. I have a file in my gmail( sent a file to my self ), which has the proper extension, so when I download it from my phone's browser and click open, it opens my application correctly, but if I explore to that file path; where the file is located, and try to open it, my phone says no application can open this file-type.

Any ideas on how to solve this problem?

答:
After spending a few hours on this issue I finally came up with this solution (AAA is the file extension):

```<code><intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <data android:mimeType="*/*" />
    <data android:scheme="file" />
    <data android:host="*" />
    <data android:port="*" />
    <data android:pathPattern=".*..*..*..*..*.AAA" />
    <data android:pathPattern=".*..*..*..*.AAA" />
    <data android:pathPattern=".*..*..*.AAA" />
    <data android:pathPattern=".*..*.AAA" />
    <data android:pathPattern=".*.AAA" />
</intent-filter>
</code>```

The reason for all of those pathPattern is that if you have a dot in your file name the general form of .*.AAA will not match the filename.

ContentLicense: CC BY-SA 3.0

Body:
I'm having trouble associating my custom file extension to my android application that I am developing. In my android manifest file I have the following:

<data android:scheme="file" android:mimeType="*/*" android:pathPattern="*.*\\.myFileExt" />
<data android:scheme="content" android:mimeType="*/*" android:pathPattern="*.*\\.myFileExt" />

It kinda works. Let me explain. I have a file in my gmail( sent a file to my self ), which has the proper extension, so when I download it from my phone's browser and click open, it opens my application correctly, but if I explore to that file path; where the file is located, and try to open it, my phone says no application can open this file-type.

Any ideas on how to solve this problem?

Body:
After spending a few hours on this issue I finally came up with this solution (AAA is the file extension):

<intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <data android:mimeType="*/*" />
    <data android:scheme="file" />
    <data android:host="*" />
    <data android:port="*" />
    <data android:pathPattern=".*..*..*..*..*.AAA" />
    <data android:pathPattern=".*..*..*..*.AAA" />
    <data android:pathPattern=".*..*..*.AAA" />
    <data android:pathPattern=".*..*.AAA" />
    <data android:pathPattern=".*.AAA" />
</intent-filter>

The reason for all of those pathPattern is that if you have a dot in your file name the general form of .*.AAA will not match the filename.


问:
Switch Logo color in Dark Mode issue
I have a black color logo for my portfolio and i would like to switch it white when Dark Mode : https://www.paulinerouger.com/

I have tried:

Using CSS Variables

```<code><img class="nav_logo" src="assets/img/PR_logo.png" alt="original logo" />

body {
  --nav_logo: url(PR_logo.png) no-repeat;

}

body[data-theme="dark"] {
  --nav_logo: url(PR_logo_white.png) no-repeat;
}

.nav_logo {
    background: var(--nav_logo);
  }

</code>```

Using SVG

```<code>
 <img class="nav_logo" src="assets/img/PR_logo.svg" id="svg" alt="PR Logo">

.nav_logo {
    fill: currentColor;
}
</code>```

Unfortunately none of the above has worked.
Any suggestion?

Title: Switch Logo color in Dark Mode issue

Body:
I have a black color logo for my portfolio and i would like to switch it white when Dark Mode : https://www.paulinerouger.com/

I have tried:

Using CSS Variables

body {
  --nav_logo: url(PR_logo.png) no-repeat;

}

body[data-theme="dark"] {
  --nav_logo: url(PR_logo_white.png) no-repeat;
}

.nav_logo {
    background: var(--nav_logo);
  }

Using SVG

.nav_logo {
    fill: currentColor;
}

Unfortunately none of the above has worked.
Any suggestion?

Body:
Svg is just perfect – but wont't work within an <img> element.
You might consider these steps:

optimize your logo svg to inherit colors in a more consistent way

reduce your logo to fixed path elements i.e convert stroked elemnts like the inside bar/pipe to a solid shape/path to avoid accidental strike-width shifts

use an svg <use> concept – providing an <img> like usage i.e providing external svg files as reusable assets.

Example1

stripping hard coded svg properties for better global css styling:

function toggleDarkmode(){
  document.body.classList.toggle('darkmode')
}

* {
  box-sizing: border-box;
}

body {
  color: #000;
  transition: 0.3s;
}

.darkmode {
  color: #fff;
  background-color: #000;
}

/* just example css – not essential */

.nav__logo .logo {
  display: inline-block;
  width: 10em;
}

.svgAsset {
  position: absolute;
  width: 0;
  height: 0;
  overflow: hidden;
}

<div class="nav__logo">
  <p><button type="button" onclick="toggleDarkmode()">toggleDarkmode</button></p>
  <svg class="logo" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 375 375" fill="currentColor">
    <path d="M 187.382812 337.265625 C 148.582031 337.265625 112.046875 322.164062 84.628906 294.691406 C 57.152344 267.273438 42.050781 230.738281 42.050781 191.933594 C 42.050781 153.132812 57.152344 116.597656 84.628906 89.179688 C 112.046875 61.703125 148.582031 46.601562 187.382812 46.601562 C 226.1875 46.601562 262.722656 61.703125 290.140625 89.179688 C 317.613281 116.652344 332.714844 153.132812 332.714844 191.933594 C 332.714844 230.738281 317.613281 267.273438 290.140625 294.691406 C 262.722656 322.164062 226.1875 337.265625 187.382812 337.265625 Z M 187.382812 55.316406 C 150.90625 55.316406 116.574219 69.546875 90.785156 95.335938 C 64.996094 121.125 50.765625 155.457031 50.765625 191.933594 C 50.765625 228.414062 64.996094 262.742188 90.785156 288.53125 C 116.574219 314.324219 150.90625 328.554688 187.382812 328.554688 C 223.863281 328.554688 258.191406 314.324219 283.980469 288.53125 C 309.773438 262.742188 324.003906 228.414062 324.003906 191.933594 C 324.003906 155.457031 309.773438 121.125 283.980469 95.335938 C 258.191406 69.546875 223.863281 55.316406 187.382812 55.316406 Z M 187.382812 55.316406"></path>
    <path d="M 35.097656 -71.835938 L 8.824219 -71.835938 L 8.824219 0 L 19.292969 0 L 19.292969 -23.910156 L 35.097656 -23.910156 C 50.59375 -23.910156 58.390625 -35.816406 58.390625 -47.820312 C 58.390625 -59.828125 50.59375 -71.835938 35.097656 -71.835938 Z M 35.097656 -34.171875 L 19.292969 -34.171875 L 19.292969 -61.367188 L 35.097656 -61.367188 C 43.820312 -61.367188 48.128906 -54.59375 48.128906 -47.71875 C 48.128906 -40.945312 43.820312 -34.171875 35.097656 -34.171875 Z M 35.097656 -34.171875" transform="translate(97.282 227.676)"></path>
    <path d="M 34.996094 -36.429688 L 22.886719 -36.429688 L 22.886719 -31.503906 L 49.054688 0 L 62.496094 0 L 39.816406 -26.988281 C 52.132812 -29.144531 58.390625 -38.792969 58.390625 -48.949219 C 58.390625 -60.34375 50.59375 -72.757812 34.996094 -72.757812 L 8.824219 -72.757812 L 8.824219 0 L 19.085938 0 L 19.085938 -62.292969 L 34.996094 -62.292969 C 43.71875 -62.292969 48.027344 -55.109375 48.027344 -48.949219 C 48.027344 -42.691406 43.71875 -36.429688 34.996094 -36.429688 Z M 34.996094 -36.429688" transform="translate(216.811 227.676)"></path>
    <path transform="matrix(0 -9.7441 10.11111 0 187.491 250.21)" d="M -0.0000988013 0.0000885473 L 11.930592 0.0000885473" stroke="currentColor" stroke-width="1"></path>
  </svg>
</div>

all path related fill attributes are removed (resulting in a default fill="#000" / black)

svg parent element gets a fill="currentColor" – inherited to all children

the stroke based bar/pipe element gets a stroke="currentColor" rule

Example2

<svg><use href="#..."></svg> also works fine with external files

The next example takes an inlined svg as source but will also work fine with external file references like this (provided, these external files are available on the same domain):

  <svg>
    <use href="logo.svg#logo-symbol">
  </svg>

function toggleDarkmode(){
  document.body.classList.toggle('darkmode')
}

*{
  box-sizing:border-box;
}

body {
  color: #000;
  transition: 0.3s;
}

.darkmode {
  color: #fff;
  background-color: #000;
}

/* just example css – not essential */
.nav__logo .logo {
  display: inline-block;
  width: 10em;
}

.svgAsset{
  position:absolute;
  width:0;
  height:0;
  overflow:hidden;
}

<div class="nav__logo">
  <p><button type="button" onclick="toggleDarkmode()">toggleDarkmode</button></p>
  <svg class="logo logo-cropped" viewBox="0 0 100 100" >
    <use href="#logo-smaller" />
  </svg>
</div>

<svg class="svgAsset" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" aria-hidden="true">
  <symbol id="logo-smaller" viewBox="0 0 100 100" fill="currentColor">
    <path id="circle" d="M50 100c-27.6 0-50-22.4-50-50c0-27.6 22.4-50 50-50c27.6 0 50 22.4 50 50c0 27.6-22.4 50-50 50zm0-97c-25.9 0-47 21.1-47 47c0 25.9 21.1 47 47 47c25.9 0 47-21.1 47-47c0-25.9-21.1-47-47-47z" />
    <path id="P" d="M31.1 37.6l-9 0l0 24.7l3.6 0l0-8.2l5.4 0c5.3 0 8-4.1 8-8.2c0-4.2-2.7-8.3-8-8.3zm0 12.9l-5.4 0l0-9.4l5.4 0c3 0 4.5 2.3 4.5 4.7c0 2.4-1.5 4.7-4.5 4.7z" />
    <path id="R" d="M72.2 49.8l-4.2 0l0 1.7l9 10.8l4.6 0l-7.8-9.3c4.2-0.7 6.4-4.1 6.4-7.6c0-3.9-2.7-8.2-8-8.2l-9 0l0 25l3.5 0l0-21.3l5.5 0c3 0 4.5 2.5 4.5 4.6c-0.1 2.1-1.5 4.3-4.5 4.3z" />
    <path id="Pipe" d="M51.4 70l-2.8 0l0-40l2.8 0l0 40z" />
  </symbol>
</svg>

In the above example, strokes are converted to solid paths – thus you don’t have to bother about styling stroke-colors and fill colors.

»Silverbullet« currentColor?

svg's currentColor value is handy to color svg elements according to their parent elements' (text) color.

E.g. perfectly suited for an inline (icon font like) element behavior.

But you won't see any effect applying fill color values.

Nothing wrong with the fill property

Since fill is reserved for svg elements – you don't have to worry about accidentally overridden styles.

So it might still be a better choice for some elements.


问:
indexedDB add record to objectStore only works once
I am trying to understand how indexedDB works and wrote a rather basic site visitor tracker. This works the first time around. When page is loaded the first time everything works as expected. I can see the data is added into my objectStore.

Now every time I refresh the page I do not get another record added as expected. What am I not doing correctly ? Any guidance or help is most welcome.

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!-- The above 3 meta tags *must* come first in the head; any other
  head content must come *after* these tags -->

  <meta name="description" content="">
  <meta name="author" content="">

  <script language="JavaScript" src="http://www.geoplugin.net
  /javascript.gp" type="text/javascript"></script>

</head>
<body>
  // UI here
</body>
<script>
  var timeDate = new Date();
  var tD=timeDate.toString();
  alert(timeDate);

  var ip = geoplugin_request();           // get client ip
  alert(ip);

  var city = geoplugin_city();            // get client city
  alert(city);

  var country = geoplugin_countryName() ; // get client country
  alert(country);

  var os = navigator.oscpu;               // get platform info
  alert(os);

  window.indexedDB = window.indexedDB || window.mozIndexedDB ||
  window.webkitIndexedDB || window.msIndexedDB;

  //prefixes of window.IDB objects
  window.IDBTransaction = window.IDBTransaction ||
  window.webkitIDBTransaction || window.msIDBTransaction;
  window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange ||
  window.msIDBKeyRange

  if (!window.indexedDB) {
    window.alert("Your browser doesn't support a stable version of IndexedDB.")
  }

  var visitorInfo = [{
         date   : tD,
         ip     : ip,
         city   : city,
         country: country,
         os     :os },
     ];

     var db;
     var request = window.indexedDB.open("visitor", 1);

     request.onerror = function(event) {
        console.log("error: ");
     };

     request.onsuccess = function(event) {
        db = request.result;
        console.log("success: "+ db);
     };

     request.onupgradeneeded = function(event) {
        var db = event.target.result;

        if(!db.objectStoreNames.contains("userinfo")){
            console.log("creating userinfo table..");
            //var objectStore = db.createObjectStore("userinfo", {keyPath: "ip",autoIncrement:true});
            var objectStore = db.createObjectStore("userinfo", {keyPath: "ip"});
        }
        else{
            console.log("userinfo exists");
            }

        for (var i in visitorInfo) {
           objectStore.add(visitorInfo[i]);
        }
     }
</code>```

答:
I have run access to the same problem. Two things were causing that in my case.

Use onsuccess handler if you have already created the table/indexdb.

This one is the silly part but I've made this mistake. If you are reviewing the data over browser developer tools, the indexDB itself doesn't update the records when you click on the odjectstore/table. You have to click on refresh button on indexdb window under application section to see if the record has been created. The refresh button is the left corner of the dataset.

Body:
I am trying to understand how indexedDB works and wrote a rather basic site visitor tracker. This works the first time around. When page is loaded the first time everything works as expected. I can see the data is added into my objectStore.

Now every time I refresh the page I do not get another record added as expected. What am I not doing correctly ? Any guidance or help is most welcome.

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <meta name="description" content="">
  <meta name="author" content="">

  // UI here


问:
laravel jetstream photo profile section doesnt apear
eh been trying to make the section of upload photo appear in the update section, but it does not appear unless I remove the if and I do not understand why I already modify the jetstream.php the .env and I do not know what else to do
enter image description here
that if I do not know what it does but it is what does not allow the image to be displayed
enter image description here
the photo section does not appear :(</p>

答:
To enable profile photo, you must enable the feature in your application's config/jetstream.php configuration file. simply uncomment the corresponding feature entry from the features configuration item within this file:

use Laravel\Jetstream\Features;

'features' => [
    Features::profilePhotos(), <- uncomment this line
    Features::api(),
    Features::teams(),
],
```
<p>Also don't forget to run</p>
```php artisan storage:link
```

This is straight from the Jetstream Docs By the way.

Body:
To enable profile photo, you must enable the feature in your application's config/jetstream.php configuration file. simply uncomment the corresponding feature entry from the features configuration item within this file:

use Laravel\Jetstream\Features;

'features' => [
    Features::profilePhotos(), <- uncomment this line
    Features::api(),
    Features::teams(),
],

Also don't forget to run

php artisan storage:link

This is straight from the Jetstream Docs By the way.


问:
Python.NET: How to access generic member of an interface
I am trying to use a generic member from an interface in FlaUI through Python.NET.

The below C# code works,

```<code>// myLegacyTreeItem is a valid AutomationElement
// this works and the default action expands the tree node
myLegacyTreeItem.Patterns.LegacyIAccessible.Pattern.DoDefaultAction();
</code>```

However, the below corresponding Python.NET code doesn't work,

```<code># my_legacy_tree_item is a valid element
my_legacy_tree_item.Patterns.LegacyIAccessible.Pattern.DoDefaultAction()
</code>```

I am getting the following error,

```<code>AttributeError: 'UIA3FrameworkAutomationElement' object has no attribute 'LegacyIAccessible'
</code>```

I can see the the LegacyIAccessible member is using generic syntax. But I am not able to figure out how to bind it to the concrete type.

https://github.com/FlaUI/FlaUI/blob/master/src/FlaUI.Core/FrameworkAutomationElementBase.Patterns.cs

```<code>using FlaUI.Core.Patterns;

namespace FlaUI.Core
{
    public abstract partial class FrameworkAutomationElementBase : FrameworkAutomationElementBase.IFrameworkPatterns
    {
        private IAutomationPattern<IAnnotationPattern> _annotationPattern;
        private IAutomationPattern<IDockPattern> _dockPattern;
        private IAutomationPattern<IDragPattern> _dragPattern;
        private IAutomationPattern<IDropTargetPattern> _dropTargetPattern;
        private IAutomationPattern<IExpandCollapsePattern> _expandCollapsePattern;
        private IAutomationPattern<IGridItemPattern> _gridItemPattern;
        private IAutomationPattern<IGridPattern> _gridPattern;
        private IAutomationPattern<IInvokePattern> _invokePattern;
        private IAutomationPattern<IItemContainerPattern> _itemContainerPattern;
        private IAutomationPattern<ILegacyIAccessiblePattern> _legacyIAccessiblePattern;
        ...
        public IFrameworkPatterns Patterns => this;

        IAutomationPattern<IAnnotationPattern> IFrameworkPatterns.Annotation => _annotationPattern ?? (_annotationPattern = InitializeAnnotationPattern());
        IAutomationPattern<IDockPattern> IFrameworkPatterns.Dock => _dockPattern ?? (_dockPattern = InitializeDockPattern());
        IAutomationPattern<IDragPattern> IFrameworkPatterns.Drag => _dragPattern ?? (_dragPattern = InitializeDragPattern());
        IAutomationPattern<IDropTargetPattern> IFrameworkPatterns.DropTarget => _dropTargetPattern ?? (_dropTargetPattern = InitializeDropTargetPattern());
        IAutomationPattern<IExpandCollapsePattern> IFrameworkPatterns.ExpandCollapse => _expandCollapsePattern ?? (_expandCollapsePattern = InitializeExpandCollapsePattern());
        IAutomationPattern<IGridItemPattern> IFrameworkPatterns.GridItem => _gridItemPattern ?? (_gridItemPattern = InitializeGridItemPattern());
        IAutomationPattern<IGridPattern> IFrameworkPatterns.Grid => _gridPattern ?? (_gridPattern = InitializeGridPattern());
        IAutomationPattern<IInvokePattern> IFrameworkPatterns.Invoke => _invokePattern ?? (_invokePattern = InitializeInvokePattern());
        IAutomationPattern<IItemContainerPattern> IFrameworkPatterns.ItemContainer => _itemContainerPattern ?? (_itemContainerPattern = InitializeItemContainerPattern());
        IAutomationPattern<ILegacyIAccessiblePattern> IFrameworkPatterns.LegacyIAccessible => _legacyIAccessiblePattern ?? (_legacyIAccessiblePattern = InitializeLegacyIAccessiblePattern());
        ...
    }
}
</code>```

If I change the call as below, there is no error, but the tree item is not expanded,

```<code>((FrameworkAutomationElementBase.IFrameworkPatterns)(my_legacy_tree_item.Patterns)).LegacyIAccessible.Pattern.DoDefaultAction()

</code>```

Trying to use the below cast throws error,

```<code>((FrameworkAutomationElementBase.IFrameworkPatterns[ILegacyIAccessiblePattern])(parent.Patterns)).LegacyIAccessible.Pattern.DoDefaultAction()
</code>```
```<code>Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
   at Python.Runtime.GenericUtil.GenericByName(String ns, String name, Int32 paramCount)
   at Python.Runtime.ClassBase.type_subscript(IntPtr idx)
</code>```

答:
Answering my own question as it was a silly mistake.

The below line indeed expands the legacy tree item,

```<code>((FrameworkAutomationElementBase.IFrameworkPatterns)(my_legacy_tree_item.Patterns)).LegacyIAccessible.Pattern.DoDefaultAction()
</code>```

However, since in my case, I was also immediately right clicking on the same item, the context menu was getting popped up before the tree item could be expanded. So adding sleep(1) after the above call worked for me.

Alternatively my_legacy_tree_item.DoubleClick() followed by sleep(1) worked too.

Body:
I am trying to use a generic member from an interface in FlaUI through Python.NET.

The below C# code works,

// myLegacyTreeItem is a valid AutomationElement
// this works and the default action expands the tree node
myLegacyTreeItem.Patterns.LegacyIAccessible.Pattern.DoDefaultAction();

However, the below corresponding Python.NET code doesn't work,

# my_legacy_tree_item is a valid element
my_legacy_tree_item.Patterns.LegacyIAccessible.Pattern.DoDefaultAction()

I am getting the following error,

AttributeError: 'UIA3FrameworkAutomationElement' object has no attribute 'LegacyIAccessible'

I can see the the LegacyIAccessible member is using generic syntax. But I am not able to figure out how to bind it to the concrete type.

https://github.com/FlaUI/FlaUI/blob/master/src/FlaUI.Core/FrameworkAutomationElementBase.Patterns.cs

using FlaUI.Core.Patterns;

namespace FlaUI.Core
{
    public abstract partial class FrameworkAutomationElementBase : FrameworkAutomationElementBase.IFrameworkPatterns
    {
        private IAutomationPattern<IAnnotationPattern> _annotationPattern;
        private IAutomationPattern<IDockPattern> _dockPattern;
        private IAutomationPattern<IDragPattern> _dragPattern;
        private IAutomationPattern<IDropTargetPattern> _dropTargetPattern;
        private IAutomationPattern<IExpandCollapsePattern> _expandCollapsePattern;
        private IAutomationPattern<IGridItemPattern> _gridItemPattern;
        private IAutomationPattern<IGridPattern> _gridPattern;
        private IAutomationPattern<IInvokePattern> _invokePattern;
        private IAutomationPattern<IItemContainerPattern> _itemContainerPattern;
        private IAutomationPattern<ILegacyIAccessiblePattern> _legacyIAccessiblePattern;
        ...
        public IFrameworkPatterns Patterns => this;

        IAutomationPattern<IAnnotationPattern> IFrameworkPatterns.Annotation => _annotationPattern ?? (_annotationPattern = InitializeAnnotationPattern());
        IAutomationPattern<IDockPattern> IFrameworkPatterns.Dock => _dockPattern ?? (_dockPattern = InitializeDockPattern());
        IAutomationPattern<IDragPattern> IFrameworkPatterns.Drag => _dragPattern ?? (_dragPattern = InitializeDragPattern());
        IAutomationPattern<IDropTargetPattern> IFrameworkPatterns.DropTarget => _dropTargetPattern ?? (_dropTargetPattern = InitializeDropTargetPattern());
        IAutomationPattern<IExpandCollapsePattern> IFrameworkPatterns.ExpandCollapse => _expandCollapsePattern ?? (_expandCollapsePattern = InitializeExpandCollapsePattern());
        IAutomationPattern<IGridItemPattern> IFrameworkPatterns.GridItem => _gridItemPattern ?? (_gridItemPattern = InitializeGridItemPattern());
        IAutomationPattern<IGridPattern> IFrameworkPatterns.Grid => _gridPattern ?? (_gridPattern = InitializeGridPattern());
        IAutomationPattern<IInvokePattern> IFrameworkPatterns.Invoke => _invokePattern ?? (_invokePattern = InitializeInvokePattern());
        IAutomationPattern<IItemContainerPattern> IFrameworkPatterns.ItemContainer => _itemContainerPattern ?? (_itemContainerPattern = InitializeItemContainerPattern());
        IAutomationPattern<ILegacyIAccessiblePattern> IFrameworkPatterns.LegacyIAccessible => _legacyIAccessiblePattern ?? (_legacyIAccessiblePattern = InitializeLegacyIAccessiblePattern());
        ...
    }
}

If I change the call as below, there is no error, but the tree item is not expanded,

((FrameworkAutomationElementBase.IFrameworkPatterns)(my_legacy_tree_item.Patterns)).LegacyIAccessible.Pattern.DoDefaultAction()

Trying to use the below cast throws error,

((FrameworkAutomationElementBase.IFrameworkPatterns[ILegacyIAccessiblePattern])(parent.Patterns)).LegacyIAccessible.Pattern.DoDefaultAction()

Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
   at Python.Runtime.GenericUtil.GenericByName(String ns, String name, Int32 paramCount)
   at Python.Runtime.ClassBase.type_subscript(IntPtr idx)

Body:
Answering my own question as it was a silly mistake.

The below line indeed expands the legacy tree item,

((FrameworkAutomationElementBase.IFrameworkPatterns)(my_legacy_tree_item.Patterns)).LegacyIAccessible.Pattern.DoDefaultAction()

However, since in my case, I was also immediately right clicking on the same item, the context menu was getting popped up before the tree item could be expanded. So adding sleep(1) after the above call worked for me.

Alternatively my_legacy_tree_item.DoubleClick() followed by sleep(1) worked too.


问:
Why am I getting a NG0901 error when I am not performing any data change?
In the following code segment, I am iterating over ardene.section1.items. I have logged this array to the console to verify that it does exist. The "BEFORE FOR LOOP" test is printed to the screen but the "INSIDE FOR LOOP" test is never printed. And I get  and NG0901 error which Angular tells me is a ngDoCheck error.

```<code><div class="row mt-4">
BEFORE FOR LOOP
<div class="col text-center col-12 col-md-3 mb-4 mb-md-0"
    *ngFor="let item of ardene.section1.items">
    INSIDE FOR LOOP
    <img class="img-fluid"
        src=`{{ardene.assetPath}}{{item.img}}`>
    <div>
        <h5 class="text-center fw-bold mt-2">{{item.name}}</h5>
        <h6 class="text-center">{{item.description}}<br></h6>
        <a>
            <h6 class="fw-bold">Shop Now</h6>
        </a>
    </div>
</div>
</code>```

The component code that produces ardene.section1.items is shown below.

```<code>  constructor(
    private store:Store<{ardeneState}>
  ) { }

  ngOnInit(): void {
    this.subscribeToReduxStores();
  }

private subscribeToReduxStores = () => {
const ardene$ = this.store.select(state => {
  return state.ardeneState
})

ardene$.subscribe(ardene => {
  this.ardene = ardene;

  console.log('ardene.section1.heading', this.ardene.section1.heading)
  console.log('ardene.section1.items', this.ardene.section1.items)
  console.log('ardene', this.ardene)
})
  }
</code>```

The data originates from the redux store:

```<code>const initialState = {
  assetPath: 'app/category/ladies-apparel/ardene/assets/img/',

  section1: {
    heading: 'New Denim Guide',
    subheading: "EVERYBODY'S OBSESSING OVER THESE STYLES",
    items: {
      img: 'ardene-6.jpg',
      name: 'Mom Jeans',
      description: 'The vintage silhouette',
      link: '',
    },
  },
};
</code>```

Error:

```<code>ERROR Error: NG0901
at e.find (main.10edf50a2ef1763e.js:1:146206)
at h.ngDoCheck (main.10edf50a2ef1763e.js:1:43158)
at Vs (main.10edf50a2ef1763e.js:1:56860)
at Bs (main.10edf50a2ef1763e.js:1:56661)
at yr (main.10edf50a2ef1763e.js:1:56381)
at ro (main.10edf50a2ef1763e.js:1:76106)
at Gy (main.10edf50a2ef1763e.js:1:82951)
at _y (main.10edf50a2ef1763e.js:1:76845)
at ro (main.10edf50a2ef1763e.js:1:76856)
at Hy (main.10edf50a2ef1763e.js:1:76404)
</code>```

答:
You are getting error because you are trying to iterate over an object instead of an array when using *ngFor.

// ardene.section1.items is an object and not an array
*ngFor="let item of ardene.section1.items"
```
<p>NgFor only supports binding to Iterables such as Arrays. If you want to iterate over an object, you can make use of KeyValuePipe which</p>
<blockquote>
<p>Transforms Object or Map into an array of key value pairs.</p>
</blockquote>
<p>Looking at your data structure I don't see any reason for you to use <code>*ngFor</code>, you can simply access the object properties as:</p>
<pre class="lang-html prettyprint-override"><code>{{ardene?.section1?.items?.img}}
{{ardene?.section1?.items?.name}}
{{ardene?.section1?.items?.description}}
</code>```

If you want to avoid repetition of ardene?.section1?.items, you can try to do something as below:

<ng-container *ngIf="ardene?.section1?.items as item">
  <img class="img-fluid" src=`{{ardene.assetPath}}{{item?.img}}`>

{{item?.name}}

{{item?.description}}

Shop Now

</ng-container>
```

Body:
In the following code segment, I am iterating over ardene.section1.items. I have logged this array to the console to verify that it does exist. The "BEFORE FOR LOOP" test is printed to the screen but the "INSIDE FOR LOOP" test is never printed. And I get  and NG0901 error which Angular tells me is a ngDoCheck error.

BEFORE FOR LOOP

    INSIDE FOR LOOP
    <img class="img-fluid"
        src=`{{ardene.assetPath}}{{item.img}}`>

{{item.name}}

{{item.description}}

Shop Now

The component code that produces ardene.section1.items is shown below.

  constructor(
    private store:Store<{ardeneState}>
  ) { }

  ngOnInit(): void {
    this.subscribeToReduxStores();
  }

private subscribeToReduxStores = () => {
const ardene$ = this.store.select(state => {
  return state.ardeneState
})

ardene$.subscribe(ardene => {
  this.ardene = ardene;

  console.log('ardene.section1.heading', this.ardene.section1.heading)
  console.log('ardene.section1.items', this.ardene.section1.items)
  console.log('ardene', this.ardene)
})
  }

The data originates from the redux store:

const initialState = {
  assetPath: 'app/category/ladies-apparel/ardene/assets/img/',

  section1: {
    heading: 'New Denim Guide',
    subheading: "EVERYBODY'S OBSESSING OVER THESE STYLES",
    items: {
      img: 'ardene-6.jpg',
      name: 'Mom Jeans',
      description: 'The vintage silhouette',
      link: '',
    },
  },
};

Error:

ERROR Error: NG0901
at e.find (main.10edf50a2ef1763e.js:1:146206)
at h.ngDoCheck (main.10edf50a2ef1763e.js:1:43158)
at Vs (main.10edf50a2ef1763e.js:1:56860)
at Bs (main.10edf50a2ef1763e.js:1:56661)
at yr (main.10edf50a2ef1763e.js:1:56381)
at ro (main.10edf50a2ef1763e.js:1:76106)
at Gy (main.10edf50a2ef1763e.js:1:82951)
at _y (main.10edf50a2ef1763e.js:1:76845)
at ro (main.10edf50a2ef1763e.js:1:76856)
at Hy (main.10edf50a2ef1763e.js:1:76404)

Body:
You are getting error because you are trying to iterate over an object instead of an array when using *ngFor.

// ardene.section1.items is an object and not an array
*ngFor="let item of ardene.section1.items"

NgFor only supports binding to Iterables such as Arrays. If you want to iterate over an object, you can make use of KeyValuePipe which

Transforms Object or Map into an array of key value pairs.

Looking at your data structure I don't see any reason for you to use *ngFor, you can simply access the object properties as:

{{ardene?.section1?.items?.img}}
{{ardene?.section1?.items?.name}}
{{ardene?.section1?.items?.description}}

If you want to avoid repetition of ardene?.section1?.items, you can try to do something as below:

<ng-container *ngIf="ardene?.section1?.items as item">
  <img class="img-fluid" src=`{{ardene.assetPath}}{{item?.img}}`>
  <div>
    <h5 class="text-center fw-bold mt-2">{{item?.name}}</h5>
    <h6 class="text-center">{{item?.description}}<br></h6>
    <a>
      <h6 class="fw-bold">Shop Now</h6>
    </a>
  </div>
</ng-container>


问:
How to export the world of NetLogo 6.2 coloring only the patches that were born turtles?
I don't really know how to export the following output...

I have 16 turtles profiles, which refers to the non-repeating combination of habitatcover types (see ValidHabs variable)

In the model, it starts with 10 turtles that can reproduce or die.

I would like to generate an output in which the whole world turns white and paints magenta only where turtles were born, that is, the 10 turtles that started the world and then the new turtles that emerged through the reproduction process. And that this came out by turtle profile. I have looked up the NetLogo dictionary and I believe I should use the export-view command

But, I still couldn't execute in a simple code that can only export in image form the patches that only existed turtle (painted in magenta) at the end of all ticks (that is, all patches that had turtles taking into account all ticks ) for that turtle profile.

What I've managed to do so far is below.

Any kind of help will be very welcome :)

Thanks in advance!

```<code>globals [ ValidHabs ValidHabsItem HotPatchSet CurrentHotPatchSet PatchAvailable ListProfiles Death ]

patches-own [ habitatcover resources turtle-count ]

turtles-own [ turtle-profiles-habitat metabolism reproduction all-code code-metabolism code-reproduction energy my-patches x ]

to setup
  clear-all
  random-seed 1
  set ValidHabs [[1] [2] [3] [4] [5] [6] [1 2] [1 3] [1 4] [1 5] [2 3] [2 4] [2 5] [3 4] [3 5] [4 5] ]
  set Death 0
  set ListProfiles [ ]
  setup-world
  setup-patches
  reset-ticks
  foreach sort turtles
  [
    t ->
    ask t
    [
      print ( word "I am:" " " who )
    ]
  ]
  print ""
end

to setup-world
  let pcolors []
  set pcolors [ 25 65 23 53 105 45 ]
  ask patches [
    set pcolor item (random 6) pcolors
  ]

  ask patches [
    if pcolor = 25 [ set habitatcover 1 ]
    if pcolor = 65 [ set habitatcover 2 ]
    if pcolor = 23 [ set habitatcover 3 ]
    if pcolor = 53 [ set habitatcover 4 ]
    if pcolor = 105 [ set habitatcover 5 ]
    if pcolor = 45 [ set habitatcover 6 ]
  ]
  ask patches [ set resources random 100 ]
end

to setup-patches
  set HotPatchSet patches with  [ ( habitatcover != 6 ) ]
  let list1 ( list 2 )
  let list2 ( list 5 )
  let n0 count turtles
  set CurrentHotPatchSet HotPatchSet with [ habitatcover = one-of item ValidHabsItem ValidHabs ]
  while [ n0 < ( length list1 ) * ( length list2 ) * 10 ]
  [
    (
      foreach list1
      [
        this-metabolism ->
        foreach list2
        [
          this-reproduction ->
          let c count CurrentHotPatchSet
          if c = 0 [ stop ]
          ask one-of CurrentHotPatchSet
          [
            sprout 1
            [
              set turtle-profiles-habitat item ValidHabsItem ValidHabs
              set metabolism this-metabolism
              set reproduction this-reproduction
              setup-turtles who
            ]
            set CurrentHotPatchSet CurrentHotPatchSet with [ not any? turtles in-radius 2 ]
          ]
        ]
      ]
    )
    set n0 count turtles
  ]
end

to setup-turtles [ WhichColony? ]
  set color black
  set energy 0
  ask turtle who [
    (
      ifelse
      metabolism = 2 [set code-metabolism "M1"]
    )
    (
      ifelse
      reproduction = 5 [set code-reproduction "R1"]
    )
    set all-code ( word code-metabolism code-reproduction )
  ]

  set x turtle-profiles-habitat

  ask turtle who
  [
    if length x = 1
      [
        let a 1
        while [ a < 7 ]
        [
          if member? a x
          [
            set my-patches patches with [ habitatcover = a ]
          ]
          set a a + 1
        ]
    ]

     if length x = 2
    [
      let a 1
      while [ a < 7 ]
        [
        let b 1
        while [ b < 7 ]
        [
          if a = item 0 x and b = item 1 x
            [
              set my-patches patches with [ habitatcover = a or habitatcover = b ]
          ]
          set b b + 1
        ]
        set a a + 1
      ]
    ]
  ]
end

to go
  metabolic
   print ( word "TICK: " ticks )
  ask turtles [ print ( word "I am: " who ) ]
  tick
  let n count turtles
  if n = 0 or ticks = 10 and ExportView? = true [ output ] ;; ExportView? is a switch in the interface
end

to metabolic
  ask turtles
  [
    let z [ resources ] of patch-here
    if
    metabolism = 2 [
      set energy ( ceiling ( z ) - 2 )
      if energy <= 1.7 [ die-turtles ]
      if
      reproduction = 5 [
        if energy >= 5 [ dispersion ]
      ]
    ]
  ]
end

to dispersion
  let p 0
  while [ p < 1 ] [
    let available-patch my-patches with [ distance myself > 3 and distance myself < 5 and count turtles-here = 0 and not any? other turtles in-radius 3 ]
    set PatchAvailable count available-patch
    if PatchAvailable = 0 [ stop ]
    let choose-patch one-of available-patch
    let coordx [ pxcor ] of choose-patch
    let coordy [ pycor ] of choose-patch
    hatch 1 [
      setxy coordx coordy
      set turtle-count count turtles-here
      set color white
      set energy 0
      set p p + 1
    ]
  ]
end

to die-turtles
    foreach ListProfiles [ lp ->
    set Death 0
    set Death Death + 1
  ]
  die
end

to color_patches
  ask patches [ set pcolor white ]
  ask turtles [
    ask patch-here [ set pcolor magenta ]
  ]
end

to output
  export-view ( word "View.png" )
end

;; in the interface go button, I put the following:
;if ExportView? = true
;[
;  color_patches
;]
;go
</code>```

答:
I think the best way to track this is a patches-own variable to track if a turtle was ever born on the patch. In this example code I've called that turtle-born-here, set the variable to false in the setup, then update the variable any time a turtle is 'born' (either on setup, or during go).

```<code>patches-own [ turtle-born-here ]

to setup
  ca
  ask patches [ set turtle-born-here false ]
  ask n-of 5 patches [
    sprout 1
    set turtle-born-here true
  ]
  reset-ticks
end

to go
  ask turtles [
    rt random 60 - 30
    fd 1
    if random-float 1 < 0.05 [
      hatch 1
      ask patch-here [ set turtle-born-here true]
    ]
  ]
end

to example-export-image
  setup
  ; Some example go runs
  repeat 50 [ go ]

  ; This is the export-view component
  cd
  ask turtles [
    ht
  ]
  ask patches [
    ifelse turtle-born-here
    [ set pcolor magenta ]
    [ set pcolor white ]
  ]
  export-view "example_view_export.png"
end
</code>```

Running this spits out an image like:

Body:
I don't really know how to export the following output...

I have 16 turtles profiles, which refers to the non-repeating combination of habitatcover types (see ValidHabs variable)

In the model, it starts with 10 turtles that can reproduce or die.

I would like to generate an output in which the whole world turns white and paints magenta only where turtles were born, that is, the 10 turtles that started the world and then the new turtles that emerged through the reproduction process. And that this came out by turtle profile. I have looked up the NetLogo dictionary and I believe I should use the export-view command

But, I still couldn't execute in a simple code that can only export in image form the patches that only existed turtle (painted in magenta) at the end of all ticks (that is, all patches that had turtles taking into account all ticks ) for that turtle profile.

What I've managed to do so far is below.

Any kind of help will be very welcome :)

Thanks in advance!

globals [ ValidHabs ValidHabsItem HotPatchSet CurrentHotPatchSet PatchAvailable ListProfiles Death ]

patches-own [ habitatcover resources turtle-count ]

turtles-own [ turtle-profiles-habitat metabolism reproduction all-code code-metabolism code-reproduction energy my-patches x ]

to setup
  clear-all
  random-seed 1
  set ValidHabs [[1] [2] [3] [4] [5] [6] [1 2] [1 3] [1 4] [1 5] [2 3] [2 4] [2 5] [3 4] [3 5] [4 5] ]
  set Death 0
  set ListProfiles [ ]
  setup-world
  setup-patches
  reset-ticks
  foreach sort turtles
  [
    t ->
    ask t
    [
      print ( word "I am:" " " who )
    ]
  ]
  print ""
end

to setup-world
  let pcolors []
  set pcolors [ 25 65 23 53 105 45 ]
  ask patches [
    set pcolor item (random 6) pcolors
  ]

  ask patches [
    if pcolor = 25 [ set habitatcover 1 ]
    if pcolor = 65 [ set habitatcover 2 ]
    if pcolor = 23 [ set habitatcover 3 ]
    if pcolor = 53 [ set habitatcover 4 ]
    if pcolor = 105 [ set habitatcover 5 ]
    if pcolor = 45 [ set habitatcover 6 ]
  ]
  ask patches [ set resources random 100 ]
end

to setup-patches
  set HotPatchSet patches with  [ ( habitatcover != 6 ) ]
  let list1 ( list 2 )
  let list2 ( list 5 )
  let n0 count turtles
  set CurrentHotPatchSet HotPatchSet with [ habitatcover = one-of item ValidHabsItem ValidHabs ]
  while [ n0 < ( length list1 ) * ( length list2 ) * 10 ]
  [
    (
      foreach list1
      [
        this-metabolism ->
        foreach list2
        [
          this-reproduction ->
          let c count CurrentHotPatchSet
          if c = 0 [ stop ]
          ask one-of CurrentHotPatchSet
          [
            sprout 1
            [
              set turtle-profiles-habitat item ValidHabsItem ValidHabs
              set metabolism this-metabolism
              set reproduction this-reproduction
              setup-turtles who
            ]
            set CurrentHotPatchSet CurrentHotPatchSet with [ not any? turtles in-radius 2 ]
          ]
        ]
      ]
    )
    set n0 count turtles
  ]
end

to setup-turtles [ WhichColony? ]
  set color black
  set energy 0
  ask turtle who [
    (
      ifelse
      metabolism = 2 [set code-metabolism "M1"]
    )
    (
      ifelse
      reproduction = 5 [set code-reproduction "R1"]
    )
    set all-code ( word code-metabolism code-reproduction )
  ]

  set x turtle-profiles-habitat

  ask turtle who
  [
    if length x = 1
      [
        let a 1
        while [ a < 7 ]
        [
          if member? a x
          [
            set my-patches patches with [ habitatcover = a ]
          ]
          set a a + 1
        ]
    ]

     if length x = 2
    [
      let a 1
      while [ a < 7 ]
        [
        let b 1
        while [ b < 7 ]
        [
          if a = item 0 x and b = item 1 x
            [
              set my-patches patches with [ habitatcover = a or habitatcover = b ]
          ]
          set b b + 1
        ]
        set a a + 1
      ]
    ]
  ]
end

to go
  metabolic
   print ( word "TICK: " ticks )
  ask turtles [ print ( word "I am: " who ) ]
  tick
  let n count turtles
  if n = 0 or ticks = 10 and ExportView? = true [ output ] ;; ExportView? is a switch in the interface
end

to metabolic
  ask turtles
  [
    let z [ resources ] of patch-here
    if
    metabolism = 2 [
      set energy ( ceiling ( z ) - 2 )
      if energy <= 1.7 [ die-turtles ]
      if
      reproduction = 5 [
        if energy >= 5 [ dispersion ]
      ]
    ]
  ]
end

to dispersion
  let p 0
  while [ p < 1 ] [
    let available-patch my-patches with [ distance myself > 3 and distance myself < 5 and count turtles-here = 0 and not any? other turtles in-radius 3 ]
    set PatchAvailable count available-patch
    if PatchAvailable = 0 [ stop ]
    let choose-patch one-of available-patch
    let coordx [ pxcor ] of choose-patch
    let coordy [ pycor ] of choose-patch
    hatch 1 [
      setxy coordx coordy
      set turtle-count count turtles-here
      set color white
      set energy 0
      set p p + 1
    ]
  ]
end

to die-turtles
    foreach ListProfiles [ lp ->
    set Death 0
    set Death Death + 1
  ]
  die
end

to color_patches
  ask patches [ set pcolor white ]
  ask turtles [
    ask patch-here [ set pcolor magenta ]
  ]
end

to output
  export-view ( word "View.png" )
end

;; in the interface go button, I put the following:
;if ExportView? = true
;[
;  color_patches
;]
;go

Body:
I think the best way to track this is a patches-own variable to track if a turtle was ever born on the patch. In this example code I've called that turtle-born-here, set the variable to false in the setup, then update the variable any time a turtle is 'born' (either on setup, or during go).

patches-own [ turtle-born-here ]

to setup
  ca
  ask patches [ set turtle-born-here false ]
  ask n-of 5 patches [
    sprout 1
    set turtle-born-here true
  ]
  reset-ticks
end

to go
  ask turtles [
    rt random 60 - 30
    fd 1
    if random-float 1 < 0.05 [
      hatch 1
      ask patch-here [ set turtle-born-here true]
    ]
  ]
end

to example-export-image
  setup
  ; Some example go runs
  repeat 50 [ go ]

  ; This is the export-view component
  cd
  ask turtles [
    ht
  ]
  ask patches [
    ifelse turtle-born-here
    [ set pcolor magenta ]
    [ set pcolor white ]
  ]
  export-view "example_view_export.png"
end

Running this spits out an image like:


问:
Object array not printing to screen - React
On page load, I am using UseEffect to take an object array files. The array is mapped through, if it is male it is added to maleArray, if it is female it is added to femaleArray. At the end, i use console.log to check if the new arrays have filled and they have. I also set hasLoaded to true after this.

```<code>const[hasLoaded, setHasLoaded] = useState();
var maleArray= [];
var femaleArray= [];

useEffect(() => {
      getPersonGender();

    }, [props.files]);

    const getPersonGender = () => {
      if(!props.files.length > 0){
        console.log("WAITING");
      }else{
        props.files.map( person => {
          if(person.gender=== "male"){
            maleArray.push(person);
          }else{
            femaleArray.push(person);
          }
        });
        console.log(maleArray)
        console.log(femaleArray)
        setHasLoaded(true);
      }
    }
</code>```

However when I get to the return statement, the new arrays I filled seem to be empty. For example, I am trying to map the maleArray to a table. I check hasLoaded and it is true but when I get to print nothing displays and I can't figure out why. When I attempted to debug, it seemed that maleArray and femaleArray never filled, but however, I am getting the console.log results saying that they are.

```<code>{!hasLoaded
    ?<div class="spinner-border" role="status"></div>
    :
    <table class="table">
    <tbody>
        {maleArray.map(male=> (
            <tr>
                <td>{male.name}</td>
                <td>{male.age}</td>
            </tr>
    ))}
    </tbody>
    </table>
}
</code>```

Any reason why the new arrays are not being filled, yet i see the output on console.log? Thanks

答:
The main reason it did not work is that the state was not set. You need to use the useState() hook to assign it to arrays and then use them further

Complete working example

import { useState, useEffect } from "react";

function ConfigurationList(props) {
  const [hasLoaded, setHasLoaded] = useState();
  // usage of hooks
  const [maleArray, setMaleArr] = useState([]);
  const [femaleArray, setFemaleArr] = useState([]);

  useEffect(() => {
    getPersonGender();
  }, [props.files]);

  const getPersonGender = () => {
    let maleBuf = [];
    let femaleBuf = [];
    if (!props.files.length > 0) {
      console.log("WAITING");
    } else {
      props.files.map((person) => {
        if (person.gender === "male") {
          maleBuf.push(person);
        } else {
          femaleBuf.push(person);
        }
      });
      console.log(maleArray);
      console.log(femaleArray);
      // Setting the value to the state
      setFemaleArr([...femaleBuf])
      setMaleArr([...maleBuf])
      setHasLoaded(true);
    }
  };

  return (

Male

          {!hasLoaded ? (

          ) : (

                    Name

                    Age

                {maleArray.map((male) => (

                    {male.name}
                    {male.age}

                ))}

          )}

  );
}

export default ConfigurationList;
```

useState :
You will have to make sure that the array is not directly updated, because that will not render the data, So you should create a local variable and then assign it to the state at the end, or you can use the spread operator and then assign them, Both should work.

Body:
On page load, I am using UseEffect to take an object array files. The array is mapped through, if it is male it is added to maleArray, if it is female it is added to femaleArray. At the end, i use console.log to check if the new arrays have filled and they have. I also set hasLoaded to true after this.

const[hasLoaded, setHasLoaded] = useState();
var maleArray= [];
var femaleArray= [];

useEffect(() => {
      getPersonGender();

    }, [props.files]);

    const getPersonGender = () => {
      if(!props.files.length > 0){
        console.log("WAITING");
      }else{
        props.files.map( person => {
          if(person.gender=== "male"){
            maleArray.push(person);
          }else{
            femaleArray.push(person);
          }
        });
        console.log(maleArray)
        console.log(femaleArray)
        setHasLoaded(true);
      }
    }

However when I get to the return statement, the new arrays I filled seem to be empty. For example, I am trying to map the maleArray to a table. I check hasLoaded and it is true but when I get to print nothing displays and I can't figure out why. When I attempted to debug, it seemed that maleArray and femaleArray never filled, but however, I am getting the console.log results saying that they are.

{!hasLoaded
    ?

    :

        {maleArray.map(male=> (

                {male.name}
                {male.age}

    ))}

}

Any reason why the new arrays are not being filled, yet i see the output on console.log? Thanks

Body:
The main reason it did not work is that the state was not set. You need to use the useState() hook to assign it to arrays and then use them further

Complete working example

import { useState, useEffect } from "react";

function ConfigurationList(props) {
  const [hasLoaded, setHasLoaded] = useState();
  // usage of hooks
  const [maleArray, setMaleArr] = useState([]);
  const [femaleArray, setFemaleArr] = useState([]);

  useEffect(() => {
    getPersonGender();
  }, [props.files]);

  const getPersonGender = () => {
    let maleBuf = [];
    let femaleBuf = [];
    if (!props.files.length > 0) {
      console.log("WAITING");
    } else {
      props.files.map((person) => {
        if (person.gender === "male") {
          maleBuf.push(person);
        } else {
          femaleBuf.push(person);
        }
      });
      console.log(maleArray);
      console.log(femaleArray);
      // Setting the value to the state
      setFemaleArr([...femaleBuf])
      setMaleArr([...maleBuf])
      setHasLoaded(true);
    }
  };

  return (
    <div>
      <div class="card rounded-0">
        <div class="card-header bg-dark custom-font rounded-0">Male</div>

        <div class="card-body text-center">
          {!hasLoaded ? (
            <div class="spinner-border" role="status"></div>
          ) : (
            <table class="table">
              <thead>
                <tr>
                  <th style={{ width: "30%" }} scope="col">
                    Name
                  </th>
                  <th style={{ width: "30%" }} scope="col">
                    Age
                  </th>
                </tr>
              </thead>
              <tbody>
                {maleArray.map((male) => (
                  <tr>
                    <td>{male.name}</td>
                    <td>{male.age}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      </div>
    </div>
  );
}

export default ConfigurationList;

useState :
You will have to make sure that the array is not directly updated, because that will not render the data, So you should create a local variable and then assign it to the state at the end, or you can use the spread operator and then assign them, Both should work.


问:
Most useful animation in web or desktop application
Many animation effects are simply gratuitous eye candy -- however, there are situations where animations effectively communicate to the user what's going on.
What are some of your favorite uses for animations, and what specific animation type would you use?

E.g.: Animate items downwards when a new item is inserted into a list

答: AJAX loading gifs - you've got to have an indicator that you definitely registered an event and you're doing something about it

OwnerDisplayName: Jen

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: annakata


问:
Toast not show in OnItemCLick
```<code>package com.custom;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;

import android.os.Bundle;
import android.util.Log;
import android.view.View;

import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {
    ListView list;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Log.v("", "on create");
        ListView list = (ListView)findViewById(R.id.list);

        List<PhoneList> listOfPhonebook = new ArrayList<PhoneList>();
        listOfPhonebook.add(new PhoneList("Sutadi","9898989", "Jl.Pasar"));
        listOfPhonebook.add(new PhoneList("Iyand","1234455", "Jl.Mall"));
        listOfPhonebook.add(new PhoneList("Yanti","00000", "Jl.Sawah"));
        Log.v("", "Add phone list");

        PhoneBookAdapter adapter = new PhoneBookAdapter(this, listOfPhonebook);
        Log.v("", "Adapter create");

        list.setAdapter(adapter);
        Log.v("", "adapter implement");

    list.setOnItemClickListener(new OnItemClickListener() {

        @Override

    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        // TODO Auto-generated method stub
            Toast.makeText(getBaseContext(), "You clciked ", Toast.LENGTH_LONG).show();

    }
    });
    }
}
</code>```

why the toast can not show ? anyone can help me ?

This is my PhoneBookAdapter

```<code>package com.custom;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class PhoneBookAdapter extends BaseAdapter{
    private Context context;

    private List<PhoneList> listPhonebook;

    public PhoneBookAdapter(Context context, List<PhoneList> listPhonebook) {
        this.context = context;
        this.listPhonebook = listPhonebook;
    }

    public int getCount() {
        return listPhonebook.size();
    }

    public Object getItem(int position) {
        return listPhonebook.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup viewGroup) {
        PhoneList entry = listPhonebook.get(position);
        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.row, null);
        }
        TextView tvContact = (TextView) convertView.findViewById(R.id.textstatus);
        tvContact.setText(entry.getName());

        TextView tvPhone = (TextView) convertView.findViewById(R.id.textkonos);
        tvPhone.setText(entry.getPhone());

        TextView tvAlamat = (TextView) convertView.findViewById(R.id.textalamat);
        tvAlamat.setText(entry.getAlamat());

        return convertView;
    }

}
</code>```

main.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="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Custom"
    android:textSize="10pt"
    android:paddingBottom="7px"
    android:background="#d5d5d5"
    android:textColor="#000000"
    />
<ListView
    android:paddingLeft="2px"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/list"
></ListView>

</LinearLayout>
</code>```

row.xml

```<code><?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="?android:attr/listPreferredItemHeight"

    android:padding="6dip">

    <CheckBox android:text=""
    android:layout_width="wrap_content"
    android:id="@+id/checkBox1"
    android:layout_height="fill_parent"
    android:layout_alignParentBottom="true"
    android:layout_alignParentTop="true"
    android:layout_alignParentRight="true"></CheckBox>

    <TextView
    android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/textnama"
            android:padding="7px"
            android:layout_alignParentLeft="true"
            android:text="Konos : "/>

    <TextView
       android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/textstatus"
            android:singleLine="true"
            android:padding="7px"

            android:layout_below="@+id/textnama"
            android:layout_alignParentLeft="true"
            android:text="haha"/>

     <TextView android:layout_width="wrap_content"
     android:text="hohohoho"
     android:layout_height="wrap_content"
     android:id="@+id/textkonos"
     android:paddingRight="3px"
     android:padding="7px"
     android:layout_above="@+id/textstatus"
     android:layout_toRightOf="@+id/textnama"></TextView>

    <TextView android:layout_width="wrap_content"
     android:text="-"
     android:layout_height="wrap_content"
     android:id="@+id/text"
     android:paddingRight="3px"
     android:padding="7px"
     android:layout_below="@+id/textkonos"
     android:layout_toRightOf="@+id/textstatus"></TextView>

     <TextView android:layout_width="wrap_content"
     android:text=""
     android:layout_height="wrap_content"
     android:id="@+id/textalamat"
     android:paddingRight="3px"
     android:padding="7px"
     android:layout_alignParentBottom="true"
     android:layout_alignLeft="@+id/textkonos"></TextView>

</RelativeLayout>
</code>```

答:
first put the breakpoint at toast and ensure that you are getting the call there and if you get the call and it is not showing then try this:</p>

```<code>Toast.makeText(MainActivity.this, "You clciked ", Toast.LENGTH_LONG).show();
</code>```

Title: Toast not show in OnItemCLick

Body:
package com.custom;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;

import android.os.Bundle;
import android.util.Log;
import android.view.View;

import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {
    ListView list;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Log.v("", "on create");
        ListView list = (ListView)findViewById(R.id.list);

        List<PhoneList> listOfPhonebook = new ArrayList<PhoneList>();
        listOfPhonebook.add(new PhoneList("Sutadi","9898989", "Jl.Pasar"));
        listOfPhonebook.add(new PhoneList("Iyand","1234455", "Jl.Mall"));
        listOfPhonebook.add(new PhoneList("Yanti","00000", "Jl.Sawah"));
        Log.v("", "Add phone list");

        PhoneBookAdapter adapter = new PhoneBookAdapter(this, listOfPhonebook);
        Log.v("", "Adapter create");

        list.setAdapter(adapter);
        Log.v("", "adapter implement");

    list.setOnItemClickListener(new OnItemClickListener() {

        @Override

    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        // TODO Auto-generated method stub
            Toast.makeText(getBaseContext(), "You clciked ", Toast.LENGTH_LONG).show();

    }
    });
    }
}

why the toast can not show ? anyone can help me ?

This is my PhoneBookAdapter

package com.custom;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class PhoneBookAdapter extends BaseAdapter{
    private Context context;

    private List<PhoneList> listPhonebook;

    public PhoneBookAdapter(Context context, List<PhoneList> listPhonebook) {
        this.context = context;
        this.listPhonebook = listPhonebook;
    }

    public int getCount() {
        return listPhonebook.size();
    }

    public Object getItem(int position) {
        return listPhonebook.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup viewGroup) {
        PhoneList entry = listPhonebook.get(position);
        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.row, null);
        }
        TextView tvContact = (TextView) convertView.findViewById(R.id.textstatus);
        tvContact.setText(entry.getName());

        TextView tvPhone = (TextView) convertView.findViewById(R.id.textkonos);
        tvPhone.setText(entry.getPhone());

        TextView tvAlamat = (TextView) convertView.findViewById(R.id.textalamat);
        tvAlamat.setText(entry.getAlamat());

        return convertView;
    }

}

main.xml

<?xml version="1.0" encoding="utf-8"?>

   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Custom"
    android:textSize="10pt"
    android:paddingBottom="7px"
    android:background="#d5d5d5"
    android:textColor="#000000"
    />
<ListView
    android:paddingLeft="2px"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/list"
></ListView>

</LinearLayout>

row.xml

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="?android:attr/listPreferredItemHeight"

    android:padding="6dip">

    <CheckBox android:text=""
    android:layout_width="wrap_content"
    android:id="@+id/checkBox1"
    android:layout_height="fill_parent"
    android:layout_alignParentBottom="true"
    android:layout_alignParentTop="true"
    android:layout_alignParentRight="true"></CheckBox>

    <TextView
    android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/textnama"
            android:padding="7px"
            android:layout_alignParentLeft="true"
            android:text="Konos : "/>

    <TextView
       android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/textstatus"
            android:singleLine="true"
            android:padding="7px"

            android:layout_below="@+id/textnama"
            android:layout_alignParentLeft="true"
            android:text="haha"/>

     <TextView android:layout_width="wrap_content"
     android:text="hohohoho"
     android:layout_height="wrap_content"
     android:id="@+id/textkonos"
     android:paddingRight="3px"
     android:padding="7px"
     android:layout_above="@+id/textstatus"
     android:layout_toRightOf="@+id/textnama"></TextView>

    <TextView android:layout_width="wrap_content"
     android:text="-"
     android:layout_height="wrap_content"
     android:id="@+id/text"
     android:paddingRight="3px"
     android:padding="7px"
     android:layout_below="@+id/textkonos"
     android:layout_toRightOf="@+id/textstatus"></TextView>

     <TextView android:layout_width="wrap_content"
     android:text=""
     android:layout_height="wrap_content"
     android:id="@+id/textalamat"
     android:paddingRight="3px"
     android:padding="7px"
     android:layout_alignParentBottom="true"
     android:layout_alignLeft="@+id/textkonos"></TextView>

</RelativeLayout>

Body:
first put the breakpoint at toast and ensure that you are getting the call there and if you get the call and it is not showing then try this:

Toast.makeText(MainActivity.this, "You clciked ", Toast.LENGTH_LONG).show();


问:
TypeError: conv2d_v2() got an unexpected keyword argument 'filter
Was trying to run the code from a course from Coursera on my device with pretrained VGG model.
Getting this error while running the model. This is a question regarding neural style transfer with a pretrained model using a VGG model.

```<code>pp = pprint.PrettyPrinter(indent=4)
model = load_vgg_model("pretrained-model/imagenet-vgg-verydeep-19.mat")
pp.pprint(model)

</code>```
```<code>TypeError                                 Traceback (most recent call last)
<ipython-input-7-2a76ad487818> in <module>
      1 pp = pprint.PrettyPrinter(indent=4)
----> 2 model = load_vgg_model("pretrained-model/imagenet-vgg-verydeep-19.mat")
      3 pp.pprint(model)

D:\College\Machine learning\Coursera\c4\jovyan\work\week4\Neural Style Transfer\nst_utils.py in load_vgg_model(path)
    127     graph = {}
    128     graph['input']   = tf.Variable(np.zeros((1, CONFIG.IMAGE_HEIGHT, CONFIG.IMAGE_WIDTH, CONFIG.COLOR_CHANNELS)), dtype = 'float32')
--> 129     graph['conv1_1']  = _conv2d_relu(graph['input'], 0, 'conv1_1')
    130     graph['conv1_2']  = _conv2d_relu(graph['conv1_1'], 2, 'conv1_2')
    131     graph['avgpool1'] = _avgpool(graph['conv1_2'])

D:\College\Machine learning\Coursera\c4\jovyan\work\week4\Neural Style Transfer\nst_utils.py in _conv2d_relu(prev_layer, layer, layer_name)
    116         model at 'layer'.
    117         """
--> 118         return _relu(_conv2d(prev_layer, layer, layer_name))
    119
    120     def _avgpool(prev_layer):

D:\College\Machine learning\Coursera\c4\jovyan\work\week4\Neural Style Transfer\nst_utils.py in _conv2d(prev_layer, layer, layer_name)
    109         W = tf.constant(W)
    110         b = tf.constant(np.reshape(b, (b.size)))
--> 111         return tf.nn.conv2d(prev_layer, strides=[1, 1, 1, 1], padding='SAME') + b
    112
    113     def _conv2d_relu(prev_layer, layer, layer_name):

D:\Applications\Anaconda\lib\site-packages\tensorflow\python\util\dispatch.py in wrapper(*args, **kwargs)
    199     """Call target, and fall back on dispatchers if there is a TypeError."""
    200     try:
--> 201       return target(*args, **kwargs)
    202     except (TypeError, ValueError):
    203       # Note: convert_to_eager_tensor currently raises a ValueError, not a

TypeError: conv2d_v2() got an unexpected keyword argument 'filter'
</code>```

This is my function to load the model.

```<code>def load_vgg_model(path):

    vgg = scipy.io.loadmat(path)

    vgg_layers = vgg['layers']

    def _conv2d(prev_layer, layer, layer_name):

        W, b = _weights(layer, layer_name)
        W = tf.constant(W)
        b = tf.constant(np.reshape(b, (b.size)))
        return tf.nn.conv2d(prev_layer, filter=W, strides=[1, 1, 1, 1], padding='SAME') + b

    def _conv2d_relu(prev_layer, layer, layer_name):

        return _relu(_conv2d(prev_layer, layer, layer_name))

</code>```

I am pretty confused as the same model runs on Coursera but doesn't run on my PC.

答:
Try using:</p>
```<code>tf.nn.conv2d(prev_layer, W, strides=[1, 1, 1, 1], padding='SAME') + b
</code>```

Body:
Was trying to run the code from a course from Coursera on my device with pretrained VGG model.
Getting this error while running the model. This is a question regarding neural style transfer with a pretrained model using a VGG model.

pp = pprint.PrettyPrinter(indent=4)
model = load_vgg_model("pretrained-model/imagenet-vgg-verydeep-19.mat")
pp.pprint(model)

TypeError                                 Traceback (most recent call last)
<ipython-input-7-2a76ad487818> in <module>
      1 pp = pprint.PrettyPrinter(indent=4)
----> 2 model = load_vgg_model("pretrained-model/imagenet-vgg-verydeep-19.mat")
      3 pp.pprint(model)

D:\College\Machine learning\Coursera\c4\jovyan\work\week4\Neural Style Transfer\nst_utils.py in load_vgg_model(path)
    127     graph = {}
    128     graph['input']   = tf.Variable(np.zeros((1, CONFIG.IMAGE_HEIGHT, CONFIG.IMAGE_WIDTH, CONFIG.COLOR_CHANNELS)), dtype = 'float32')
--> 129     graph['conv1_1']  = _conv2d_relu(graph['input'], 0, 'conv1_1')
    130     graph['conv1_2']  = _conv2d_relu(graph['conv1_1'], 2, 'conv1_2')
    131     graph['avgpool1'] = _avgpool(graph['conv1_2'])

D:\College\Machine learning\Coursera\c4\jovyan\work\week4\Neural Style Transfer\nst_utils.py in _conv2d_relu(prev_layer, layer, layer_name)
    116         model at 'layer'.
    117         """
--> 118         return _relu(_conv2d(prev_layer, layer, layer_name))
    119
    120     def _avgpool(prev_layer):

D:\College\Machine learning\Coursera\c4\jovyan\work\week4\Neural Style Transfer\nst_utils.py in _conv2d(prev_layer, layer, layer_name)
    109         W = tf.constant(W)
    110         b = tf.constant(np.reshape(b, (b.size)))
--> 111         return tf.nn.conv2d(prev_layer, strides=[1, 1, 1, 1], padding='SAME') + b
    112
    113     def _conv2d_relu(prev_layer, layer, layer_name):

D:\Applications\Anaconda\lib\site-packages\tensorflow\python\util\dispatch.py in wrapper(*args, **kwargs)
    199     """Call target, and fall back on dispatchers if there is a TypeError."""
    200     try:
--> 201       return target(*args, **kwargs)
    202     except (TypeError, ValueError):
    203       # Note: convert_to_eager_tensor currently raises a ValueError, not a

TypeError: conv2d_v2() got an unexpected keyword argument 'filter'

This is my function to load the model.

def load_vgg_model(path):

    vgg = scipy.io.loadmat(path)

    vgg_layers = vgg['layers']

    def _conv2d(prev_layer, layer, layer_name):

        W, b = _weights(layer, layer_name)
        W = tf.constant(W)
        b = tf.constant(np.reshape(b, (b.size)))
        return tf.nn.conv2d(prev_layer, filter=W, strides=[1, 1, 1, 1], padding='SAME') + b

    def _conv2d_relu(prev_layer, layer, layer_name):

        return _relu(_conv2d(prev_layer, layer, layer_name))

I am pretty confused as the same model runs on Coursera but doesn't run on my PC.

Body:
Try using:

tf.nn.conv2d(prev_layer, W, strides=[1, 1, 1, 1], padding='SAME') + b


问:
How to add values from previous input to textarea
I am trying to add values from 2 of my inputs to the text area. I was able to find a solution to grab one of the inputs and hope someone can help me find a way to get another one. Also, is there a way to grab another element from the page for example php echo of student's first name?

Please see the picture
I would like this to say "Hey, student_first_name, my name is last_name from university_name, let's connect.

This is the code I have

```<code>    <script>
  // save the location of the name field
  var message_field = document.getElementById('university');
  var last_name_field = document.getElementById('last_name');

  //add an event listener to activate if the value of the field changes
  message_field.addEventListener('change', function() {
    // when the field changes run the following code

    // copy the text (value)
    var name = message_field.value;

    // concatenate it with the desired message
    var autoFill = 'Hi ' + name + ', thank you for visiting us!';

    // and paste it into the message field.
    document.getElementById('message').value = autoFill;
  })
</script>
</code>```

答:
```<code><script>
// save the location of the name field
var university = document.getElementById('university_name').value;
var last_name = document.getElementById('last_name').value;
var first_name = document.getElementById('student_first_name').value;

//add an event listener to activate if the value of the field changes
message_field.addEventListener('change', function() {
// when the field changes run the following code

// copy the text (value)
var name = message_field.value;

// concatenate it with the desired message
var autoFill = autoFill + university;
autoFill = autoFill + last_name;
autoFill = autoFill + first_name;

// and paste it into the message field.
document.getElementById('message').value = autoFill;
})
</script>
</code>```


问:
Pdf Reader+iphone
i want to make PDF reader app in phone.
where i have to implement search functionality.
in which i have to take the text of one page of .pdf file and have to do search functionality.

Is anyone had done it.
Please give me the sample code.
Thanks in advance

Editing the question.....
I had done how to search the key word,but i is working on .pdf file of one single page only.But not able to do how i have to search the word in multiple page.

Example:-
If i am having the .pdf file of multiple page.And now i want to implement the search functionality.Then how can i do it.
Please help me

答: Yes someone did it before. I used this kit also and it is great to search pages and highlight the result. It's PDFKitten by KurtCode (on Github).</p>

Title: Pdf Reader+iphone


问:
Have numpy argsort return an array of 2d indices?
If we have a 1d array

```<code>arr = np.random.randint(7, size=(5))
# [3 1 4 6 2]
print np.argsort(arr)
# [1 4 0 2 3] <= The indices in the sorted order
</code>```

If we have a 2d array

```<code>arr = np.random.randint(7, size=(3, 3))
# [[5 2 4]
# [3 3 3]
# [6 1 2]]
print np.argsort(arr)
# [[1 2 0]
# [0 1 2]
# [1 2 0]] <= It sorts each row
</code>```

What I need is the 2d indices that sort this matrix in its entirety. Something like this:

```<code># [[2 1] => 1
# [0 1] => 2
# [2 2] => 2
# .
# .
# .
# [0 2] => 4
# [0 0] => 5
# [2 0]] => 6
</code>```

How do I get "2d indices" for the sorting of a 2d array?

答:
Use np.take_along_axis to slices with your indices. Assuming you need to sort row-wise:

```<code>>>> arr = np.array([[5, 2, 4],
[3, 3, 3],
[6, 1, 2]])
>>> ind = arr.argsort(axis=-1)
>>> ind
array([[1, 2, 0],
       [0, 1, 2],
       [1, 2, 0]])
>>> np.take_along_axis(arr, ind, axis=-1)
array([[2, 4, 5],
       [3, 3, 3],
       [1, 2, 6]])
</code>```

Body:
If we have a 1d array

arr = np.random.randint(7, size=(5))
# [3 1 4 6 2]
print np.argsort(arr)
# [1 4 0 2 3] <= The indices in the sorted order

If we have a 2d array

arr = np.random.randint(7, size=(3, 3))
# [[5 2 4]
# [3 3 3]
# [6 1 2]]
print np.argsort(arr)
# [[1 2 0]
# [0 1 2]
# [1 2 0]] <= It sorts each row

What I need is the 2d indices that sort this matrix in its entirety. Something like this:

# [[2 1] => 1
# [0 1] => 2
# [2 2] => 2
# .
# .
# .
# [0 2] => 4
# [0 0] => 5
# [2 0]] => 6

How do I get "2d indices" for the sorting of a 2d array?

Body:
Use np.take_along_axis to slices with your indices. Assuming you need to sort row-wise:

>>> arr = np.array([[5, 2, 4],
[3, 3, 3],
[6, 1, 2]])
>>> ind = arr.argsort(axis=-1)
>>> ind
array([[1, 2, 0],
       [0, 1, 2],
       [1, 2, 0]])
>>> np.take_along_axis(arr, ind, axis=-1)
array([[2, 4, 5],
       [3, 3, 3],
       [1, 2, 6]])


问:
Finding the frequency of restaurant order cancellations by time in five second intervals
My data set looks like the below:

order_id
canceled_at
accepted_at
Delta

1
2021-07-02 23:30:26
2021-07-02 23:29:21
0 days 00:01:05

2
2021-09-17 20:35:44
2021-09-17 20:35:33
0 days 00:00:11

3
2021-05-21 11:47:28
2021-05-21 11:37:19
0 days 00:10:09

4
2021-06-18 7:34:06
2021-06-18 7:31:08
0 days 00:02:58

5
2021-05-16 15:54:34
2021-05-16 15:53:43
0 days 00:00:51

Delta is from the time the customer canceled the order to the time they put in their order. My goal is to find the frequency of restaurant order cancellations by time in five second intervals as well as mode, median, mean. However, I attempted the below:

df_new.resample('5S', on='Delta').count().head(5)

My results were not ideal:

Delta
order_id
canceled_at
accepted_at
Delta

0 days 00:00:01
656
656
656
656

0 days 00:00:06
1348
1348
1348
1348

0 days 00:00:11
3874
3874
3874
3874

0 days 00:00:16
3586
3586
3586
3586

0 days 00:00:21
2916
2916
2916
2916

I'm not sure what's happening and I was hoping maybe someone could help? Thanks so much in advance! I think the count is filling everything.

Ideally I would just want the 2 columns

Delta to be grouped every 5 seconds (the minimum Delta is 1 second so that looks right)

and the count of cancellations per 5 second intervals.

5 Second Intervals
Count of Cancellations

1
25

6
30

11
6

...

...

1 minute and 1 second
32

答:
```<code>(((df['Delta'].dt.seconds - 1) // 5) * 5 + 1).value_counts().reset_index()
</code>```

The maths converts each Delta into a group-label. The // takes the quotient of division of 5 so that 1, 2, 3, 4, 5 seconds (after subtracted by 1) all become group 0. We then revert it back into seconds by * 5 + 1. value_counts does exactly the counting. reset_index gives you back a dataframe.

Body:
(((df['Delta'].dt.seconds - 1) // 5) * 5 + 1).value_counts().reset_index()

The maths converts each Delta into a group-label. The // takes the quotient of division of 5 so that 1, 2, 3, 4, 5 seconds (after subtracted by 1) all become group 0. We then revert it back into seconds by * 5 + 1. value_counts does exactly the counting. reset_index gives you back a dataframe.


问:
How to run jar file in Azure Data Factory (ADF)
I Have a Jar file. that takes arguments and perform certain actions.

EX:

```<code>java -jar MyJavaEx.jar dev
</code>```

this jar file will execute some logic inside it and then prints some log.

I want run this job daily using ADF trigger. how to do this?

if this is not possible what's the best alternative approach.

答:
If you're looking for a lightweight, serverless way to run your Java app, I'd consider Azure Functions.

You might find this document helpful:

Azure Functions Java developer guide

Body:
I Have a Jar file. that takes arguments and perform certain actions.

EX:

java -jar MyJavaEx.jar dev

this jar file will execute some logic inside it and then prints some log.

I want run this job daily using ADF trigger. how to do this?

if this is not possible what's the best alternative approach.


问:
Problems with constructor resolution order
Consider the following constructors for T:

```<code>struct T {
    T(const bool) { std::cout << "T(const bool)" << endl; }
    T(const std::string&) { std::cout << "T(const std::string&)" << endl; }
};

T t("");
</code>```

Why does T(const bool) take precedence over T(const std::string&) when constructing t?

Since the above precedence might cause confusion to users expecting T(const std::string&) to be called, what can I do to have T(const std::string&) implicitly called when passing string literals to the constructor of T. For now the only work around I have found is to add another constructor, which takes the highest precedence:

```<code>T(const char* s)
{
    std::cout << "T(const char*)" << endl;
    *this = std::string(s);
}
</code>```

Apart from the above solution, declaring explicit T(const bool) to avoid confusion does not solve the above problem: in this case, although T t = "" is now prohibited, why is the form T t("") is still allowed and does call T(const bool) ?

答:
Because a user-defined conversion is not considered if a built-in one is available.

Use the third constructor, one that takes const char*. There's no better way.

Body:
Consider the following constructors for T:

struct T {
    T(const bool) { std::cout << "T(const bool)" << endl; }
    T(const std::string&) { std::cout << "T(const std::string&)" << endl; }
};

T t("");

Why does T(const bool) take precedence over T(const std::string&) when constructing t?

Since the above precedence might cause confusion to users expecting T(const std::string&) to be called, what can I do to have T(const std::string&) implicitly called when passing string literals to the constructor of T. For now the only work around I have found is to add another constructor, which takes the highest precedence:

T(const char* s)
{
    std::cout << "T(const char*)" << endl;
    *this = std::string(s);
}

Apart from the above solution, declaring explicit T(const bool) to avoid confusion does not solve the above problem: in this case, although T t = "" is now prohibited, why is the form T t("") is still allowed and does call T(const bool) ?


问:
Twilio Voice calls using sub account
I have more than 10 subaccounts in twilio. On average a subaccount has 2 phone numbers. Now I'm trying to add voice call function. According to the documentation, I have to create Twiml applications and Mobile Push Credentials (to receive calls) and configure each phone number with server urls (https://github.com/twilio/voice-quickstart-android/blob/d7d4f0658e145eb94ab8f5e34f6fd17314e7ab17/README.md)

My questions are,

Should I create one twiml application per subaccount ?

Should I create one Mobile Push Credentials per subaccount?

答:
Twilio developer evangelist here.

You will indeed need a TwiML application per subaccount. That way you can validate the requests made to each endpoint using the auth token from that subaccount. Also, it would allow you to handle individual subaccount call flows independently.

You will also need to create the mobile push credentials per subaccount. Subaccounts can't use cross subaccount resources.

If you do want all your numbers to share resources like TwiML applications and push credentials then you should move all of the numbers from subaccounts to the main account.

Title: Twilio Voice calls using sub account


问:
Gettng exception while using findBy using JPARepository?
I have 2 tables Employee and Address. Each have primary key sequence_id and address_Id  which is generated through sequence.

Employee Class:

```<code>public class Employee {
    @Id
    @Column(name = "sequence_id")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "emp_seq")
    @SequenceGenerator(sequenceName = "emp_seq", allocationSize = 1, name = "emp_seq")
    private Long sequenceId;

    @Column(name = "emp_id")
    private String empId;

    @Column(name = "joiningDate")
    private Date businessDate;

    @OneToOne(mappedBy = "employee", cascade = CascadeType.ALL)
    private Address address;
}
</code>```

Address Class

public class Address {

```<code>@Id
@Column(name = "address_id")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "address_seq")
@SequenceGenerator(sequenceName = "address_seq", allocationSize = 1, name = "address_seq")
private Long addressID;

@Column(name = "street")
private String street;

@OneToOne
@JoinColumn(name = "emp_id", referencedColumnName = "emp_id")
@JsonIgnore
private Employee employee;
</code>```

}

I am using JPARepository to save both entities. here is my main class.

```<code>Employee e = Employee.builder().businessDate(new Date())
        .empId("thinkerId").build();
Address a = Address.builder().street("32nd Street")
        .employee(e).build();
e.setAddress(a);
empRepository.save(e);
</code>```

Code runs successfully and save both into address and employee table.

But it failed while usig findAll() / findById method?

```<code>Optional<Employeee> emp = employeeRepository.findById(23l); //**FAILING**
</code>```

Error --

```<code>[2022.02.08 09:08:13:401] [http-nio-8997-exec-2] [o.h.e.j.s.SqlExceptionHelper] [WARN ] - SQL Error: 1722, SQLState: 42000
[2022.02.08 09:08:13:403] [http-nio-8997-exec-2] [o.h.e.j.s.SqlExceptionHelper] [ERROR] - ORA-01722: invalid number

[2022.02.08 09:08:13:430] [http-nio-8997-exec-2] [o.h.e.i.DefaultLoadEventListener] [INFO ] - HHH000327: Error performing load command
org.hibernate.exception.SQLGrammarException: could not extract ResultSet
</code>```

While using findAll() method, I got below error:

```<code>org.springframework.orm.jpa.JpaSystemException: Error accessing field [private java.lang.String com.msci.rt.monitoring.entity.Employee.empId] by reflection for persistent property [com.msci.rt.monitoring.entity.Employee#empId] :
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private java.lang.String Employee.emp_ID] by reflection for persistent property [empId] : 22
    ... 85 more
Caused by: java.lang.IllegalArgumentException: Can not set java.lang.String field Employee.empId to null value
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
    at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:58)
    at sun.reflect.UnsafeObjectFieldAccessorImpl.get(UnsafeObjectFieldAccessorImpl.java:36)
    at java.lang.reflect.Field.get(Field.java:393)
    at org.hibernate.property.access.spi.GetterFieldImpl.get(GetterFieldImpl.java:71)
</code>```

How can i get "thinkerId" as value in Address table?

Thank you.

答:
The error message from Hibernate seems to be saying that the database is expecting a number somewhere, but instead is getting something else, possibly a string.  If you examine your Employee entity class, you'll notice that you have defined the join column emp_id to be a string.  However the primary key field there is called sequence_id.  I suggest making the PK column the join field.  Use this version:

public class Employee {
    @Id
    @Column(name = "emp_id")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "emp_seq")
    @SequenceGenerator(sequenceName = "emp_seq", allocationSize = 1, name = "emp_seq")
    private Long empId;

    @Column(name = "joiningDate")
    private Date businessDate;

    @OneToOne(mappedBy = "employee", cascade = CascadeType.ALL)
    private Address address;
}
```

Body:
I have 2 tables Employee and Address. Each have primary key sequence_id and address_Id  which is generated through sequence.

Employee Class:

public class Employee {
    @Id
    @Column(name = "sequence_id")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "emp_seq")
    @SequenceGenerator(sequenceName = "emp_seq", allocationSize = 1, name = "emp_seq")
    private Long sequenceId;

    @Column(name = "emp_id")
    private String empId;

    @Column(name = "joiningDate")
    private Date businessDate;

    @OneToOne(mappedBy = "employee", cascade = CascadeType.ALL)
    private Address address;
}

Address Class

public class Address {

@Id
@Column(name = "address_id")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "address_seq")
@SequenceGenerator(sequenceName = "address_seq", allocationSize = 1, name = "address_seq")
private Long addressID;

@Column(name = "street")
private String street;

@OneToOne
@JoinColumn(name = "emp_id", referencedColumnName = "emp_id")
@JsonIgnore
private Employee employee;

}

I am using JPARepository to save both entities. here is my main class.

Employee e = Employee.builder().businessDate(new Date())
        .empId("thinkerId").build();
Address a = Address.builder().street("32nd Street")
        .employee(e).build();
e.setAddress(a);
empRepository.save(e);

Code runs successfully and save both into address and employee table.

But it failed while usig findAll() / findById method?

Optional<Employeee> emp = employeeRepository.findById(23l); //**FAILING**

Error --

[2022.02.08 09:08:13:401] [http-nio-8997-exec-2] [o.h.e.j.s.SqlExceptionHelper] [WARN ] - SQL Error: 1722, SQLState: 42000
[2022.02.08 09:08:13:403] [http-nio-8997-exec-2] [o.h.e.j.s.SqlExceptionHelper] [ERROR] - ORA-01722: invalid number

[2022.02.08 09:08:13:430] [http-nio-8997-exec-2] [o.h.e.i.DefaultLoadEventListener] [INFO ] - HHH000327: Error performing load command
org.hibernate.exception.SQLGrammarException: could not extract ResultSet

While using findAll() method, I got below error:

org.springframework.orm.jpa.JpaSystemException: Error accessing field [private java.lang.String com.msci.rt.monitoring.entity.Employee.empId] by reflection for persistent property [com.msci.rt.monitoring.entity.Employee#empId] :
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private java.lang.String Employee.emp_ID] by reflection for persistent property [empId] : 22
    ... 85 more
Caused by: java.lang.IllegalArgumentException: Can not set java.lang.String field Employee.empId to null value
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
    at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:58)
    at sun.reflect.UnsafeObjectFieldAccessorImpl.get(UnsafeObjectFieldAccessorImpl.java:36)
    at java.lang.reflect.Field.get(Field.java:393)
    at org.hibernate.property.access.spi.GetterFieldImpl.get(GetterFieldImpl.java:71)

How can i get "thinkerId" as value in Address table?

Thank you.


问:
what's the relationship between system signal and Com signal in autosar
what's the relationship between system signal and Com signal in autosar.?

for my knowledge, Com signal is configured in Com module in BasicSoftware

答:
AUTOSAR_TPS_SystemTemplate describes this in the chapter 5.2 DataMapping.

In short for a Sender/Receiver interface, the data elements (VariableDataPrototype) of a SWCs SenderReceiver port are mapped to SystemSignals and SystemSignalGroups, when the communication between two SWCs are crossing the ECU boundaries, because the SWCs are mapped to different ECUs (Inter-ECU communication).

The SystemSignalGroups are then mapped to ISignalGroups and SystemSignals to ISignals. These ISignals and ISignalGroups are mapped to ISignalIPdus and these are again mapped to Frames (e.g. CanFrames).

The ISignals and ISignalGroups are, what will be configured in EcuConfiguration in  Com or LdCom as ComSignals and ComSignalGroups.

The SystemSignals and SystemSignalGroups are, what the RTE configurator will do, to create the mapping of Rte_Read/Write functions to the calls of Com_Send/ReceiveSignal() / Com_Send/ReceiveSignalGroup().