问:
KotlinNullPointerException when rotating the screen on Fragment with map and localization
I have a kotlin.KotlinNullPointerException at line:

```<code>val locationmanager=context!!.getSystemService(Context.LOCATION_SERVICE) as LocationManager
</code>```

When I rotate my screen. This line is in function in:

```<code>class MyMapFragment: Fragment(),OnMapReadyCallback
</code>```

答:
The activity is destroyed and re-created when you rotate the phone. This means while the activity is being re-created the context will be null, and you must be trying to access it at some point during this.

I'm not sure where you have the line of code you posted, but if you want to guarantee a non-null context you should wait till the activity is created.

```<code>var locationmanager: LocationManager? = null

override fun onActivityCreated(savedInstanceState: Bundle?) {
    val context = context ?: return // this line gets a non-null context and is safer than !!

    locationmanager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager

    ...
</code>```

In general, when accessing things that are nullable in Kotlin, it is much preferred to use ? instead of !! to avoid any null pointer exceptions

Body:
I have a kotlin.KotlinNullPointerException at line:

val locationmanager=context!!.getSystemService(Context.LOCATION_SERVICE) as LocationManager

When I rotate my screen. This line is in function in:

class MyMapFragment: Fragment(),OnMapReadyCallback

Body:
The activity is destroyed and re-created when you rotate the phone. This means while the activity is being re-created the context will be null, and you must be trying to access it at some point during this.

I'm not sure where you have the line of code you posted, but if you want to guarantee a non-null context you should wait till the activity is created.

var locationmanager: LocationManager? = null

override fun onActivityCreated(savedInstanceState: Bundle?) {
    val context = context ?: return // this line gets a non-null context and is safer than !!

    locationmanager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager

    ...

In general, when accessing things that are nullable in Kotlin, it is much preferred to use ? instead of !! to avoid any null pointer exceptions


来源: stackexchange

问:
Windows Event Viewer xPath query doesn't work on certain strings. Escape characters?
I am trying to return an event log entry from the Windows security log using xPath (in PowerShell, in Event Viewer UI) and not succeeding.

This query doesn't work, as it returns zero results event though there is are appropriate entries in the log:

```<code>Get-WinEvent -FilterXPath "*[EventData[Data[@Name='CommandLine']='-ExecutionPolicy ByPass -File Do-Something.ps1']]" -LogName Security
</code>```

The syntax of the query seems fine as changing the query value will return the expected results:

```<code>Get-WinEvent -FilterXPath "*[EventData[Data[@Name='CommandLine']='\??\C:\Windows\system32\conhost.exe 0xffffffff -ForceV1']]" -LogName Security
</code>```

Same results if formatted as -FilterXML.

Alternative query strategy works, though is not efficient at all with big logs:

```<code>Get-WinEvent -LogName Security | Where-Object -Property Message -match '-ExecutionPolicy ByPass -File Do-Something.ps1'
</code>```

So it seems that there is something in the xPath query value that is not quite kosher. I don't know what it is. What am I missing?

Here is EventData for the desired hit:

```<code>- <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
- <System>
  <Provider Name="Microsoft-Windows-Security-Auditing" Guid="{54849625-5478-4994-a5ba-3e3b0328c30d}" />
  <EventID>4688</EventID>
  <Version>2</Version>
  <Level>0</Level>
  <Task>13312</Task>
  <Opcode>0</Opcode>
  <Keywords>0x8020000000000000</Keywords>
  <TimeCreated SystemTime="2020-02-19T15:17:13.982780900Z" />
  <EventRecordID>SCRUBBED</EventRecordID>
  <Correlation />
  <Execution ProcessID="4" ThreadID="256" />
  <Channel>Security</Channel>
  <Computer>SCRUBBED</Computer>
  <Security />
  </System>
- <EventData>
  <Data Name="SubjectUserSid">SCRUBBED</Data>
  <Data Name="SubjectUserName">SCRUBBED</Data>
  <Data Name="SubjectDomainName">SCRUBBED</Data>
  <Data Name="SubjectLogonId">SCRUBBED</Data>
  <Data Name="NewProcessId">SCRUBBED</Data>
  <Data Name="NewProcessName">C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe</Data>
  <Data Name="TokenElevationType">%%1937</Data>
  <Data Name="ProcessId">0x41c</Data>
  <Data Name="CommandLine">-ExecutionPolicy ByPass -File Do-Something.ps1</Data>
  <Data Name="TargetUserSid">S-1-0-0</Data>
  <Data Name="TargetUserName">-</Data>
  <Data Name="TargetDomainName">-</Data>
  <Data Name="TargetLogonId">0x0</Data>
  <Data Name="ParentProcessName">C:\Windows\System32\gpscript.exe</Data>
  <Data Name="MandatoryLabel">SCRUBBED</Data>
  </EventData>
  </Event>
</code>```

Here is EventData for the other hit that works but isn't interesting to me:

```<code>- <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
- <System>
  <Provider Name="Microsoft-Windows-Security-Auditing" Guid="{54849625-5478-4994-a5ba-3e3b0328c30d}" />
  <EventID>4688</EventID>
  <Version>2</Version>
  <Level>0</Level>
  <Task>13312</Task>
  <Opcode>0</Opcode>
  <Keywords>0x8020000000000000</Keywords>
  <TimeCreated SystemTime="2020-02-19T15:21:21.753690000Z" />
  <EventRecordID>SCRUBBED</EventRecordID>
  <Correlation />
  <Execution ProcessID="4" ThreadID="96" />
  <Channel>Security</Channel>
  <Computer>SCRUBBED</Computer>
  <Security />
  </System>
- <EventData>
  <Data Name="SubjectUserSid">SCRUBBED</Data>
  <Data Name="SubjectUserName">SCRUBBED</Data>
  <Data Name="SubjectDomainName">SCRUBBED</Data>
  <Data Name="SubjectLogonId">SCRUBBED</Data>
  <Data Name="NewProcessId">SCRUBBED</Data>
  <Data Name="NewProcessName">C:\Windows\System32\conhost.exe</Data>
  <Data Name="TokenElevationType">%%1936</Data>
  <Data Name="ProcessId">0x690</Data>
  <Data Name="CommandLine">\??\C:\Windows\system32\conhost.exe 0xffffffff -ForceV1</Data>
  <Data Name="TargetUserSid">S-1-0-0</Data>
  <Data Name="TargetUserName">-</Data>
  <Data Name="TargetDomainName">-</Data>
  <Data Name="TargetLogonId">0x0</Data>
  <Data Name="ParentProcessName">C:\Program Files\Windows Defender\MpCmdRun.exe</Data>
  <Data Name="MandatoryLabel">SCRUBBED</Data>
  </EventData>
  </Event>
</code>```

答:
Try to see if this works:</p>

```<code>Get-WinEvent -LogName Security -FilterXPath "//Event//Data[@Name='CommandLine'][text()='-ExecutionPolicy ByPass -File Do-Something.ps1']"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to return an event log entry from the Windows security log using xPath (in PowerShell, in Event Viewer UI) and not succeeding.

This query doesn't work, as it returns zero results event though there is are appropriate entries in the log:

Get-WinEvent -FilterXPath "*[EventData[Data[@Name='CommandLine']='-ExecutionPolicy ByPass -File Do-Something.ps1']]" -LogName Security

The syntax of the query seems fine as changing the query value will return the expected results:

Get-WinEvent -FilterXPath "*[EventData[Data[@Name='CommandLine']='\??\C:\Windows\system32\conhost.exe 0xffffffff -ForceV1']]" -LogName Security

Same results if formatted as -FilterXML.

Alternative query strategy works, though is not efficient at all with big logs:

Get-WinEvent -LogName Security | Where-Object -Property Message -match '-ExecutionPolicy ByPass -File Do-Something.ps1'

So it seems that there is something in the xPath query value that is not quite kosher. I don't know what it is. What am I missing?

Here is EventData for the desired hit:

- <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
- <System>
  <Provider Name="Microsoft-Windows-Security-Auditing" Guid="{54849625-5478-4994-a5ba-3e3b0328c30d}" />
  <EventID>4688</EventID>
  <Version>2</Version>
  <Level>0</Level>
  <Task>13312</Task>
  <Opcode>0</Opcode>
  <Keywords>0x8020000000000000</Keywords>
  <TimeCreated SystemTime="2020-02-19T15:17:13.982780900Z" />
  <EventRecordID>SCRUBBED</EventRecordID>
  <Correlation />
  <Execution ProcessID="4" ThreadID="256" />
  <Channel>Security</Channel>
  <Computer>SCRUBBED</Computer>
  <Security />
  </System>
- <EventData>
  <Data Name="SubjectUserSid">SCRUBBED</Data>
  <Data Name="SubjectUserName">SCRUBBED</Data>
  <Data Name="SubjectDomainName">SCRUBBED</Data>
  <Data Name="SubjectLogonId">SCRUBBED</Data>
  <Data Name="NewProcessId">SCRUBBED</Data>
  <Data Name="NewProcessName">C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe</Data>
  <Data Name="TokenElevationType">%%1937</Data>
  <Data Name="ProcessId">0x41c</Data>
  <Data Name="CommandLine">-ExecutionPolicy ByPass -File Do-Something.ps1</Data>
  <Data Name="TargetUserSid">S-1-0-0</Data>
  <Data Name="TargetUserName">-</Data>
  <Data Name="TargetDomainName">-</Data>
  <Data Name="TargetLogonId">0x0</Data>
  <Data Name="ParentProcessName">C:\Windows\System32\gpscript.exe</Data>
  <Data Name="MandatoryLabel">SCRUBBED</Data>
  </EventData>
  </Event>

Here is EventData for the other hit that works but isn't interesting to me:

- <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
- <System>
  <Provider Name="Microsoft-Windows-Security-Auditing" Guid="{54849625-5478-4994-a5ba-3e3b0328c30d}" />
  <EventID>4688</EventID>
  <Version>2</Version>
  <Level>0</Level>
  <Task>13312</Task>
  <Opcode>0</Opcode>
  <Keywords>0x8020000000000000</Keywords>
  <TimeCreated SystemTime="2020-02-19T15:21:21.753690000Z" />
  <EventRecordID>SCRUBBED</EventRecordID>
  <Correlation />
  <Execution ProcessID="4" ThreadID="96" />
  <Channel>Security</Channel>
  <Computer>SCRUBBED</Computer>
  <Security />
  </System>
- <EventData>
  <Data Name="SubjectUserSid">SCRUBBED</Data>
  <Data Name="SubjectUserName">SCRUBBED</Data>
  <Data Name="SubjectDomainName">SCRUBBED</Data>
  <Data Name="SubjectLogonId">SCRUBBED</Data>
  <Data Name="NewProcessId">SCRUBBED</Data>
  <Data Name="NewProcessName">C:\Windows\System32\conhost.exe</Data>
  <Data Name="TokenElevationType">%%1936</Data>
  <Data Name="ProcessId">0x690</Data>
  <Data Name="CommandLine">\??\C:\Windows\system32\conhost.exe 0xffffffff -ForceV1</Data>
  <Data Name="TargetUserSid">S-1-0-0</Data>
  <Data Name="TargetUserName">-</Data>
  <Data Name="TargetDomainName">-</Data>
  <Data Name="TargetLogonId">0x0</Data>
  <Data Name="ParentProcessName">C:\Program Files\Windows Defender\MpCmdRun.exe</Data>
  <Data Name="MandatoryLabel">SCRUBBED</Data>
  </EventData>
  </Event>

Body:
Try to see if this works:

Get-WinEvent -LogName Security -FilterXPath "//Event//Data[@Name='CommandLine'][text()='-ExecutionPolicy ByPass -File Do-Something.ps1']"


问:
Javascript insert array in array
Source from wi2l.de/sof.html

var x = -1;
var a = new Array(9);
var i = new Array(2);

x = x + 1;
a[x] = ["a", "b"];
x = x + 1;
a[x] = ["c", "d"];
i[0] = "e";
i[1] = "f";
x = x + 1;
a[x] = i;
i[0] = "g";
i[1] = "h";
x = x + 1;
a[x] = i;

console.log(a[1] + " " + a[2] + " " + a[3]);```

result is c,d g,h g,h but should be c,d e,f g,h.

答:
```<code>i[0] = "e"; // these two lines
i[1] = "f";
x = x + 1;
a[x] = i;
i[0] = "g"; // are changing the same array as these two lines
i[1] = "h";
</code>```

So when you add the array i in, and change it's value, it changes it everywhere you used that array. It doesn't make a copy or anything.

Title: Javascript insert array in array

Body:
Source from wi2l.de/sof.html

var x = -1;
var a = new Array(9);
var i = new Array(2);

x = x + 1;
a[x] = ["a", "b"];
x = x + 1;
a[x] = ["c", "d"];
i[0] = "e";
i[1] = "f";
x = x + 1;
a[x] = i;
i[0] = "g";
i[1] = "h";
x = x + 1;
a[x] = i;

console.log(a[1] + " " + a[2] + " " + a[3]);

result is c,d g,h g,h but should be c,d e,f g,h.

Body:
i[0] = "e"; // these two lines
i[1] = "f";
x = x + 1;
a[x] = i;
i[0] = "g"; // are changing the same array as these two lines
i[1] = "h";

So when you add the array i in, and change it's value, it changes it everywhere you used that array. It doesn't make a copy or anything.


问:
Dynamically changing the bound entity of a list box on a canvas
I'm wondering if anyone has come across this issue.
I have two radio buttons on a canvas app that I am attempting to control the values displayed within a list box.

RadioButtons.Items: ["SomeValueA","SomeValueB"]

The list box control should be getting reset whenever the value of the radio button changes.

```<code>UpdateContext({resetList: !resetList});
UpdateContext({resetList: !resetList});
Reset(lbListbox);

lbListbox.Reset: resetList
</code>```

For the list box itself I have the following for Items:

```<code>Switch(
    RadioButtons.Selected.Value,
    "SomeValueA",
    Sort(
        EntityA.FieldName,
        Descending
    ),
    "SomeValueB",
    Sort(
        EntityB.'Some other field name',
        Descending
    )
)
</code>```

The problem is when I select 'SomeValueA' the list box properly populates with the values from EntityA.FieldName but when I then select 'SomeValueB' from the radio buttons the list box blanks out with empty records.  There appears to be items in the list box that I can scroll through and select but not see.

If I put two list boxes on the screen and set their Items event to the specific entity the values show up properly in both list boxes so I know the entity naming/field is correct.

I've tried it without the reset of the list box, I've tried it using collections made out of the entity records.

Has anyone come across this who maybe has a solution.  I was going to try to put two list boxes on top of one another and either hide/show or bring to front the active list but that also doesn't want to work.

thanks!

答:
(Received this post from another source, figured I might as well post back here as well)

Got this to work, but it was a bit finicky. The catch seemed to be giving the List a value-pairing table, instead of just a list of values.
First I collected the Option Sets from CDS, and added a column to indicate the source name, for reference. This could easily be combined into a single collection, and then filtered later but I was thinking simple.

```<code>ClearCollect(colOptionSet1,AddColumns(Choices('Ownership (Accounts)'),"appSource","Ownership"));
ClearCollect(colOptionSet2,AddColumns(Choices('Preferred Method of Contact (Accounts)'),"appSource","Preferred Method"));
</code>```

Next added a Radio button identical to yours.
Then added a List control with Items equal to

```<code>If( Radio1.Selected.Value = "SomeValueA", colOptionSet1, Radio1.Selected.Value = "SomeValueB", colOptionSet2 )
</code>```

You may need to use the right-side property pane to toggle between Value and "appSource" (from collections above), but this did allow me to toggle between two separate Option Set fields in a single list.

Patching/writing this back is gonna be another hurdle.

Body:
I'm wondering if anyone has come across this issue.
I have two radio buttons on a canvas app that I am attempting to control the values displayed within a list box.

RadioButtons.Items: ["SomeValueA","SomeValueB"]

The list box control should be getting reset whenever the value of the radio button changes.

UpdateContext({resetList: !resetList});
UpdateContext({resetList: !resetList});
Reset(lbListbox);

lbListbox.Reset: resetList

For the list box itself I have the following for Items:

Switch(
    RadioButtons.Selected.Value,
    "SomeValueA",
    Sort(
        EntityA.FieldName,
        Descending
    ),
    "SomeValueB",
    Sort(
        EntityB.'Some other field name',
        Descending
    )
)

The problem is when I select 'SomeValueA' the list box properly populates with the values from EntityA.FieldName but when I then select 'SomeValueB' from the radio buttons the list box blanks out with empty records.  There appears to be items in the list box that I can scroll through and select but not see.

If I put two list boxes on the screen and set their Items event to the specific entity the values show up properly in both list boxes so I know the entity naming/field is correct.

I've tried it without the reset of the list box, I've tried it using collections made out of the entity records.

Has anyone come across this who maybe has a solution.  I was going to try to put two list boxes on top of one another and either hide/show or bring to front the active list but that also doesn't want to work.

thanks!

Body:
(Received this post from another source, figured I might as well post back here as well)

Got this to work, but it was a bit finicky. The catch seemed to be giving the List a value-pairing table, instead of just a list of values.
First I collected the Option Sets from CDS, and added a column to indicate the source name, for reference. This could easily be combined into a single collection, and then filtered later but I was thinking simple.

ClearCollect(colOptionSet1,AddColumns(Choices('Ownership (Accounts)'),"appSource","Ownership"));
ClearCollect(colOptionSet2,AddColumns(Choices('Preferred Method of Contact (Accounts)'),"appSource","Preferred Method"));

Next added a Radio button identical to yours.
Then added a List control with Items equal to

If( Radio1.Selected.Value = "SomeValueA", colOptionSet1, Radio1.Selected.Value = "SomeValueB", colOptionSet2 )

You may need to use the right-side property pane to toggle between Value and "appSource" (from collections above), but this did allow me to toggle between two separate Option Set fields in a single list.

Patching/writing this back is gonna be another hurdle.


问:
Concatenate text nodes by milestone element using XSLT 2.0
My XML files have TEI milestone elements like <handShift new="#DP1053/>; there's always one at the start of the <text> content, but after that there are sometimes a handful of tags of this kind with one of two or three distinct attribute values scattered through the <text> element to indicate where a particular scribe picks up after the last. The value of attribute @new points to an @xml:id definition in the TEI header, registered as an attribute to a <handNote/> element.

My aim in XSLT 2.0 is to concatenate the text written by each scribe so I can query each scribe's work independently. I wonder whether a recommended solution would entail group-starting-with, but I haven't yet wrapped my head around the preprocessing involved (I'd be grateful for pointers). Instead, my own instinct is to perform

a for-each loop iterating over the scribal hands, running

a string-join

on all text nodes

where a preceding <handShift/> with a value of attribute @new matching the hand processed in the current loop iteration is nearer than a preceding <handShift/> where the attribute value does not match.

My trial syntax in an XSLT 2.0 stylesheet transforming to HTML is as follows:

```<code><xsl:for-each select="//tei:handNote[@xml:id != '']">
    <xsl:variable name="hand" select="./@xml:id"/>
    <p><xsl:value-of select="$hand"/>: <xsl:value-of select="string-join(//tei:text//text()[preceding-sibling::tei:handShift[@new = concat('#',$hand)] >> preceding-sibling::tei:handShift[@new != concat('#',$hand)]])"/></p>
</xsl:for-each>
</code>```

However, this only returns the text node(s) following the final milestone in the text, and only in the for-each iteration that selects for the attribute value matching that final milestone. I've surely got the >> statement wrong and would be grateful for any advice either with this approach or for a different, grouping-based approach.

I should probably mention that once I've mastered this concatenation, I'll have to add any <add hand="DP1054">addition</add>-type content (i.e. revisions by hands not matching that of the current stint) into the equation, by excluding nonmatching content of this nature and including matching content situated within nonmatching scribal stints, but I don't necessarily foresee this having to be added to the concatenation in the "correct" place. I thus should be able to account for these in two fairly straightforward additional steps, but the initial concatenation or grouping solution has to allow for the exclusion of nodes with nonmatching attribute values, and of any other elements I may wish to exclude (e.g. <expan> in the below example).

Here is a mock XML file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE TEI>
<TEI>
 <teiHeader>
  <fileDesc/>
   <sourceDesc>
    <msDesc>
     <physDesc>
      <handDesc>
       <handNote xml:id="DP1054"/>
       <handNote xml:id="DP1053"/>
      </handDesc>
     </physDesc>
    </msDesc>
   </sourceDesc>
 </teiHeader>
 <text>
  <body>
    <p><handShift new="#DP1054"/>I'LL REPRESENT THE WORK OF HAND 1054 IN ALLCAPS <handShift new="#DP1053"/>and I'll represent the work of hand 1053 in lowercase <handShift new="#DP1054"/>THE IDEA BEING THAT IN THE END ALL UPPERCASE TEXT SHOULD BE CONCATENATED <handShift new="#DP1053"/>separately from the sentence case content. Of course reality is a little more <add hand="#DP1054">COMPLEX</add>: we have <hi rend="color(green)">other nodes intervening</hi>, <handShift new="#DP1054"/>AND I WONDER WHETHER THESE WILL MESS WITH THE CONCEPT OF <choice>
     <abbr>SBLS</abbr>
     <expan>S<ex>I</ex>BL<ex>ING</ex>S</expan>
    </choice> <handShift new="#DP1053"/> (I will filter out nodes with `tei:expan` ancestors and nonmatching `add` elements; that's not the part I am having difficulty with).</p>
  </body>
 </text>
</TEI>
</code>```

答:
I think group-starting-with can help, here is an example that stores the result in an XPath 3.1 map (well, the grouping gives a sequence of maps and the map:merge functions merges them into a single map from id to nodes after a handShift of that id):

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:map="http://www.w3.org/2005/xpath-functions/map"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xpath-default-namespace="http://www.tei-c.org/ns/1.0"
    exclude-result-prefixes="#all"
    version="3.0">

  <xsl:output method="html" indent="yes" html-version="5"/>

  <xsl:variable name="note-map-sequence" as="map(xs:string, node()*)*">
      <xsl:for-each-group select="//body/p/node()" group-starting-with="handShift">
          <xsl:map-entry key="substring(@new, 2)" select="current-group()"/>
      </xsl:for-each-group>
  </xsl:variable>

  <xsl:variable name="note-map" as="map(xs:string, node()*)"
    select="map:merge($note-map-sequence, map { 'duplicates' : 'combine' })"/>

  <xsl:template match="/">
    <html>
      <head>
        <title>.NET XSLT Fiddle Example</title>
      </head>
      <body>
        <xsl:apply-templates select="//handNote"/>
      </body>
    </html>
  </xsl:template>

  <xsl:template match="handNote">
      <p>
        <xsl:value-of select="@xml:id"/>:
        <xsl:apply-templates select="$note-map(@xml:id)"/>
      </p>
  </xsl:template>

</xsl:stylesheet>
</code>```

https://xsltfiddle.liberty-development.net/bFWRApk has an online sample outputting

```<code><!DOCTYPE HTML>
<html>
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>.NET XSLT Fiddle Example</title></head>
   <body>
      <p>DP1054:
         I'LL REPRESENT THE WORK OF HAND 1054 IN ALLCAPS THE IDEA BEING THAT IN THE END ALL UPPERCASE TEXT SHOULD BE CONCATENATED AND I WONDER WHETHER THESE WILL MESS WITH THE CONCEPT OF
         SBLS
         SIBLINGS

      </p>
      <p>DP1053:
         and I'll represent the work of hand 1053 in lowercase separately from the sentence case content. Of course reality is a little more COMPLEX: we have other nodes intervening,  (I will filter out nodes with `tei:expan` ancestors and nonmatching `add` elements;
         that's not the part I am having difficulty with).
      </p>
   </body>
</html>
</code>```

XSLT 3 with XPath 3.1 is available since Saxon 9.8 so most people using Saxon 9 for XSLT 2 should be able to use XSLT 3 as well by using the latest (9.9) or previous (9.8) version of Saxon.

Of course the map only serves as an elegant and light-weight container for the grouping results, the used for-each-group can be used with XSLT 2 as well, only you would need to store the grouping result in some intermediary XML (e.g. <group id="{current-grouping-key()}">...</group>) instead.

Body:
My XML files have TEI milestone elements like <handShift new="#DP1053/>; there's always one at the start of the <text> content, but after that there are sometimes a handful of tags of this kind with one of two or three distinct attribute values scattered through the <text> element to indicate where a particular scribe picks up after the last. The value of attribute @new points to an @xml:id definition in the TEI header, registered as an attribute to a <handNote/> element.

My aim in XSLT 2.0 is to concatenate the text written by each scribe so I can query each scribe's work independently. I wonder whether a recommended solution would entail group-starting-with, but I haven't yet wrapped my head around the preprocessing involved (I'd be grateful for pointers). Instead, my own instinct is to perform

a for-each loop iterating over the scribal hands, running

a string-join

on all text nodes

where a preceding <handShift/> with a value of attribute @new matching the hand processed in the current loop iteration is nearer than a preceding <handShift/> where the attribute value does not match.

My trial syntax in an XSLT 2.0 stylesheet transforming to HTML is as follows:

<xsl:for-each select="//tei:handNote[@xml:id != '']">
    <xsl:variable name="hand" select="./@xml:id"/>

<xsl:value-of select="$hand"/>: <xsl:value-of select="string-join(//tei:text//text()[preceding-sibling::tei:handShift[@new = concat('#',$hand)] >> preceding-sibling::tei:handShift[@new != concat('#',$hand)]])"/>

</xsl:for-each>

However, this only returns the text node(s) following the final milestone in the text, and only in the for-each iteration that selects for the attribute value matching that final milestone. I've surely got the >> statement wrong and would be grateful for any advice either with this approach or for a different, grouping-based approach.

I should probably mention that once I've mastered this concatenation, I'll have to add any <add hand="DP1054">addition</add>-type content (i.e. revisions by hands not matching that of the current stint) into the equation, by excluding nonmatching content of this nature and including matching content situated within nonmatching scribal stints, but I don't necessarily foresee this having to be added to the concatenation in the "correct" place. I thus should be able to account for these in two fairly straightforward additional steps, but the initial concatenation or grouping solution has to allow for the exclusion of nodes with nonmatching attribute values, and of any other elements I may wish to exclude (e.g. <expan> in the below example).

Here is a mock XML file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE TEI>
<TEI>
 <teiHeader>
  <fileDesc/>
   <sourceDesc>
    <msDesc>
     <physDesc>
      <handDesc>
       <handNote xml:id="DP1054"/>
       <handNote xml:id="DP1053"/>
      </handDesc>
     </physDesc>
    </msDesc>
   </sourceDesc>
 </teiHeader>
 <text>

<handShift new="#DP1054"/>I'LL REPRESENT THE WORK OF HAND 1054 IN ALLCAPS <handShift new="#DP1053"/>and I'll represent the work of hand 1053 in lowercase <handShift new="#DP1054"/>THE IDEA BEING THAT IN THE END ALL UPPERCASE TEXT SHOULD BE CONCATENATED <handShift new="#DP1053"/>separately from the sentence case content. Of course reality is a little more <add hand="#DP1054">COMPLEX</add>: we have <hi rend="color(green)">other nodes intervening</hi>, <handShift new="#DP1054"/>AND I WONDER WHETHER THESE WILL MESS WITH THE CONCEPT OF <choice>
     SBLS
     <expan>S<ex>I</ex>BL<ex>ING</ex>S</expan>
    </choice> <handShift new="#DP1053"/> (I will filter out nodes with `tei:expan` ancestors and nonmatching `add` elements; that's not the part I am having difficulty with).

 </text>
</TEI>

Body:
I think group-starting-with can help, here is an example that stores the result in an XPath 3.1 map (well, the grouping gives a sequence of maps and the map:merge functions merges them into a single map from id to nodes after a handShift of that id):

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:map="http://www.w3.org/2005/xpath-functions/map"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xpath-default-namespace="http://www.tei-c.org/ns/1.0"
    exclude-result-prefixes="#all"
    version="3.0">

  <xsl:output method="html" indent="yes" html-version="5"/>

  <xsl:variable name="note-map-sequence" as="map(xs:string, node()*)*">
      <xsl:for-each-group select="//body/p/node()" group-starting-with="handShift">
          <xsl:map-entry key="substring(@new, 2)" select="current-group()"/>
      </xsl:for-each-group>
  </xsl:variable>

  <xsl:variable name="note-map" as="map(xs:string, node()*)"
    select="map:merge($note-map-sequence, map { 'duplicates' : 'combine' })"/>

  <xsl:template match="/">
    <html>
      <head>
        <title>.NET XSLT Fiddle Example</title>
      </head>
      <body>
        <xsl:apply-templates select="//handNote"/>
      </body>
    </html>
  </xsl:template>

  <xsl:template match="handNote">
      <p>
        <xsl:value-of select="@xml:id"/>:
        <xsl:apply-templates select="$note-map(@xml:id)"/>
      </p>
  </xsl:template>

</xsl:stylesheet>

https://xsltfiddle.liberty-development.net/bFWRApk has an online sample outputting

<!DOCTYPE HTML>
<html>
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>.NET XSLT Fiddle Example</title></head>
   <body>
      <p>DP1054:
         I'LL REPRESENT THE WORK OF HAND 1054 IN ALLCAPS THE IDEA BEING THAT IN THE END ALL UPPERCASE TEXT SHOULD BE CONCATENATED AND I WONDER WHETHER THESE WILL MESS WITH THE CONCEPT OF
         SBLS
         SIBLINGS

      </p>
      <p>DP1053:
         and I'll represent the work of hand 1053 in lowercase separately from the sentence case content. Of course reality is a little more COMPLEX: we have other nodes intervening,  (I will filter out nodes with `tei:expan` ancestors and nonmatching `add` elements;
         that's not the part I am having difficulty with).
      </p>
   </body>
</html>

XSLT 3 with XPath 3.1 is available since Saxon 9.8 so most people using Saxon 9 for XSLT 2 should be able to use XSLT 3 as well by using the latest (9.9) or previous (9.8) version of Saxon.

Of course the map only serves as an elegant and light-weight container for the grouping results, the used for-each-group can be used with XSLT 2 as well, only you would need to store the grouping result in some intermediary XML (e.g. <group id="{current-grouping-key()}">...</group>) instead.


问:
TSLint and VSCode Issues: All destructured elements are unused
Error 1:

```<code>Type assertion using the '<>' syntax is forbidden. Use the 'as' syntax instead. (no-angle-bracket-type-assertion)tslint(1)
This assertion is unnecessary since it does not change the type of the expression. (no-unnecessary-type-assertion)tslint(1)
'SchemaForm' refers to a value, but is being used as a type here.ts(2749)
</code>```

Error 2:

```<code>All destructured elements are unused.
</code>```

Error 3

```<code>Cannot find name 'container'.
</code>```

What settings gone missing?

VSCode: Latest Version
OS: Mac Catalina 10.15.3

答: JSX syntax is only valid in a .tsx file. Since you are in a .ts file, typescript will try to interpret the <> as a type assertion not a JSX tag, and parsing goes bad from there. Change the extension and it should work

Body:
Error 1:

Type assertion using the '<>' syntax is forbidden. Use the 'as' syntax instead. (no-angle-bracket-type-assertion)tslint(1)
This assertion is unnecessary since it does not change the type of the expression. (no-unnecessary-type-assertion)tslint(1)
'SchemaForm' refers to a value, but is being used as a type here.ts(2749)

Error 2:

All destructured elements are unused.

Error 3

Cannot find name 'container'.

What settings gone missing?

VSCode: Latest Version
OS: Mac Catalina 10.15.3


问:
ESP8266: How to get MAC address of client in station mode (STA_MODE)?
I can get the client mac-address in Access Point mode (AP_MODE), see suGetClientMacAddress() function below.Found this code on the internet. I try to figure out the MAC-address of clients in WiFi.mode(STA_MODE);, however cannot find any useful info on this, impossible? And when it seems it is impossible, why is it impossible? Or is there still a 'trick' to get it working?

Below you can find the working function/version in AP_MODE

The library I am using the default ESP (v. 2.4.0) library and the Async web/sockets library:
https://github.com/me-no-dev/ESPAsyncWebServer

```<code>#define SU_WCFG_SERVER_ASYNC

 ........
 ........

 #ifdef SU_WCFG_SERVER_ASYNC
  #define SUWebSocketServer       AsyncWebSocket
  #define SUWebServerRequest      AsyncWebServerRequest
 #else
  ......
 #endif

 extern "C" {
    #include "user_interface.h"   // Required for some low level wifi functions
 }

............
............

String suIpAddressToString( IPAddress ipAddress )
{
  return String( ipAddress[0] )+"."+
         String( ipAddress[1] )+"."+
         String( ipAddress[2] )+"."+
         String( ipAddress[3] );
}

IPAddress suStringToIpAddress( String ipAddress )
{
  IPAddress ip = IPAddress( 0, 0, 0, 0 );
  char* pStr   = (char*)ipAddress.c_str();
  uint8_t i    = strlen( pStr );
  uint8_t iPos = 4;

   // Test before start
  if( i > 6 && pStr[i-1] != '.' )
  {
    while( i-- && iPos )
    {
      if( pStr[i] == '.' || i == 0 )
      {
        ip[--iPos] = String( (char*)&pStr[i+(i>0)] ).toInt();
        pStr[i] = 0; // set null termination to truncate
      }
    }
  }

  return ip;
}

String suGetClientIp( SUWebServerRequest* request )
{
  if( request )
   { return suIpAddressToString( IPAddress( request->client()->remoteIP() )); }

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

The function:

```<code>String suGetClientMacAddress( SUWebServerRequest* request )
{
  if( request )
   {
     struct ip_addr*       IPaddress;
     IPAddress             ip;
     struct station_info*  stat_info = wifi_softap_get_station_info();
     String                sClientIp = suGetClientIp( request );

     Serial.print( "Client ip: " );
     Serial.println( sClientIp );

     if( sClientIp.length() > 0 )
     {
      while( stat_info )
      {
        IPaddress = &stat_info->ip;
        ip = IPaddress->addr;

        if( suIpAddressToString( ip ) == sClientIp )
        {
           // Kind of rude and ugly to exit a loop and function this way
           // however it works with less 'check' overhead. OK to me.
          return String( stat_info->bssid[0], HEX )+":"+
                 String( stat_info->bssid[1], HEX )+":"+
                 String( stat_info->bssid[2], HEX )+":"+
                 String( stat_info->bssid[3], HEX )+":"+
                 String( stat_info->bssid[4], HEX )+":"+
                 String( stat_info->bssid[5], HEX );
        }

        stat_info = STAILQ_NEXT(stat_info, next);
      }
     }
   }

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

Any hints to get it working in STA_MODE?

答:
Hint:

```<code>- stations (clients) connect to an AP (Access Point - server)
- an AP generally hosts RF (radio) mechanisms for the connections of stations
</code>```

An ESP8266 can be either a station or AP, neither or both.

WiFi stations (as clients) do not usually communicate directly with each other unless special provisions are made to do so, such as in mesh / Ad Hoc networks or with a physical (cable ;) connection.

ContentLicense: CC BY-SA 3.0

Body:
I can get the client mac-address in Access Point mode (AP_MODE), see suGetClientMacAddress() function below.Found this code on the internet. I try to figure out the MAC-address of clients in WiFi.mode(STA_MODE);, however cannot find any useful info on this, impossible? And when it seems it is impossible, why is it impossible? Or is there still a 'trick' to get it working?

Below you can find the working function/version in AP_MODE

The library I am using the default ESP (v. 2.4.0) library and the Async web/sockets library:
https://github.com/me-no-dev/ESPAsyncWebServer

#define SU_WCFG_SERVER_ASYNC

 ........
 ........

 #ifdef SU_WCFG_SERVER_ASYNC
  #define SUWebSocketServer       AsyncWebSocket
  #define SUWebServerRequest      AsyncWebServerRequest
 #else
  ......
 #endif

 extern "C" {
    #include "user_interface.h"   // Required for some low level wifi functions
 }

............
............

String suIpAddressToString( IPAddress ipAddress )
{
  return String( ipAddress[0] )+"."+
         String( ipAddress[1] )+"."+
         String( ipAddress[2] )+"."+
         String( ipAddress[3] );
}

IPAddress suStringToIpAddress( String ipAddress )
{
  IPAddress ip = IPAddress( 0, 0, 0, 0 );
  char* pStr   = (char*)ipAddress.c_str();
  uint8_t i    = strlen( pStr );
  uint8_t iPos = 4;

   // Test before start
  if( i > 6 && pStr[i-1] != '.' )
  {
    while( i-- && iPos )
    {
      if( pStr[i] == '.' || i == 0 )
      {
        ip[--iPos] = String( (char*)&pStr[i+(i>0)] ).toInt();
        pStr[i] = 0; // set null termination to truncate
      }
    }
  }

  return ip;
}

String suGetClientIp( SUWebServerRequest* request )
{
  if( request )
   { return suIpAddressToString( IPAddress( request->client()->remoteIP() )); }

  return "";
}

The function:

String suGetClientMacAddress( SUWebServerRequest* request )
{
  if( request )
   {
     struct ip_addr*       IPaddress;
     IPAddress             ip;
     struct station_info*  stat_info = wifi_softap_get_station_info();
     String                sClientIp = suGetClientIp( request );

     Serial.print( "Client ip: " );
     Serial.println( sClientIp );

     if( sClientIp.length() > 0 )
     {
      while( stat_info )
      {
        IPaddress = &stat_info->ip;
        ip = IPaddress->addr;

        if( suIpAddressToString( ip ) == sClientIp )
        {
           // Kind of rude and ugly to exit a loop and function this way
           // however it works with less 'check' overhead. OK to me.
          return String( stat_info->bssid[0], HEX )+":"+
                 String( stat_info->bssid[1], HEX )+":"+
                 String( stat_info->bssid[2], HEX )+":"+
                 String( stat_info->bssid[3], HEX )+":"+
                 String( stat_info->bssid[4], HEX )+":"+
                 String( stat_info->bssid[5], HEX );
        }

        stat_info = STAILQ_NEXT(stat_info, next);
      }
     }
   }

  return "";
}

Any hints to get it working in STA_MODE?

Body:
Hint:

- stations (clients) connect to an AP (Access Point - server)
- an AP generally hosts RF (radio) mechanisms for the connections of stations

An ESP8266 can be either a station or AP, neither or both.

WiFi stations (as clients) do not usually communicate directly with each other unless special provisions are made to do so, such as in mesh / Ad Hoc networks or with a physical (cable ;) connection.


问:
Count occurrences of a char in a string using Bash
I need to count the number of occurrences of a char in a string using Bash.

In the following example, when the char is (for example) t, it echos the correct number of occurrences of t in var, but when the character is comma or semicolon, it prints out zero:

```<code>var = "text,text,text,text"
num = `expr match $var [,]`
echo "$num"
</code>```

答:
also check this out, for example we wanna count t

```<code>echo "test" | awk -v RS='t' 'END{print NR-1}'
</code>```

or in python

```<code>python -c 'print "this is for test".count("t")'
</code>```

or even better, we can make our script dynamic with awk

```<code>echo 'test' | awk '{for (i=1 ; i<=NF ; i++) array[$i]++ } END{ for (char in array) print char,array[char]}' FS=""
</code>```

in this case output is like this :

```<code>e 1
s 1
t 2
</code>```

Body:
I need to count the number of occurrences of a char in a string using Bash.

In the following example, when the char is (for example) t, it echos the correct number of occurrences of t in var, but when the character is comma or semicolon, it prints out zero:

var = "text,text,text,text"
num = `expr match $var [,]`
echo "$num"

Body:
also check this out, for example we wanna count t

echo "test" | awk -v RS='t' 'END{print NR-1}'

or in python

python -c 'print "this is for test".count("t")'

or even better, we can make our script dynamic with awk

echo 'test' | awk '{for (i=1 ; i<=NF ; i++) array[$i]++ } END{ for (char in array) print char,array[char]}' FS=""

in this case output is like this :

e 1
s 1
t 2


问:
What is the replacement for labelFunction in Spark DataGrid?
mx:DataGrid has a property called "labelFunction". I'm migrating my datagrid to Spark, but it doesn't have this property. How should I replace this functionality?</p>

答:
Use the labelFunction property on the GridColumn class.

I'll point out, you would have used the same approach w/ the MX DataGrid. The labelFunction was a property on the DataGridColumn class; not on the DataGrid.


问:
How to take screenshot in Flutter?
Is there a way or package that can help either taking fullscreen screenshot, or screenshot of widget that is wrapped or at least sharing the picture of screen via native share option?

There are some packages and I have tried, did not found any useful one.

答:
RepaintBoundary is the Widget you're looking for, this one can be converted into an image.

Example:

```<code>Future<CaptureResult> captureImage() async {
    final pixelRatio = MediaQuery.of(context).devicePixelRatio;
    final boundary = _boundaryKey.currentContext.findRenderObject() as RenderRepaintBoundary;
    final image = await boundary.toImage(pixelRatio: pixelRatio);
    final data = await image.toByteData(format: ui.ImageByteFormat.png);
    return CaptureResult(data.buffer.asUint8List(), image.width, image.height);
}

final _boundaryKey = GlobalKey();

RepaintBoundary(
   key: _boundaryKey,
   child: Container(),// Your Widgets to be captured.
)
</code>```

Link: capture_widget.dart

Title: How to take screenshot in Flutter?

Body:
RepaintBoundary is the Widget you're looking for, this one can be converted into an image.

Example:

Future<CaptureResult> captureImage() async {
    final pixelRatio = MediaQuery.of(context).devicePixelRatio;
    final boundary = _boundaryKey.currentContext.findRenderObject() as RenderRepaintBoundary;
    final image = await boundary.toImage(pixelRatio: pixelRatio);
    final data = await image.toByteData(format: ui.ImageByteFormat.png);
    return CaptureResult(data.buffer.asUint8List(), image.width, image.height);
}

final _boundaryKey = GlobalKey();

RepaintBoundary(
   key: _boundaryKey,
   child: Container(),// Your Widgets to be captured.
)

Link: capture_widget.dart


问:
Filter not returning results in Angular Material
I am trying  to filter results from a table using Material NG but am not getting any results and no errors either.

Here is my code

```<code>  displayedColumns: string[] = ['name', 'description', 'url'];
  dataSource = {};

  ngOnInit() {
    this.loading = true;
    this.apiService.getData().subscribe((res: ItemsInterface) => {
      this.dataSource = res;
      this.dataSource = new Array(res);
      console.log(this.dataSource[0]);
      this.loading = false;
    }, err => {
      this.loading = false;
    });
  }

  applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.dataSource[0].filter = filterValue.trim().toLowerCase();
  }

  <mat-form-field>
    <mat-label>Filter</mat-label>
    <input matInput (keyup)="applyFilter($event)" placeholder="Filter">
  </mat-form-field>
  <table mat-table [dataSource]="dataSource[0]" class="mat-elevation-z8">
    <ng-container matColumnDef="name">
      <th mat-header-cell *matHeaderCellDef> Name </th>
      <td mat-cell *matCellDef="let element"> {{element.name}} </td>
    </ng-container>

    <ng-container matColumnDef="description">
      <th mat-header-cell *matHeaderCellDef> Description </th>
      <td mat-cell *matCellDef="let element"> {{element.description}} </td>
    </ng-container>

    <ng-container matColumnDef="url">
      <th mat-header-cell *matHeaderCellDef> URL </th>
      <td mat-cell *matCellDef="let element"> <a mat-raised-button href="{{element.url}}" color="primary">Go to site</a></td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
  </table>
</code>```

I'm wondering if it's the format of the dataSource I have. It looks like this.

```<code>[
  {
    "name": "Ajax",
    "description": "a technology for asynchronous HTTP requests",
    "url": "https://github.com/HugoGiraudel/SJSJ/blob/master/_glossary/AJAX.md"
  },
  {
    "name": "AMD",
    "description": "a standard defining how to load JavaScript libraries or modules asynchronously",
    "url": "https://github.com/HugoGiraudel/SJSJ/blob/master/_glossary/AMD.md"
  },
  {
    "name": "AngularJS",
    "description": "a structural framework for dynamic web apps",
    "url": "https://github.com/HugoGiraudel/SJSJ/blob/master/_glossary/ANGULARJS.md"
  }
]
</code>```

I have made a repo here to reproduce issue.
https://github.com/dhameergovind/NG-Starter.git

答:
api.service.ts

```<code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Constants } from '../constants/constants';
import { ItemsInterface } from '../models/data';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ApiService {

 constructor(private httpClient: HttpClient) {
 }

  getData(): Observable<ItemsInterface[]> {
    return this.httpClient.get<ItemsInterface[]>(Constants.API_ENDPOINT + 'data.json');
  }

}
</code>```

app.component.ts

```<code>import { Component, OnInit, ViewChild , AfterViewInit} from '@angular/core';
import { ApiService } from './services/api.service';
import { ItemsInterface } from './models/data';
import { MatPaginator, MatTableDataSource } from '@angular/material';
export interface SourceDataType {
  name: string;
  description: string;
  markdown: string;
  html: string;
  url: string;
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.sass']
})
export class AppComponent implements OnInit , AfterViewInit{
  @ViewChild(MatPaginator, { static: false }) paginator: MatPaginator;
  ELEMENT_DATA: SourceDataType[];
  title = 'NG PWA';
  displayedColumns: string[] = ['name', 'description', 'url'];
  dataSource = new MatTableDataSource<SourceDataType>(this.ELEMENT_DATA);
  public loading = false;
  constructor(private apiService: ApiService) { }

  ngOnInit() {
    this.loading = true;
    this.apiService.getData().subscribe((res: SourceDataType[]) => {
      this.dataSource = new MatTableDataSource<SourceDataType>(res);
      this.dataSource.paginator = this.paginator;
      console.log(this.dataSource);
      this.loading = false;
    }, err => {
      this.loading = false;
    });
  }
  ngAfterViewInit() {
    setTimeout(() => this.dataSource.paginator = this.paginator);
  }
  applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.dataSource.filter = filterValue.trim().toLowerCase();
  }
}
</code>```

app.component.html

```<code><mat-toolbar color="primary">
  <mat-toolbar-row>
    <span>Data</span>
  </mat-toolbar-row>
</mat-toolbar>
<main>

  <mat-form-field>
    <mat-label>Filter</mat-label>
    <input matInput (input)="applyFilter($event)" placeholder="Filter">
  </mat-form-field>
  <table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
    <ng-container matColumnDef="name">
      <th mat-header-cell *matHeaderCellDef> Name </th>
      <td mat-cell *matCellDef="let element"> {{element.name}} </td>
    </ng-container>

    <ng-container matColumnDef="description">
      <th mat-header-cell *matHeaderCellDef> Description </th>
      <td mat-cell *matCellDef="let element"> {{element.description}} </td>
    </ng-container>

    <ng-container matColumnDef="url">
      <th mat-header-cell *matHeaderCellDef> URL </th>
      <td mat-cell *matCellDef="let element"> <a mat-raised-button href="{{element.url}}" color="primary">Go to site</a></td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
  </table>

</main>

<router-outlet></router-outlet>
<ngx-loading [show]="loading" [config]="{ backdropBorderRadius: '3px' }"></ngx-loading>
</code>```

Body:
I am trying  to filter results from a table using Material NG but am not getting any results and no errors either.

Here is my code

  displayedColumns: string[] = ['name', 'description', 'url'];
  dataSource = {};

  ngOnInit() {
    this.loading = true;
    this.apiService.getData().subscribe((res: ItemsInterface) => {
      this.dataSource = res;
      this.dataSource = new Array(res);
      console.log(this.dataSource[0]);
      this.loading = false;
    }, err => {
      this.loading = false;
    });
  }

  applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.dataSource[0].filter = filterValue.trim().toLowerCase();
  }

  <mat-form-field>
    <mat-label>Filter</mat-label>
    <input matInput (keyup)="applyFilter($event)" placeholder="Filter">
  </mat-form-field>

    <ng-container matColumnDef="name">
       Name
       {{element.name}}
    </ng-container>

    <ng-container matColumnDef="description">
       Description
       {{element.description}}
    </ng-container>

    <ng-container matColumnDef="url">
       URL
       Go to site
    </ng-container>

I'm wondering if it's the format of the dataSource I have. It looks like this.

[
  {
    "name": "Ajax",
    "description": "a technology for asynchronous HTTP requests",
    "url": "https://github.com/HugoGiraudel/SJSJ/blob/master/_glossary/AJAX.md"
  },
  {
    "name": "AMD",
    "description": "a standard defining how to load JavaScript libraries or modules asynchronously",
    "url": "https://github.com/HugoGiraudel/SJSJ/blob/master/_glossary/AMD.md"
  },
  {
    "name": "AngularJS",
    "description": "a structural framework for dynamic web apps",
    "url": "https://github.com/HugoGiraudel/SJSJ/blob/master/_glossary/ANGULARJS.md"
  }
]

I have made a repo here to reproduce issue.
https://github.com/dhameergovind/NG-Starter.git

Body:
api.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Constants } from '../constants/constants';
import { ItemsInterface } from '../models/data';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ApiService {

 constructor(private httpClient: HttpClient) {
 }

  getData(): Observable<ItemsInterface[]> {
    return this.httpClient.get<ItemsInterface[]>(Constants.API_ENDPOINT + 'data.json');
  }

}

app.component.ts

import { Component, OnInit, ViewChild , AfterViewInit} from '@angular/core';
import { ApiService } from './services/api.service';
import { ItemsInterface } from './models/data';
import { MatPaginator, MatTableDataSource } from '@angular/material';
export interface SourceDataType {
  name: string;
  description: string;
  markdown: string;
  html: string;
  url: string;
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.sass']
})
export class AppComponent implements OnInit , AfterViewInit{
  @ViewChild(MatPaginator, { static: false }) paginator: MatPaginator;
  ELEMENT_DATA: SourceDataType[];
  title = 'NG PWA';
  displayedColumns: string[] = ['name', 'description', 'url'];
  dataSource = new MatTableDataSource<SourceDataType>(this.ELEMENT_DATA);
  public loading = false;
  constructor(private apiService: ApiService) { }

  ngOnInit() {
    this.loading = true;
    this.apiService.getData().subscribe((res: SourceDataType[]) => {
      this.dataSource = new MatTableDataSource<SourceDataType>(res);
      this.dataSource.paginator = this.paginator;
      console.log(this.dataSource);
      this.loading = false;
    }, err => {
      this.loading = false;
    });
  }
  ngAfterViewInit() {
    setTimeout(() => this.dataSource.paginator = this.paginator);
  }
  applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.dataSource.filter = filterValue.trim().toLowerCase();
  }
}

app.component.html

<mat-toolbar color="primary">
  <mat-toolbar-row>
    <span>Data</span>
  </mat-toolbar-row>
</mat-toolbar>
<main>

  <mat-form-field>
    <mat-label>Filter</mat-label>
    <input matInput (input)="applyFilter($event)" placeholder="Filter">
  </mat-form-field>
  <table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
    <ng-container matColumnDef="name">
      <th mat-header-cell *matHeaderCellDef> Name </th>
      <td mat-cell *matCellDef="let element"> {{element.name}} </td>
    </ng-container>

    <ng-container matColumnDef="description">
      <th mat-header-cell *matHeaderCellDef> Description </th>
      <td mat-cell *matCellDef="let element"> {{element.description}} </td>
    </ng-container>

    <ng-container matColumnDef="url">
      <th mat-header-cell *matHeaderCellDef> URL </th>
      <td mat-cell *matCellDef="let element"> <a mat-raised-button href="{{element.url}}" color="primary">Go to site</a></td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
  </table>

</main>

<router-outlet></router-outlet>
<ngx-loading [show]="loading" [config]="{ backdropBorderRadius: '3px' }"></ngx-loading>


问:
What will be the logic to show top rated item?
I want to show items in my website sorted by its rating.
I don't want to show highest rated items by the average of rating. Could anyone suggest some formula to define highest rated item.</p>

答:
You could weight each item's average rating by the number of people who have entered in a rating. This would ensure items with both high number of rating and high average rating would float to the top instead of just items with a singular rating.

```<code>projectedRating = item.AverageRating * item.Ratings.Count
</code>```

Additionally, you could consider normalizing this so it only makes a difference between say 1 and 100 rating applied.

```<code>projectedRating = item.AverageRating * Max(item.Ratings.Count, 100)
</code>```

This way run away votes on an item, even with a low average rating, wouldn't end up on the top all the time.

Outside of that, I think you'll need to provide more information on what basis you'd like to indicate an item is a top item. Total views on it, marking it as most popular, could be an option as well.

Body:
You could weight each item's average rating by the number of people who have entered in a rating. This would ensure items with both high number of rating and high average rating would float to the top instead of just items with a singular rating.

projectedRating = item.AverageRating * item.Ratings.Count

Additionally, you could consider normalizing this so it only makes a difference between say 1 and 100 rating applied.

projectedRating = item.AverageRating * Max(item.Ratings.Count, 100)

This way run away votes on an item, even with a low average rating, wouldn't end up on the top all the time.

Outside of that, I think you'll need to provide more information on what basis you'd like to indicate an item is a top item. Total views on it, marking it as most popular, could be an option as well.


问:
Using IN in where clause
*Assuming this mySql table :

```<code> id   | group |  members
 1    | blue  |     Bob
 2    | red   |     Tom
 3    |green  |     Maria
 4    |blue   |     Maria
 5    |red    |     Bob
 6    |red    |     Maria
 7    |yellow |     Bob
</code>```

How can I query this table in order to get the rows where members are both in group "blue" and "green

Using the "IN" in where clause does not work for me.

Expected result : "Maria"

Edit :

Maybe I found something... If I use n variable in my "IN" array, so I should use the same n value in the "HAVING" part.
Tried with this statement and it seems to work. (comments appreciated)

```    SELECT id,members
    FROM my_table
    WHERE `team` IN('blue', 'red', 'green')
    GROUP BY members
    HAVING COUNT( DISTINCT team) >= 3
```

What is your opinion ?

答:
select id from my_table A inner join my_table B
ON A.members = B.members
where A.group ='blue' AND B.group ='green'</p>

Title: Using IN in where clause

Body:
*Assuming this mySql table :

 id   | group |  members
 1    | blue  |     Bob
 2    | red   |     Tom
 3    |green  |     Maria
 4    |blue   |     Maria
 5    |red    |     Bob
 6    |red    |     Maria
 7    |yellow |     Bob

How can I query this table in order to get the rows where members are both in group "blue" and "green

Using the "IN" in where clause does not work for me.

Expected result : "Maria"

Edit :

Maybe I found something... If I use n variable in my "IN" array, so I should use the same n value in the "HAVING" part.
Tried with this statement and it seems to work. (comments appreciated)

    SELECT id,members
    FROM my_table
    WHERE `team` IN('blue', 'red', 'green')
    GROUP BY members
    HAVING COUNT( DISTINCT team) >= 3

What is your opinion ?


问:
Put on action html Route to my controller
Good afternoon,

I want to create a route to my Create Controller. How do I do it? I' ve seen code like this

```<code>@Url.RouteUrl( "Create", new { action = "Create"} )
routes.MapRoute(
    name: "Root",
    url: "index.html",
    defaults: new { controller = "Home", action = "Index" }
);
</code>```

But I'm not able to use it

```<code><form method="POST" action='@Url.RouteUrl( "Create", new { action = "Create"} )' enctype="multipart/form-data">
    <input placeholder="Nome" name="nome" type="text">
    <input placeholder="Password" name="senha" type="password">
    <input placeholder="Email" name="email" type="email">
    <button type="submit">Submeter</button>
</form>
</code>```

and this is my Controller

```<code>[HttpPost]
public IActionResult Create(Usuario usuario)
{
    if (usuario == null)
        return BadRequest();

    usuarioRepositorio.Add(usuario);

    return CreatedAtRoute(new {id=usuario.UsuarioId}, usuario);
}
</code>```

答: I find this action='@Url.Action("Create", "Usuarios")' where first need action and after the name of controller

Body:
Good afternoon,

I want to create a route to my Create Controller. How do I do it? I' ve seen code like this

@Url.RouteUrl( "Create", new { action = "Create"} )
routes.MapRoute(
    name: "Root",
    url: "index.html",
    defaults: new { controller = "Home", action = "Index" }
);

But I'm not able to use it

<form method="POST" action='@Url.RouteUrl( "Create", new { action = "Create"} )' enctype="multipart/form-data">
    <input placeholder="Nome" name="nome" type="text">
    <input placeholder="Password" name="senha" type="password">
    <input placeholder="Email" name="email" type="email">
    <button type="submit">Submeter</button>
</form>

and this is my Controller

[HttpPost]
public IActionResult Create(Usuario usuario)
{
    if (usuario == null)
        return BadRequest();

    usuarioRepositorio.Add(usuario);

    return CreatedAtRoute(new {id=usuario.UsuarioId}, usuario);
}


问:
How to perform >= or <= conditions with date in python pandas dataframe
I have a dataframe named df1 and one variable named start date and I have given the dt for both the dataframe and Date variable. the important thing to check out here is both the length of dataframe and date variable are different

```<code>df1
</code>```

Date Variable

we need to filter the data in dataframe df1 based dates for df1 greater than or equal to dates in Date variable.

simply df['Date'] >= Date variable

答:
Have you tried the approach below ?

```<code>df.loc[df['Date'] >= Date variable]
</code>```

You need to ensure that that the values in the Series Date and the 'Date variable' are of the same datatype, either Datetime or Date in this case.

Body:
I have a dataframe named df1 and one variable named start date and I have given the dt for both the dataframe and Date variable. the important thing to check out here is both the length of dataframe and date variable are different

df1

Date Variable

we need to filter the data in dataframe df1 based dates for df1 greater than or equal to dates in Date variable.

simply df['Date'] >= Date variable

Body:
Have you tried the approach below ?

df.loc[df['Date'] >= Date variable]

You need to ensure that that the values in the Series Date and the 'Date variable' are of the same datatype, either Datetime or Date in this case.


问:
How to detect platform using Ionic 4
How to detect browser and mobileweb platform using Ionic 4 because when I tried with below code in desktop browser it is not falling in ‘core’ condition.

```<code>if (this.platform.is('core')) {
    alert('core platform');
  } else {
    alert('something else');
  }
</code>```

When I have debug in chrome developer tool it showing 'android' platform as per below snapshot.

Can anyone please help me how to detect platform in Ionic 4 or what can be the alternative for this?

答:
Ionic 4 / Capacitor

I have written a service like so:

detect-platform.service.ts

```<code>import { Injectable } from '@angular/core';
import { Platform } from '@ionic/angular';
import { find } from 'lodash';

@Injectable({
    providedIn: 'root'
})
export class DetectPlatformService {

    isDevice: boolean = false;

    constructor(
        private platform: Platform, ) { }

    setPlatform(): void {

        const platforms: string[] = this.platform.platforms();
        const platform: string = find(platforms, (p: string) => {
            return p === 'capacitor';
        });

        this.isDevice = platform ? true : false;
    }

}
</code>```

Note: Since I use Ionic 4/Capacitor it gives true if it is on device else false.

Title: How to detect platform using Ionic 4

Body:
How to detect browser and mobileweb platform using Ionic 4 because when I tried with below code in desktop browser it is not falling in ‘core’ condition.

if (this.platform.is('core')) {
    alert('core platform');
  } else {
    alert('something else');
  }

When I have debug in chrome developer tool it showing 'android' platform as per below snapshot.

Can anyone please help me how to detect platform in Ionic 4 or what can be the alternative for this?

Body:
Ionic 4 / Capacitor

I have written a service like so:

detect-platform.service.ts

import { Injectable } from '@angular/core';
import { Platform } from '@ionic/angular';
import { find } from 'lodash';

@Injectable({
    providedIn: 'root'
})
export class DetectPlatformService {

    isDevice: boolean = false;

    constructor(
        private platform: Platform, ) { }

    setPlatform(): void {

        const platforms: string[] = this.platform.platforms();
        const platform: string = find(platforms, (p: string) => {
            return p === 'capacitor';
        });

        this.isDevice = platform ? true : false;
    }

}

Note: Since I use Ionic 4/Capacitor it gives true if it is on device else false.


问:
PHP form not writing to mySQL database
I'm just learning PHP and am trying the most basic thing: capturing info from a form and sticking it into a table in a mySQL database.  I'm embarrassed to ask such a stupid newbie question, but after reviewing two books, several Stack Overflow posts, and 7 different tutorials, I still can't get my pathetic code to write a few lousy metrics to my database.

Here's the latest version of the code.  Could someone please tell me what I am doing wrong?

* Basic HTML Form *

```<code><form method="post" action="post_metrics_stack.php" >
<p>Date<br />
<input name="date" type="text" /></p>

<p>Metric1<br />
<input name="metric1" type="text" /></p>

<p>Metric2<br />
<input name="metric2" type="text" /></p>

<input type="submit" name="submit" value="Submit" />
</form>
</code>```

* Processor File *

```<code><?php

$date=$_POST['date'];
$metric1=$_POST['metric1'];
$metric2=$_POST['metric2'];

$con = mysql_connect("localhost", "root", "mypassword");
if (!$con)
  {die('Could not connect to mysql: ' . mysql_error());}

$mydb = mysql_select_db("mydatabasename");
if (!$mydb)
  {die('Could not connect to database: ' . mysql_error());}

mysql_query("INSERT INTO my_metrics VALUES ('$date', '$metric1', '$metric2')");
 Print "Your metrics have been successfully added to the database.";

mysql_close($con);
?>
</code>```

答:
Hooray!  Hooray!  Hooray!

Thank you all for such helpful advice!  It finally works!  Here's the updated code in case any other newbies have the same issue.  (Hope I didn't screw anything else up.)

Form

```<code><form method="post" action="post_metrics_stack.php" >
  <p>Date<br />
  <input name="date" type="text" /></p>

  <p>Metric1<br />
  <input name="metric1" type="text" /></p>

  <p>Metric2<br />
  <input name="metric2" type="text" /></p>

<input type="submit" name="submit" value="Submit" />
</form>
</code>```

Processor

```<code><?php

  ini_set('display_errors', 1); error_reporting(E_ALL);

  // 1. Create connection to database

  mysql_connect('localhost','root','mypassword') or die('Could not connect to mysql: <hr>'.mysql_error());

  // 2. Select database

  mysql_select_db("my_metrics") or die('Could not connect to database:<hr>'.mysql_error());

  // 3. Assign variables (after connection as required by escape string)

    $date=mysql_real_escape_string($_POST['date']);
    $metric1=mysql_real_escape_string($_POST['metric1']);
    $metric2=mysql_real_escape_string($_POST['metric2']);

  // 4. Insert data into table

  mysql_query("INSERT INTO my_metrics (date, metric1, metric2) VALUES ('$date', '$metric1', '$metric2')");

  Echo 'Your information has been successfully added to the database.';

  print_r($_POST);

  mysql_close()

?>
</code>```

Title: PHP form not writing to mySQL database

Body:
I'm just learning PHP and am trying the most basic thing: capturing info from a form and sticking it into a table in a mySQL database.  I'm embarrassed to ask such a stupid newbie question, but after reviewing two books, several Stack Overflow posts, and 7 different tutorials, I still can't get my pathetic code to write a few lousy metrics to my database.

Here's the latest version of the code.  Could someone please tell me what I am doing wrong?

* Basic HTML Form *

<form method="post" action="post_metrics_stack.php" >

Date

<input name="date" type="text" />

Metric1

<input name="metric1" type="text" />

Metric2

<input name="metric2" type="text" />

<input type="submit" name="submit" value="Submit" />
</form>

* Processor File *

<?php

$date=$_POST['date'];
$metric1=$_POST['metric1'];
$metric2=$_POST['metric2'];

$con = mysql_connect("localhost", "root", "mypassword");
if (!$con)
  {die('Could not connect to mysql: ' . mysql_error());}

$mydb = mysql_select_db("mydatabasename");
if (!$mydb)
  {die('Could not connect to database: ' . mysql_error());}

mysql_query("INSERT INTO my_metrics VALUES ('$date', '$metric1', '$metric2')");
 Print "Your metrics have been successfully added to the database.";

mysql_close($con);
?>

Body:
Hooray!  Hooray!  Hooray!

Thank you all for such helpful advice!  It finally works!  Here's the updated code in case any other newbies have the same issue.  (Hope I didn't screw anything else up.)

Form

<form method="post" action="post_metrics_stack.php" >
  <p>Date<br />
  <input name="date" type="text" /></p>

  <p>Metric1<br />
  <input name="metric1" type="text" /></p>

  <p>Metric2<br />
  <input name="metric2" type="text" /></p>

<input type="submit" name="submit" value="Submit" />
</form>

Processor

<?php

  ini_set('display_errors', 1); error_reporting(E_ALL);

  // 1. Create connection to database

  mysql_connect('localhost','root','mypassword') or die('Could not connect to mysql: <hr>'.mysql_error());

  // 2. Select database

  mysql_select_db("my_metrics") or die('Could not connect to database:<hr>'.mysql_error());

  // 3. Assign variables (after connection as required by escape string)

    $date=mysql_real_escape_string($_POST['date']);
    $metric1=mysql_real_escape_string($_POST['metric1']);
    $metric2=mysql_real_escape_string($_POST['metric2']);

  // 4. Insert data into table

  mysql_query("INSERT INTO my_metrics (date, metric1, metric2) VALUES ('$date', '$metric1', '$metric2')");

  Echo 'Your information has been successfully added to the database.';

  print_r($_POST);

  mysql_close()

?>


问:
How do I update an object state in react via hooks
This is a simple question. How do I successfully update state object via react hooks?

I just started using hooks, and I like how it allows to use the simple and pure JavaScript function to create and manage state with the useState() function, and also, make changes that affect components using the useEffect() function, but I can't seem to make update to the state work!

After making a request to an API, it return the data needed, but when I try to update the state for an error in request and for a successful request, it does not update the state. I logged it to the browser console, but no change was made to the state, it returns undefined.

I know that I'm not doing something right in the code.
Here is my App component, Its a single component for fetching and updating:

```<code>import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';

export default function App() {

    // Set date state
    const [data,setData]  = useState({
       data: [],
       loaded: false,
       placeholder: 'Loading'
    });

    // Fetch and update date
    useEffect(() => {

        fetch('http://localhost:8000/api/lead/')
        .then(response => {
            if (response.status !== 200) {
                SetData({placeholder: 'Something went wrong'});
            }
            response.json()
        })
        .then(result => {
           console.log(data);
           setData({data: result});
        });

    },[]);

    return (
      <h1>{console.log(data)}</h1>
    );
}

ReactDOM.render(<App />, document.getElementById('app'));
</code>```

答:
The correct way to update an Object with hooks it to use function syntax for setState callback:

```<code>setData(prevState => {...prevState, placeholder: 'Something went wrong'})
</code>```

Following method will override your previous object state:

```<code>setData({placeholder: 'Something went wrong'}); // <== incorrect
</code>```

Your final code should look like this:

```<code>.then(response => {
    if (response.status !== 200) {
        setData(prevObj => {...prevObj, placeholder: 'Something went wrong'});
    }
    return response.json()
 })
.then(result => {
    setData(prevObj => {...prevObj, data: result});
 });
</code>```

Body:
This is a simple question. How do I successfully update state object via react hooks?

I just started using hooks, and I like how it allows to use the simple and pure JavaScript function to create and manage state with the useState() function, and also, make changes that affect components using the useEffect() function, but I can't seem to make update to the state work!

After making a request to an API, it return the data needed, but when I try to update the state for an error in request and for a successful request, it does not update the state. I logged it to the browser console, but no change was made to the state, it returns undefined.

I know that I'm not doing something right in the code.
Here is my App component, Its a single component for fetching and updating:

import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';

export default function App() {

    // Set date state
    const [data,setData]  = useState({
       data: [],
       loaded: false,
       placeholder: 'Loading'
    });

    // Fetch and update date
    useEffect(() => {

        fetch('http://localhost:8000/api/lead/')
        .then(response => {
            if (response.status !== 200) {
                SetData({placeholder: 'Something went wrong'});
            }
            response.json()
        })
        .then(result => {
           console.log(data);
           setData({data: result});
        });

    },[]);

    return (

{console.log(data)}

    );
}

ReactDOM.render(<App />, document.getElementById('app'));

Body:
The correct way to update an Object with hooks it to use function syntax for setState callback:

setData(prevState => {...prevState, placeholder: 'Something went wrong'})

Following method will override your previous object state:

setData({placeholder: 'Something went wrong'}); // <== incorrect

Your final code should look like this:

.then(response => {
    if (response.status !== 200) {
        setData(prevObj => {...prevObj, placeholder: 'Something went wrong'});
    }
    return response.json()
 })
.then(result => {
    setData(prevObj => {...prevObj, data: result});
 });


问:
python spider return empty json file
I created Json file in python to store scraped data using scrapy , but json file is empty although python scrapy spider scraped all data.i'm trying to store all scraped data into json file.in terminal on crawl command spider display all data but it did not import into json file. i can't find any solution
i'm sharing both files spider and also items.py

i use this command scrapy crawl scraper -o products.json

Spider.py

```<code>import scrapy
from bs4 import BeautifulSoup as Soup
from ..items import ScrapyArbiItem
import requests
from idna import unicode

class Scraper(scrapy.Spider):
    name = "scraper"

    start_urls = [
          'https://www.fenom.com/en/263-men',
        # 'https://www.fenom.com/en/263-men#/page-2',
        # 'https://www.fenom.com/en/263-men#/page-3',
        # 'https://www.fenom.com/en/263-men#/page-4',
        # 'https://www.fenom.com/en/263-men#/page-5',
        # 'https://www.fenom.com/en/263-men#/page-6',
        # 'https://www.fenom.com/en/263-men#/page-7',
    ]

    def parse(self, response):

        items = ScrapyArbiItem()

        page_soup = Soup(response.text, 'html.parser')
        uls = page_soup.find_all("ul", class_="product_list grid row")[0]
        # import pdb;
        # pdb.set_trace()
        for li in uls.find_all("li", class_="ajax_block_product block_home col-xs-6 col-sm-4
        col-md-3"):
            data_to_write = []
            try:
                # print("gnbfrgjrnbgfjnbruigbnruig")
                div = li.find('div', class_='product-container')
                left_block = div.find('div', class_="left-block")
                image_container = left_block.find('div', class_="product-image-container")
                image = image_container.find('a')
                image_url_a = image_container.find('a', class_="product_img_link")
                image_url = image_url_a.find('img', class_='replace-2x img-responsive')
                image_url = image_url.get('src')  # image_url
                url = image.get('href')  # url of product
                right_block = div.find('div', class_="right-block")
                right_a = right_block.find('a')
                product = right_a.find('span', class_="product-name")
                product_name = product.text  # product_name
                pp = right_a.find('span', class_="content_price")
                product_p = pp.find('span', class_="product-price")
                product_price = product_p.text  # product_price

                items ['product_name'] = product_name
                items['product_price'] = product_price
                items['url'] = url

                print(items)
                #print(product_name)
                #print(product_price)
                #print(url)
                #print(image_url)
                next_page = url
                # import pdb;pdb.set_trace()
                # print(url)
                # if url:
                #     yield scrapy.Request(url, callback=self.parsetwo, dont_filter=True)
            except:
                pass
</code>```

items.py

in this file is to arrange all extracted data into temporary containers

```<code>import scrapy

class ScrapyArbiItem(scrapy.Item):
    # define the fields for your item here like:
    product_name = scrapy.Field()
    product_price = scrapy.Field()
    url = scrapy.Field()
</code>```

答: Looks like all you need to do now is return the items object and you're good to go.

Title: python spider return empty json file

Body:
I created Json file in python to store scraped data using scrapy , but json file is empty although python scrapy spider scraped all data.i'm trying to store all scraped data into json file.in terminal on crawl command spider display all data but it did not import into json file. i can't find any solution
i'm sharing both files spider and also items.py

i use this command scrapy crawl scraper -o products.json

Spider.py

import scrapy
from bs4 import BeautifulSoup as Soup
from ..items import ScrapyArbiItem
import requests
from idna import unicode

class Scraper(scrapy.Spider):
    name = "scraper"

    start_urls = [
          'https://www.fenom.com/en/263-men',
        # 'https://www.fenom.com/en/263-men#/page-2',
        # 'https://www.fenom.com/en/263-men#/page-3',
        # 'https://www.fenom.com/en/263-men#/page-4',
        # 'https://www.fenom.com/en/263-men#/page-5',
        # 'https://www.fenom.com/en/263-men#/page-6',
        # 'https://www.fenom.com/en/263-men#/page-7',
    ]

    def parse(self, response):

        items = ScrapyArbiItem()

        page_soup = Soup(response.text, 'html.parser')
        uls = page_soup.find_all("ul", class_="product_list grid row")[0]
        # import pdb;
        # pdb.set_trace()
        for li in uls.find_all("li", class_="ajax_block_product block_home col-xs-6 col-sm-4
        col-md-3"):
            data_to_write = []
            try:
                # print("gnbfrgjrnbgfjnbruigbnruig")
                div = li.find('div', class_='product-container')
                left_block = div.find('div', class_="left-block")
                image_container = left_block.find('div', class_="product-image-container")
                image = image_container.find('a')
                image_url_a = image_container.find('a', class_="product_img_link")
                image_url = image_url_a.find('img', class_='replace-2x img-responsive')
                image_url = image_url.get('src')  # image_url
                url = image.get('href')  # url of product
                right_block = div.find('div', class_="right-block")
                right_a = right_block.find('a')
                product = right_a.find('span', class_="product-name")
                product_name = product.text  # product_name
                pp = right_a.find('span', class_="content_price")
                product_p = pp.find('span', class_="product-price")
                product_price = product_p.text  # product_price

                items ['product_name'] = product_name
                items['product_price'] = product_price
                items['url'] = url

                print(items)
                #print(product_name)
                #print(product_price)
                #print(url)
                #print(image_url)
                next_page = url
                # import pdb;pdb.set_trace()
                # print(url)
                # if url:
                #     yield scrapy.Request(url, callback=self.parsetwo, dont_filter=True)
            except:
                pass

items.py

in this file is to arrange all extracted data into temporary containers

import scrapy

class ScrapyArbiItem(scrapy.Item):
    # define the fields for your item here like:
    product_name = scrapy.Field()
    product_price = scrapy.Field()
    url = scrapy.Field()


问:
Java code to generate comma separated values and sum
While running this code I am getting ArrayIndexOutOfBoundsException.

```<code>public class Evensum {

    public static void main(String[] args) {
        int num = Integer.parseInt(args[0]);
        int even[] = new int[num];
        int sum = 0,j = 0;
        String evennums = "";
        //Insert your code here
         for(j=0; j<=num; j++) {
            if(num%2==0) {
                even[j]=num;
                sum=sum+num;
                args[j]= Integer.toString(num);
            }
            evennums=String.join(",", args);
        }
        System.out.println(evennums);
        System.out.println(sum);
    }
}
</code>```

答:
```<code>for (j=0; j<=num; j++)
</code>```

This is wrong. It should be:

```<code>for (j = 0; j < num; j++)
</code>```

Why? Assume num is 5. Before this line you initialized even to 5. The indices of even would be 0, 1, 2, 3, 4.

Now, with j<=num, you are trying to access the index 5, which does not exist and hence the exception.

```<code>args[j]= Integer.toString(num);
</code>```

This line will raise another exception. I am assuming you're only passing one parameter from the command line which is args[0]. This means the args array is of size 1 and you cannot add more elements to it.

Also, it is not a good practice to add/modify elements to the args array. You should create a new array for this.

Body:
While running this code I am getting ArrayIndexOutOfBoundsException.

public class Evensum {

    public static void main(String[] args) {
        int num = Integer.parseInt(args[0]);
        int even[] = new int[num];
        int sum = 0,j = 0;
        String evennums = "";
        //Insert your code here
         for(j=0; j<=num; j++) {
            if(num%2==0) {
                even[j]=num;
                sum=sum+num;
                args[j]= Integer.toString(num);
            }
            evennums=String.join(",", args);
        }
        System.out.println(evennums);
        System.out.println(sum);
    }
}

Body:
for (j=0; j<=num; j++)

This is wrong. It should be:

for (j = 0; j < num; j++)

Why? Assume num is 5. Before this line you initialized even to 5. The indices of even would be 0, 1, 2, 3, 4.

Now, with j<=num, you are trying to access the index 5, which does not exist and hence the exception.

args[j]= Integer.toString(num);

This line will raise another exception. I am assuming you're only passing one parameter from the command line which is args[0]. This means the args array is of size 1 and you cannot add more elements to it.

Also, it is not a good practice to add/modify elements to the args array. You should create a new array for this.


问:
Biopython gives ValueError: Sequences must all be the same length even though sequences are of the same length
I'm trying to create a phylogenetic tree by making a .phy file from my data.

I have a dataframe

ndf=

ESV      trunc

1  esv1    TACGTAGGTG...

2  esv2    TACGGAGGGT...

3  esv3    TACGGGGGG...

7  esv7    TACGTAGGGT...

I checked the length of the elements of the column "trunc":

length_checker = np.vectorize(len)

arr_len = length_checker(ndf['trunc'])

The resulting arr_len gives the same length (=253) for all the elements.

I saved this dataframe as .phy file, which looks like this:

23  253

esv1    TACGTAGGTGGCGAGCGTTATCCGGAATTATTGGGCGTAAAGCGCGCGCAGGCGGTTTCTTAAGTCTGATGTGAAAGCCCACGGCTCAACCGTGGAGGGTCATTGGAAACTGGGAAACTTGAGTGCAGAAGAGGAAAGCGGAATTCCACGTGTAGCGGTGAAATGCGTAGAGATGTGGAGGAACACCAGTGGCGAAGGCGGCTTTCTGGTCTGTAACTGACGCTGAGGCGCGAAAGCGTGGGGAGCAAACAGG

esv2    TACGGAGGGTGCAAGCGTTATCCGGATTCACTGGGTTTAAAGGGTGCGTAGGTGGGTTGGTAAGTCAGTGGTGAAATCTCCGAGCTTAACTTGGAAACTGCCATTGATACTATTAATCTTGAATATTGTGGAGGTTAGCGGAATATGTCATGTAGCGGTGAAATGCTTAGAGATGACATAGAACACCAATTGCGAAGGCAGCTGGCTACACATATATTGACACTGAGGCACGAAAGCGTGGGGATCAAACAGG

esv3    TACGGGGGGGGCAAGCGTTGTTCGGAATTACTGGGCGTAAAGGGCGCGTAGGCGGCCAGACCAAGTCGAGTGTGAAATTGCAGGGCTTAACTTTGCAGGGTCGCTCGATACTGGTCGGCTAGAGTGTGGAAGAGGGTACTGGAATTCCCGGTGTAGCGGTGAAATGCGTAGATATCGGGAGGAACACCAGCGGCGAAGGCGGGTACCTGGGCCAACACTGACGCTGAGGCGCGAAAGCTAGGGGAGCAAACAG

This is similar to the file used in this tutorial.

However, when I run the command
aln = AlignIO.read('msa.phy', 'phylip')

I get "ValueError: Sequences must all be the same length"

I don't know why I'm getting this or how to fix it. Any help is greatly appreciated!

Thanks

答:
First, please read the answer to How to make good reproducible pandas examples. In the future please provide a minimal reproducibl example.

Secondly, Michael G is absolutely correct that phylip is a format that is very peculiar about its syntax.

The code below will alow you to generate a phylogenetic tree from your Pandas dataframe.

First some imports and let's recreate your dataframe.

```<code>import pandas as pd
from Bio import Phylo
from Bio.Phylo.TreeConstruction import DistanceCalculator
from Bio.Phylo.TreeConstruction import DistanceTreeConstructor
from Bio import AlignIO

data = {'ESV' : ['esv1', 'esv2', 'esv3'],
        'trunc': ['TACGTAGGTGGCGAGCGTTATCCGGAATTATTGGGCGTAAAGCGCGCGCAGGCGGTTTCTTAAGTCTGATGTGAAAGCCCACGGCTCAACCGTGGAGGGTCATTGGAAACTGGGAAACTTGAGTGCAGAAGAGGAAAGCGGAATTCCACGTGTAGCGGTGAAATGCGTAGAGATGTGGAGGAACACCAGTGGCGAAGGCGGCTTTCTGGTCTGTAACTGACGCTGAGGCGCGAAAGCGTGGGGAGCAAACAGG',
                 'TACGGAGGGTGCAAGCGTTATCCGGATTCACTGGGTTTAAAGGGTGCGTAGGTGGGTTGGTAAGTCAGTGGTGAAATCTCCGAGCTTAACTTGGAAACTGCCATTGATACTATTAATCTTGAATATTGTGGAGGTTAGCGGAATATGTCATGTAGCGGTGAAATGCTTAGAGATGACATAGAACACCAATTGCGAAGGCAGCTGGCTACACATATATTGACACTGAGGCACGAAAGCGTGGGGATCAAACAGG',
                 'TACGGGGGGGGCAAGCGTTGTTCGGAATTACTGGGCGTAAAGGGCGCGTAGGCGGCCAGACCAAGTCGAGTGTGAAATTGCAGGGCTTAACTTTGCAGGGTCGCTCGATACTGGTCGGCTAGAGTGTGGAAGAGGGTACTGGAATTCCCGGTGTAGCGGTGAAATGCGTAGATATCGGGAGGAACACCAGCGGCGAAGGCGGGTACCTGGGCCAACACTGACGCTGAGGCGCGAAAGCTAGGGGAGCAAACAG']

}

ndf = pd.DataFrame.from_dict(data)
print(ndf)
</code>```

Output:

```<code>    ESV                                              trunc
0  esv1  TACGTAGGTGGCGAGCGTTATCCGGAATTATTGGGCGTAAAGCGCG...
1  esv2  TACGGAGGGTGCAAGCGTTATCCGGATTCACTGGGTTTAAAGGGTG...
2  esv3  TACGGGGGGGGCAAGCGTTGTTCGGAATTACTGGGCGTAAAGGGCG...
</code>```

Next, write the phylip file in the correct format.

```<code>with open("test.phy", 'w') as f:
    f.write("{:10} {}\n".format(ndf.shape[0], ndf.trunc.str.len()[0]))
    for row in ndf.iterrows():
        f.write("{:10} {}\n".format(*row[1].to_list()))
</code>```

Ouput of test.phy:

```<code>         3 253
esv1       TACGTAGGTGGCGAGCGTTATCCGGAATTATTGGGCGTAAAGCGCGCGCAGGCGGTTTCTTAAGTCTGATGTGAAAGCCCACGGCTCAACCGTGGAGGGTCATTGGAAACTGGGAAACTTGAGTGCAGAAGAGGAAAGCGGAATTCCACGTGTAGCGGTGAAATGCGTAGAGATGTGGAGGAACACCAGTGGCGAAGGCGGCTTTCTGGTCTGTAACTGACGCTGAGGCGCGAAAGCGTGGGGAGCAAACAGG
esv2       TACGGAGGGTGCAAGCGTTATCCGGATTCACTGGGTTTAAAGGGTGCGTAGGTGGGTTGGTAAGTCAGTGGTGAAATCTCCGAGCTTAACTTGGAAACTGCCATTGATACTATTAATCTTGAATATTGTGGAGGTTAGCGGAATATGTCATGTAGCGGTGAAATGCTTAGAGATGACATAGAACACCAATTGCGAAGGCAGCTGGCTACACATATATTGACACTGAGGCACGAAAGCGTGGGGATCAAACAGG
esv3       TACGGGGGGGGCAAGCGTTGTTCGGAATTACTGGGCGTAAAGGGCGCGTAGGCGGCCAGACCAAGTCGAGTGTGAAATTGCAGGGCTTAACTTTGCAGGGTCGCTCGATACTGGTCGGCTAGAGTGTGGAAGAGGGTACTGGAATTCCCGGTGTAGCGGTGAAATGCGTAGATATCGGGAGGAACACCAGCGGCGAAGGCGGGTACCTGGGCCAACACTGACGCTGAGGCGCGAAAGCTAGGGGAGCAAACAG
</code>```

Now we can start with the creation of our phylogenetic tree.

```<code># Read the sequences and align
aln = AlignIO.read('test.phy', 'phylip')
print(aln)
</code>```

Output:

```<code>SingleLetterAlphabet() alignment with 3 rows and 253 columns
TACGTAGGTGGCGAGCGTTATCCGGAATTATTGGGCGTAAAGCG...AGG esv1
TACGGAGGGTGCAAGCGTTATCCGGATTCACTGGGTTTAAAGGG...AGG esv2
TACGGGGGGGGCAAGCGTTGTTCGGAATTACTGGGCGTAAAGGG...CAG esv3
</code>```

Calculate the distance matrix:

```<code>calculator = DistanceCalculator('identity')
dm = calculator.get_distance(aln)
print(dm)
</code>```

Output:

```<code>esv1    0
esv2    0.3003952569169961  0
esv3    0.6086956521739131  0.6245059288537549  0
</code>```

Construct the phylogenetic tree using UPGMA algorithm and draw the tree in ascii

```<code>constructor = DistanceTreeConstructor()
tree = constructor.upgma(dm)
Phylo.draw_ascii(tree)
</code>```

Output:

```<code>  ________________________________________________________________________ esv3
_|
 |                                     ___________________________________ esv2
 |____________________________________|
                                      |___________________________________ esv1
</code>```

Or make a nice plot of the tree:

```<code>    ESV                                              trunc
0  esv1  TACGTAGGTGGCGAGCGTTATCCGGAATTATTGGGCGTAAAGCGCG...
1  esv2  TACGGAGGGTGCAAGCGTTATCCGGATTCACTGGGTTTAAAGGGTG...
2  esv3  TACGGGGGGGGCAAGCGTTGTTCGGAATTACTGGGCGTAAAGGGCG...
</code>```0

Output:

Body:
First, please read the answer to How to make good reproducible pandas examples. In the future please provide a minimal reproducibl example.

Secondly, Michael G is absolutely correct that phylip is a format that is very peculiar about its syntax.

The code below will alow you to generate a phylogenetic tree from your Pandas dataframe.

First some imports and let's recreate your dataframe.

import pandas as pd
from Bio import Phylo
from Bio.Phylo.TreeConstruction import DistanceCalculator
from Bio.Phylo.TreeConstruction import DistanceTreeConstructor
from Bio import AlignIO

data = {'ESV' : ['esv1', 'esv2', 'esv3'],
        'trunc': ['TACGTAGGTGGCGAGCGTTATCCGGAATTATTGGGCGTAAAGCGCGCGCAGGCGGTTTCTTAAGTCTGATGTGAAAGCCCACGGCTCAACCGTGGAGGGTCATTGGAAACTGGGAAACTTGAGTGCAGAAGAGGAAAGCGGAATTCCACGTGTAGCGGTGAAATGCGTAGAGATGTGGAGGAACACCAGTGGCGAAGGCGGCTTTCTGGTCTGTAACTGACGCTGAGGCGCGAAAGCGTGGGGAGCAAACAGG',
                 'TACGGAGGGTGCAAGCGTTATCCGGATTCACTGGGTTTAAAGGGTGCGTAGGTGGGTTGGTAAGTCAGTGGTGAAATCTCCGAGCTTAACTTGGAAACTGCCATTGATACTATTAATCTTGAATATTGTGGAGGTTAGCGGAATATGTCATGTAGCGGTGAAATGCTTAGAGATGACATAGAACACCAATTGCGAAGGCAGCTGGCTACACATATATTGACACTGAGGCACGAAAGCGTGGGGATCAAACAGG',
                 'TACGGGGGGGGCAAGCGTTGTTCGGAATTACTGGGCGTAAAGGGCGCGTAGGCGGCCAGACCAAGTCGAGTGTGAAATTGCAGGGCTTAACTTTGCAGGGTCGCTCGATACTGGTCGGCTAGAGTGTGGAAGAGGGTACTGGAATTCCCGGTGTAGCGGTGAAATGCGTAGATATCGGGAGGAACACCAGCGGCGAAGGCGGGTACCTGGGCCAACACTGACGCTGAGGCGCGAAAGCTAGGGGAGCAAACAG']

}

ndf = pd.DataFrame.from_dict(data)
print(ndf)

Output:

    ESV                                              trunc
0  esv1  TACGTAGGTGGCGAGCGTTATCCGGAATTATTGGGCGTAAAGCGCG...
1  esv2  TACGGAGGGTGCAAGCGTTATCCGGATTCACTGGGTTTAAAGGGTG...
2  esv3  TACGGGGGGGGCAAGCGTTGTTCGGAATTACTGGGCGTAAAGGGCG...

Next, write the phylip file in the correct format.

with open("test.phy", 'w') as f:
    f.write("{:10} {}\n".format(ndf.shape[0], ndf.trunc.str.len()[0]))
    for row in ndf.iterrows():
        f.write("{:10} {}\n".format(*row[1].to_list()))

Ouput of test.phy:

         3 253
esv1       TACGTAGGTGGCGAGCGTTATCCGGAATTATTGGGCGTAAAGCGCGCGCAGGCGGTTTCTTAAGTCTGATGTGAAAGCCCACGGCTCAACCGTGGAGGGTCATTGGAAACTGGGAAACTTGAGTGCAGAAGAGGAAAGCGGAATTCCACGTGTAGCGGTGAAATGCGTAGAGATGTGGAGGAACACCAGTGGCGAAGGCGGCTTTCTGGTCTGTAACTGACGCTGAGGCGCGAAAGCGTGGGGAGCAAACAGG
esv2       TACGGAGGGTGCAAGCGTTATCCGGATTCACTGGGTTTAAAGGGTGCGTAGGTGGGTTGGTAAGTCAGTGGTGAAATCTCCGAGCTTAACTTGGAAACTGCCATTGATACTATTAATCTTGAATATTGTGGAGGTTAGCGGAATATGTCATGTAGCGGTGAAATGCTTAGAGATGACATAGAACACCAATTGCGAAGGCAGCTGGCTACACATATATTGACACTGAGGCACGAAAGCGTGGGGATCAAACAGG
esv3       TACGGGGGGGGCAAGCGTTGTTCGGAATTACTGGGCGTAAAGGGCGCGTAGGCGGCCAGACCAAGTCGAGTGTGAAATTGCAGGGCTTAACTTTGCAGGGTCGCTCGATACTGGTCGGCTAGAGTGTGGAAGAGGGTACTGGAATTCCCGGTGTAGCGGTGAAATGCGTAGATATCGGGAGGAACACCAGCGGCGAAGGCGGGTACCTGGGCCAACACTGACGCTGAGGCGCGAAAGCTAGGGGAGCAAACAG

Now we can start with the creation of our phylogenetic tree.

# Read the sequences and align
aln = AlignIO.read('test.phy', 'phylip')
print(aln)

Output:

SingleLetterAlphabet() alignment with 3 rows and 253 columns
TACGTAGGTGGCGAGCGTTATCCGGAATTATTGGGCGTAAAGCG...AGG esv1
TACGGAGGGTGCAAGCGTTATCCGGATTCACTGGGTTTAAAGGG...AGG esv2
TACGGGGGGGGCAAGCGTTGTTCGGAATTACTGGGCGTAAAGGG...CAG esv3

Calculate the distance matrix:

calculator = DistanceCalculator('identity')
dm = calculator.get_distance(aln)
print(dm)

Output:

esv1    0
esv2    0.3003952569169961  0
esv3    0.6086956521739131  0.6245059288537549  0

Construct the phylogenetic tree using UPGMA algorithm and draw the tree in ascii

constructor = DistanceTreeConstructor()
tree = constructor.upgma(dm)
Phylo.draw_ascii(tree)

Output:

  ________________________________________________________________________ esv3
_|
 |                                     ___________________________________ esv2
 |____________________________________|
                                      |___________________________________ esv1

Or make a nice plot of the tree:

Phylo.draw(tree)

Output:


问:
How can i use i tag as input tag?
I want to replace input with i tag: it's original code

```<code><a class="card-footer text-white clearfix small z-1" href="#">
    <span class="float-left">
        <form id="myform" action='model/excel.php' method='post'>
            <input type='submit' name='export_excel' value='Export To Excel' class='btn btn-default btn-sm'/>
        </form>
    </span>
</a>
</code>```

答:
Sounds like you want to use a Font Awesome Excel icon in your button for submission. In that case, I would switch to a button and place the icon inside of it:

<button type="submit" name="export_excel" class="btn btn-default btn-sm">

</button>
```

Title: How can i use i tag as input tag?

Body:
I want to replace input with i tag: it's original code

        <form id="myform" action='model/excel.php' method='post'>
            <input type='submit' name='export_excel' value='Export To Excel' class='btn btn-default btn-sm'/>
        </form>

Body:
Sounds like you want to use a Font Awesome Excel icon in your button for submission. In that case, I would switch to a button and place the icon inside of it:

<button type="submit" name="export_excel" class="btn btn-default btn-sm">
  <i class="fa fa-fw fa-file-excel-o"></i>
</button>


问:
python distutils: how to change default compiler flags for one Extension only
I have setup.py defining two Extensions and I'd like to change default CFLAGS for one extension, but not for the other. I checked the official documentation https://docs.python.org/3/distutils/apiref.html#distutils.core.Extension but it does not explain what I need. It does explain how to add extra compiler/linker flags thoiugh.

What is the right way to do this?

答: I would follow the recipe from Python Extension Patterns and reset the CFLAGS before compiling the Extensions and then restore them while setting all of the compiler flags in each fo the Extensions separately from scratch.


问:
Vue.js - How to create child component's DOM element outside of it's parent component's DOM element
I'm trying to create a child component, but instead of putting it's DOM element inside parent's as it is by default, I want to put it somewhere else.

I want to create child component of modal component, but there is a issue because the modal component is overflow: hidden, and I need the child component to be visible outside of the modal. The best solution I've found is how Vuetify do it with their v-menu component (link below). They simply not create child component's DOM element as a child node of it's parent component's DOM element, but instead they put it somewhere else.
I read their code on github, but I'm quite confused with the implementation, and found nothing in Vue documentation about this.

https://vuetifyjs.com/en/components/menus

答:
Child:

```<code><template>
    <div>
         I'm CHILD
         <slot></slot>
    </div>
</template>
</code>```

Parent:

```<code><template>
    <div>
        <Child>
            <span>I'm parent</span>
        </Child>
    </div>
</template>
</code>```

Body:
Child:

<template>
    <div>
         I'm CHILD
         <slot></slot>
    </div>
</template>

Parent:

<template>
    <div>
        <Child>
            <span>I'm parent</span>
        </Child>
    </div>
</template>


问:
postgres extract JSON column key and values to separate columns
I have a table that has a column that was created by

```<code>json_object_agg(eventid,date_now_range) eventids_range
</code>```

this what the data looks like stored in the table

```<code>{ "527813" : 184, "525947" : 133, "529957" : 178, "531490" : 143 }
</code>```

I want to select this record and have the key and value be its own record

so this

```<code>select eventids_range from special_event_conflicts
</code>```

would return something like this

```<code>col a     col b
527813    184
525947    133
529957    178
531490    143
</code>```

答:
Here is one option:

```<code>select k.cola, v.colb
from mytable t
cross join lateral json_object_keys(t.eventids_range) as k(cola)
cross join lateral json_extract_path_text(t.eventids_range, k.cola) v(colb)
</code>```

This works by first extracting the keys from the object using json_object_keys(), and then accessing the corresponding values with json_extract_path_text().

Demo on DB Fiddle:

```
cola   | colb
:----- | :---
527813 | 184
525947 | 133
529957 | 178
531490 | 143
```

Another - probably better - solution is to use json_each():

```<code>select x.cola, x.colb
from mytable t
cross join lateral json_each(t.eventids_range) as x(cola, colb)
</code>```

Demo on DB Fiddle

Body:
I have a table that has a column that was created by

json_object_agg(eventid,date_now_range) eventids_range

this what the data looks like stored in the table

{ "527813" : 184, "525947" : 133, "529957" : 178, "531490" : 143 }

I want to select this record and have the key and value be its own record

so this

select eventids_range from special_event_conflicts

would return something like this

col a     col b
527813    184
525947    133
529957    178
531490    143

Body:
Here is one option:

select k.cola, v.colb
from mytable t
cross join lateral json_object_keys(t.eventids_range) as k(cola)
cross join lateral json_extract_path_text(t.eventids_range, k.cola) v(colb)

This works by first extracting the keys from the object using json_object_keys(), and then accessing the corresponding values with json_extract_path_text().

Demo on DB Fiddle:

cola   | colb
:----- | :---
527813 | 184
525947 | 133
529957 | 178
531490 | 143

Another - probably better - solution is to use json_each():

select x.cola, x.colb
from mytable t
cross join lateral json_each(t.eventids_range) as x(cola, colb)

Demo on DB Fiddle