问:
cannot pull an object from an array and also at the same time cannot pull value from its nested array
i have a document given bellow-

```<code>{
  "_id": {
      "$oid": "61fb6bf71be79c03227d6bbf"
  },
  "id": "17202155",

  "completed": ["cse331", "cse312"],

  "incompleted": [{
      "name": "math",
      "preReq": ["bang", "eng"]
  }, {
      "name": "science",
      "preReq": ["bang", "eng", "math"]
  }, {
      "name": "astronomy",
      "preReq": ["bang", "eng", "science","math"]
  }]
}
</code>```

I want to pull the objejct from the array named "incompleted" where the name:math and also pull "math" from all the "preReq".

in short i want to update the document. And the resulted document -

```<code>{
  "_id": {
      "$oid": "61fb6bf71be79c03227d6bbf"
  },
  "id": "17202155",

  "completed": ["cse331", "cse312"],

  "incompleted": [{
      "name": "science",
      "preReq": ["bang", "eng"]
  }, {
      "name": "astronomy",
      "preReq": ["bang", "eng", "science"]
  }]
}
</code>```

I used this code-

```<code>stCourseCompetion_collection.updateOne({id:"17202155"},
             {
                $pull:{
                   "incompleted":{ "name":"math"},
                   "incompleted.$[].preReq":"math"
                }
             }).then(result=>{
                console.log(result);
             })
</code>```

but it does not work.

It give me some error like-

(node:14996) UnhandledPromiseRejectionWarning: MongoServerError: Updating the path 'incompleted.$[].preReq' would create a conflict at 'incompleted'

```<code>at F:\senior project\ciu-app-practise\ciu-app-db\node_modules\mongodb\lib\operations\update.js:80:33
at F:\senior project\ciu-app-practise\ciu-app-db\node_modules\mongodb\lib\cmap\connection_pool.js:272:25
at handleOperationResult (F:\senior project\ciu-app-practise\ciu-app-db\node_modules\mongodb\lib\sdam\server.js:363:9)
at MessageStream.messageHandler (F:\senior project\ciu-app-practise\ciu-app-db\node_modules\mongodb\lib\cmap\connection.js:479:9)

at MessageStream.emit (events.js:400:28)
at processIncomingData (F:\senior project\ciu-app-practise\ciu-app-db\node_modules\mongodb\lib\cmap\message_stream.js:108:16)
at MessageStream._write (F:\senior project\ciu-app-practise\ciu-app-db\node_modules\mongodb\lib\cmap\message_stream.js:28:9)
at writeOrBuffer (internal/streams/writable.js:358:12)
at MessageStream.Writable.write (internal/streams/writable.js:303:10)
at TLSSocket.ondata (internal/streams/readable.js:731:22) (Use `node --trace-warnings ...` to show where the warning was created) (node:14996) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
</code>```

答:
You cannot pull from two different arrays at the same time , you need to do it with two commands:

Pull  math element from preReq array:

```<code>db.collection.update({
   id: "17202155"
  },
  {
   $pull: {
   "incompleted.$[].preReq": "math"
  }
  })
</code>```

playground 1

Pull the name:"math" element from the incompleted array:

```<code>db.collection.update({
 id: "17202155"
 },
 {
  $pull: {
  "incompleted": {
   name: "math"
  }
 }
})
</code>```

playground 2

Body:
i have a document given bellow-

{
  "_id": {
      "$oid": "61fb6bf71be79c03227d6bbf"
  },
  "id": "17202155",

  "completed": ["cse331", "cse312"],

  "incompleted": [{
      "name": "math",
      "preReq": ["bang", "eng"]
  }, {
      "name": "science",
      "preReq": ["bang", "eng", "math"]
  }, {
      "name": "astronomy",
      "preReq": ["bang", "eng", "science","math"]
  }]
}

I want to pull the objejct from the array named "incompleted" where the name:math and also pull "math" from all the "preReq".

in short i want to update the document. And the resulted document -

{
  "_id": {
      "$oid": "61fb6bf71be79c03227d6bbf"
  },
  "id": "17202155",

  "completed": ["cse331", "cse312"],

  "incompleted": [{
      "name": "science",
      "preReq": ["bang", "eng"]
  }, {
      "name": "astronomy",
      "preReq": ["bang", "eng", "science"]
  }]
}

I used this code-

stCourseCompetion_collection.updateOne({id:"17202155"},
             {
                $pull:{
                   "incompleted":{ "name":"math"},
                   "incompleted.$[].preReq":"math"
                }
             }).then(result=>{
                console.log(result);
             })

but it does not work.

It give me some error like-

(node:14996) UnhandledPromiseRejectionWarning: MongoServerError: Updating the path 'incompleted.$[].preReq' would create a conflict at 'incompleted'

at F:\senior project\ciu-app-practise\ciu-app-db\node_modules\mongodb\lib\operations\update.js:80:33
at F:\senior project\ciu-app-practise\ciu-app-db\node_modules\mongodb\lib\cmap\connection_pool.js:272:25
at handleOperationResult (F:\senior project\ciu-app-practise\ciu-app-db\node_modules\mongodb\lib\sdam\server.js:363:9)
at MessageStream.messageHandler (F:\senior project\ciu-app-practise\ciu-app-db\node_modules\mongodb\lib\cmap\connection.js:479:9)

at MessageStream.emit (events.js:400:28)
at processIncomingData (F:\senior project\ciu-app-practise\ciu-app-db\node_modules\mongodb\lib\cmap\message_stream.js:108:16)
at MessageStream._write (F:\senior project\ciu-app-practise\ciu-app-db\node_modules\mongodb\lib\cmap\message_stream.js:28:9)
at writeOrBuffer (internal/streams/writable.js:358:12)
at MessageStream.Writable.write (internal/streams/writable.js:303:10)
at TLSSocket.ondata (internal/streams/readable.js:731:22) (Use `node --trace-warnings ...` to show where the warning was created) (node:14996) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)

Body:
You cannot pull from two different arrays at the same time , you need to do it with two commands:

Pull  math element from preReq array:

db.collection.update({
   id: "17202155"
  },
  {
   $pull: {
   "incompleted.$[].preReq": "math"
  }
  })

playground 1

Pull the name:"math" element from the incompleted array:

db.collection.update({
 id: "17202155"
 },
 {
  $pull: {
  "incompleted": {
   name: "math"
  }
 }
})

playground 2


来源: stackexchange

问:
After merging Master branch, fixing conflicts, removing other files from the merge, GIT is treating files in my feature branch as latest
So, trying to be proactive knowing that there were going to be some merge conflicts when merging my feature branch into Master, I went ahead and merged Master to my branch locally, fixed the conflicts, and here is the critical part---I only ended up committing the files merged from Master that I'd been working on, and removed all the rest from the commit. Looking back of course, I shouldn't have done this... I didn't realize that it was going to treat those files that I removed as the latest changes on my feature branch.

So, attempting to do a pull request into Master, I realize that all of those files I took out of the original merge were trying to overwrite newer files in Master.

This turned out to be OK, I was able to take my commit on the feature branch BEFORE the merge and clone a new branch from there. So, a learning experience. My question is... was there another better way to have handled this? I'd tried reverting the merge commit but somehow it was still trying to overwrite all of those same files when I looked at merging to Master.

Thanks

答:
My question is... was there another way to do this?

It depends what "this" is:

The correct way to deal with a merge conflict is to edit the conflicted files to resolve the conflict, add them, and say git commit.

The correct way to undo a bad merge is to reset hard back to the commit before the merge commit.

ContentLicense: CC BY-SA 4.0


问:
Analysis of algorithms
I am reading algorithm analysis topic. Here is the text snippet from the book

When n doubles, the running time goes up by a factor of 2 for linear
  programs, 4 for quadratic programs, and  8 for cubic programs.
  Programs that run in logarithmic time take only an additive constant
  longer when n doubles,  and programs that run in O(n log n) take
  slightly more than twice as long to run under the same circumstances.

These increases can be hard to spot if the lower-order terms have
  relatively large coefficients and n is not large enough.

My question is what does author mean lower-order terms have relatively large coefficients? Can any one explain with example

Thanks!

答:
Suppose your algorithm actually executes n^2 + 1000 n computations when run on n elements. Now for n = 1 you need 1001 computations, and for n = 2 you need 2004. The difference from linear growth is tiny, and you can hardly spot the quadratic contribution!

Asymptotically, however, your algorithm takes O(n^2) steps, so asymptotically (as n gets large) doubling the input size quadruples your runtime. But for our small value, doubling from 1 to 2 did not quadruple the runtime! The lower-order term is n, and its coefficient (1000) is large compared to the coefficient of the leading-order termn^2 (which is 1).

This shows how the asymptotic complexity does not say anything about particular, especially small values. It's merely a limiting statement about the behaviour as n gets large.

ContentLicense: CC BY-SA 3.0

Title: Analysis of algorithms


问:
Issue: VLC player opens up separate windows for video and audio in Ubuntu 20.04.3 LTS
I am using Ubuntu 20.04.3 LTS and I installed VLC player from snap store (version: 3.0.16).

but when I open up a video file with VLC player, it opens up a window for the video and another window for the audio.

I have tried few solutions mentioned in this website, but it did not work for me. How can I solve this issue?

答:
Also got this issue with the snap version 3.0.16. Removing /home/<user-name>/snap/vlc/current/.config/vlc worked for me, but I had to keep removing that file often because the issue would reappear.

The permanent solution for me was to get rid of the snap version via sudo snap remove vlc, and then install an apt version via sudo apt-get install vlc. At the time of writing, the new version I got from apt was 3.0.9.2 Vetinari.


问:
How to modify search fields on xmlui
Im new to Dspace. Im using the XMLUI interface, and the version 6.3
I want to modify the search fields, and the instructions from the wiki (https://wiki.lyrasis.org/display/DSPACE/Modify+search+fields) says that I sould look for this line in dspace.cfg: ##### Fields to Index for Search #####

But in the dspace.cfg document, that line is only under the JSPUI specific configurations

```<code>    ### Configure the search indices to appear in advanced search drop down lists
#
jspui.search.index.display.1 = ANY
jspui.search.index.display.2 = author
jspui.search.index.display.3 = title
jspui.search.index.display.4 = keyword
jspui.search.index.display.5 = abstract
jspui.search.index.display.6 = series
jspui.search.index.display.7 = sponsor
jspui.search.index.display.8 = identifier
jspui.search.index.display.9 = language
</code>```

Does anyone knows how I can change the search fields in the xmlui interface?
I don't know if I'm looking in the wrong file because I'm a begginer, but I can't find any other dspace.cfg document, and neither can I find a dspace.src document. Thanks in advance

答:
I think what you're looking for is the discovery search filters. You can add metadata fields that you would like to be 'searchable' aside from the default fields. Please see the documentation for discovery: Configuring lists of sidebarFacets and searchFilters

The file to edit can be found in [dspace]/config/spring/api/discovery.xml.

For example, I created a new search filter for document types.

```<code>    <bean id="searchFilterType" class="org.dspace.discovery.configuration.DiscoverySearchFilterFacet">
        <property name="indexFieldName" value="type"/>
        <property name="metadataFields">
            <list>
                <value>dc.type</value>
            </list>
        </property>
        <property name="sortOrderSidebar" value="COUNT"/>
        <property name="sortOrderFilterPage" value="VALUE"/>
    </bean>
</code>```

Then I reference it in the defaultConfiguration bean to appear in sidebar facets and search filters. Please note that all sidebar facets should also have a search filter as per the documentation:

Each sidebar facet must also occur in the list of the search filters.

```<code>    <!--The default configuration settings for discovery-->
    <bean id="defaultConfiguration" class="org.dspace.discovery.configuration.DiscoveryConfiguration" scope="prototype">
        <!--Which sidebar facets are to be displayed-->
        <property name="sidebarFacets">
            <list>
                <ref bean="searchFilterAuthor" />
                <ref bean="searchFilterSubject" />
                <ref bean="searchFilterIssued" />
                <ref bean="searchFilterType" />
                <ref bean="searchFilterContentInOriginalBundle"/>
            </list>
        </property>
        <!-- Set TagCloud configuration per discovery configuration -->
        <property name="tagCloudFacetConfiguration" ref="defaultTagCloudFacetConfiguration"/>
        <!--The search filters which can be used on the discovery search page-->
        <property name="searchFilters">
            <list>
                <ref bean="searchFilterTitle" />
                <ref bean="searchFilterAuthor" />
                <ref bean="searchFilterSubject" />
                <ref bean="searchFilterIssued" />
                <ref bean="searchFilterType" />
                <ref bean="searchFilterContentInOriginalBundle"/>
                <ref bean="searchFilterFileNameInOriginalBundle" />
                <ref bean="searchFilterFileDescriptionInOriginalBundle" />
            </list>
        </property>
        <!--The sort filters for the discovery search-->
        <property name="searchSortConfiguration">
            <bean class="org.dspace.discovery.configuration.DiscoverySortConfiguration">
                <!--<property name="defaultSort" ref="sortDateIssued"/>-->
                <!--DefaultSortOrder can either be desc or asc (desc is default)-->
                <property name="defaultSortOrder" value="desc"/>
                <property name="sortFields">
                    <list>
                        <ref bean="sortTitle" />
                        <ref bean="sortDateIssued" />
                    </list>
                </property>
            </bean>
        </property>
        <!--Any default filter queries, these filter queries will be used for all queries done by discovery for this configuration-->
        <!--<property name="defaultFilterQueries">-->
            <!--<list>-->
                <!--Only find items-->
                <!--<value>search.resourcetype:2</value>-->
            <!--</list>-->
        <!--</property>-->
        <property name="defaultFilterQueries">
        <list>
        <!--Only find items-->
        <value>search.resourcetype:2</value>
        </list>
        </property>
        <!--The configuration for the recent submissions-->
        <property name="recentSubmissionConfiguration">
            <bean class="org.dspace.discovery.configuration.DiscoveryRecentSubmissionsConfiguration">
                <property name="metadataSortField" value="dc.date.accessioned" />
                <property name="type" value="date"/>
                <property name="max" value="20"/>
                <!-- If enabled the collection home page will not display metadata but show a pageable list of recent submissions -->
                <property name="useAsHomePage" value="false"/>
            </bean>
        </property>
        <!--Default result per page  -->
        <property name="defaultRpp" value="10" />
        <property name="hitHighlightingConfiguration">
            <bean class="org.dspace.discovery.configuration.DiscoveryHitHighlightingConfiguration">
                <property name="metadataFields">
                    <list>
                        <bean class="org.dspace.discovery.configuration.DiscoveryHitHighlightFieldConfiguration">
                            <property name="field" value="dc.title"/>
                            <property name="snippets" value="5"/>
                        </bean>
                        <bean class="org.dspace.discovery.configuration.DiscoveryHitHighlightFieldConfiguration">
                            <property name="field" value="dc.contributor.author"/>
                            <property name="snippets" value="5"/>
                        </bean>
                        <bean class="org.dspace.discovery.configuration.DiscoveryHitHighlightFieldConfiguration">
                            <property name="field" value="dc.description.abstract"/>
                            <property name="maxSize" value="250"/>
                            <property name="snippets" value="2"/>
                        </bean>
                        <!-- By default, full text snippets are disabled, as snippets of embargoed/restricted bitstreams
                         may appear in search results when the Item is public. See DS-3498
                        <bean class="org.dspace.discovery.configuration.DiscoveryHitHighlightFieldConfiguration">
                            <property name="field" value="fulltext"/>
                            <property name="maxSize" value="250"/>
                            <property name="snippets" value="2"/>
                        </bean>
                        -->
                    </list>
                </property>
            </bean>
        </property>
        <property name="moreLikeThisConfiguration">
            <bean class="org.dspace.discovery.configuration.DiscoveryMoreLikeThisConfiguration">
                <!--When altering this list also alter the "xmlui.Discovery.RelatedItems.help" key as it describes
            the metadata fields below-->
                <property name="similarityMetadataFields">
                    <list>
                        <value>dc.title</value>
                        <value>dc.contributor.author</value>
                        <value>dc.creator</value>
                        <value>dc.subject</value>
                    </list>
                </property>
                <!--The minimum number of matching terms across the metadata fields above before an item is found as related -->
                <property name="minTermFrequency" value="5"/>
                <!--The maximum number of related items displayed-->
                <property name="max" value="3"/>
                <!--The minimum word length below which words will be ignored-->
                <property name="minWordLength" value="5"/>
            </bean>
        </property>
        <!-- When true a "did you mean" example will be displayed, value can be true or false -->
        <property name="spellCheckEnabled" value="true"/>
    </bean>
</code>```

Lastly, you should also update the search filters and sidebar facets in the homepageConfiguration bean if you want your new sidebar facets to appear in the home page. Don't forget to restart DSpace (stop and start Tomcat) and run dspace index-discovery -b every time you modified discovery.xml.

Title: How to modify search fields on xmlui

Body:
Im new to Dspace. Im using the XMLUI interface, and the version 6.3
I want to modify the search fields, and the instructions from the wiki (https://wiki.lyrasis.org/display/DSPACE/Modify+search+fields) says that I sould look for this line in dspace.cfg: ##### Fields to Index for Search #####

But in the dspace.cfg document, that line is only under the JSPUI specific configurations

    ### Configure the search indices to appear in advanced search drop down lists
#
jspui.search.index.display.1 = ANY
jspui.search.index.display.2 = author
jspui.search.index.display.3 = title
jspui.search.index.display.4 = keyword
jspui.search.index.display.5 = abstract
jspui.search.index.display.6 = series
jspui.search.index.display.7 = sponsor
jspui.search.index.display.8 = identifier
jspui.search.index.display.9 = language

Does anyone knows how I can change the search fields in the xmlui interface?
I don't know if I'm looking in the wrong file because I'm a begginer, but I can't find any other dspace.cfg document, and neither can I find a dspace.src document. Thanks in advance

Body:
I think what you're looking for is the discovery search filters. You can add metadata fields that you would like to be 'searchable' aside from the default fields. Please see the documentation for discovery: Configuring lists of sidebarFacets and searchFilters

The file to edit can be found in [dspace]/config/spring/api/discovery.xml.

For example, I created a new search filter for document types.

    <bean id="searchFilterType" class="org.dspace.discovery.configuration.DiscoverySearchFilterFacet">
        <property name="indexFieldName" value="type"/>
        <property name="metadataFields">
            <list>
                <value>dc.type</value>
            </list>
        </property>
        <property name="sortOrderSidebar" value="COUNT"/>
        <property name="sortOrderFilterPage" value="VALUE"/>
    </bean>

Then I reference it in the defaultConfiguration bean to appear in sidebar facets and search filters. Please note that all sidebar facets should also have a search filter as per the documentation:

Each sidebar facet must also occur in the list of the search filters.

    <!--The default configuration settings for discovery-->
    <bean id="defaultConfiguration" class="org.dspace.discovery.configuration.DiscoveryConfiguration" scope="prototype">
        <!--Which sidebar facets are to be displayed-->
        <property name="sidebarFacets">
            <list>
                <ref bean="searchFilterAuthor" />
                <ref bean="searchFilterSubject" />
                <ref bean="searchFilterIssued" />
                <ref bean="searchFilterType" />
                <ref bean="searchFilterContentInOriginalBundle"/>
            </list>
        </property>
        <!-- Set TagCloud configuration per discovery configuration -->
        <property name="tagCloudFacetConfiguration" ref="defaultTagCloudFacetConfiguration"/>
        <!--The search filters which can be used on the discovery search page-->
        <property name="searchFilters">
            <list>
                <ref bean="searchFilterTitle" />
                <ref bean="searchFilterAuthor" />
                <ref bean="searchFilterSubject" />
                <ref bean="searchFilterIssued" />
                <ref bean="searchFilterType" />
                <ref bean="searchFilterContentInOriginalBundle"/>
                <ref bean="searchFilterFileNameInOriginalBundle" />
                <ref bean="searchFilterFileDescriptionInOriginalBundle" />
            </list>
        </property>
        <!--The sort filters for the discovery search-->
        <property name="searchSortConfiguration">
            <bean class="org.dspace.discovery.configuration.DiscoverySortConfiguration">
                <!--<property name="defaultSort" ref="sortDateIssued"/>-->
                <!--DefaultSortOrder can either be desc or asc (desc is default)-->
                <property name="defaultSortOrder" value="desc"/>
                <property name="sortFields">
                    <list>
                        <ref bean="sortTitle" />
                        <ref bean="sortDateIssued" />
                    </list>
                </property>
            </bean>
        </property>
        <!--Any default filter queries, these filter queries will be used for all queries done by discovery for this configuration-->
        <!--<property name="defaultFilterQueries">-->
            <!--<list>-->
                <!--Only find items-->
                <!--<value>search.resourcetype:2</value>-->
            <!--</list>-->
        <!--</property>-->
        <property name="defaultFilterQueries">
        <list>
        <!--Only find items-->
        <value>search.resourcetype:2</value>
        </list>
        </property>
        <!--The configuration for the recent submissions-->
        <property name="recentSubmissionConfiguration">
            <bean class="org.dspace.discovery.configuration.DiscoveryRecentSubmissionsConfiguration">
                <property name="metadataSortField" value="dc.date.accessioned" />
                <property name="type" value="date"/>
                <property name="max" value="20"/>
                <!-- If enabled the collection home page will not display metadata but show a pageable list of recent submissions -->
                <property name="useAsHomePage" value="false"/>
            </bean>
        </property>
        <!--Default result per page  -->
        <property name="defaultRpp" value="10" />
        <property name="hitHighlightingConfiguration">
            <bean class="org.dspace.discovery.configuration.DiscoveryHitHighlightingConfiguration">
                <property name="metadataFields">
                    <list>
                        <bean class="org.dspace.discovery.configuration.DiscoveryHitHighlightFieldConfiguration">
                            <property name="field" value="dc.title"/>
                            <property name="snippets" value="5"/>
                        </bean>
                        <bean class="org.dspace.discovery.configuration.DiscoveryHitHighlightFieldConfiguration">
                            <property name="field" value="dc.contributor.author"/>
                            <property name="snippets" value="5"/>
                        </bean>
                        <bean class="org.dspace.discovery.configuration.DiscoveryHitHighlightFieldConfiguration">
                            <property name="field" value="dc.description.abstract"/>
                            <property name="maxSize" value="250"/>
                            <property name="snippets" value="2"/>
                        </bean>
                        <!-- By default, full text snippets are disabled, as snippets of embargoed/restricted bitstreams
                         may appear in search results when the Item is public. See DS-3498
                        <bean class="org.dspace.discovery.configuration.DiscoveryHitHighlightFieldConfiguration">
                            <property name="field" value="fulltext"/>
                            <property name="maxSize" value="250"/>
                            <property name="snippets" value="2"/>
                        </bean>
                        -->
                    </list>
                </property>
            </bean>
        </property>
        <property name="moreLikeThisConfiguration">
            <bean class="org.dspace.discovery.configuration.DiscoveryMoreLikeThisConfiguration">
                <!--When altering this list also alter the "xmlui.Discovery.RelatedItems.help" key as it describes
            the metadata fields below-->
                <property name="similarityMetadataFields">
                    <list>
                        <value>dc.title</value>
                        <value>dc.contributor.author</value>
                        <value>dc.creator</value>
                        <value>dc.subject</value>
                    </list>
                </property>
                <!--The minimum number of matching terms across the metadata fields above before an item is found as related -->
                <property name="minTermFrequency" value="5"/>
                <!--The maximum number of related items displayed-->
                <property name="max" value="3"/>
                <!--The minimum word length below which words will be ignored-->
                <property name="minWordLength" value="5"/>
            </bean>
        </property>
        <!-- When true a "did you mean" example will be displayed, value can be true or false -->
        <property name="spellCheckEnabled" value="true"/>
    </bean>

Lastly, you should also update the search filters and sidebar facets in the homepageConfiguration bean if you want your new sidebar facets to appear in the home page. Don't forget to restart DSpace (stop and start Tomcat) and run dspace index-discovery -b every time you modified discovery.xml.


问:
How to add a user exception to "Require pull request reviews before merging" option in git protected branch?
I am trying to use lerna publish to manage package publishing in my team. So what lerna does at the end of every publish is, it bumps the version in the package.json file and commits those changes in the branch that did the publish.

However in master I need "Require pull request reviews before merging" to be active as it is protected branch.

My problem is not in publishing as lerna publishes the package. However the circle-ci fails with this error:

```<code>remote: error: GH006: Protected branch update failed for refs/heads/publish-test.
remote: error: At least 1 approving review is required by reviewers with write access.
To github.com:username/repo.git
 ! [remote rejected] publish-test -> publish-test (protected branch hook declined)
</code>```

I tried enabling "Restrict who can push to matching branches" option to allow a user to commit in master, (we are using a bot user for devops commits).

Is there a way to add a user exception to the option "Require pull request reviews before merging" or do a pre-merge hook(so I can publish before the merge in ci)?

答:
Update

GetHub enterprise now has the ability to create custom roles in which you can assign the permission to bypass branch policy.

The only way to excempt users is to make them repo admins and allow admins to bypass the policy.

Or use a GitHub actions workflow that uses the PAT if an admin to push to the target branch if the changes were pushed by allow-listed users. That opens up some interesting security issues though.

Body:
I am trying to use lerna publish to manage package publishing in my team. So what lerna does at the end of every publish is, it bumps the version in the package.json file and commits those changes in the branch that did the publish.

However in master I need "Require pull request reviews before merging" to be active as it is protected branch.

My problem is not in publishing as lerna publishes the package. However the circle-ci fails with this error:

remote: error: GH006: Protected branch update failed for refs/heads/publish-test.
remote: error: At least 1 approving review is required by reviewers with write access.
To github.com:username/repo.git
 ! [remote rejected] publish-test -> publish-test (protected branch hook declined)

I tried enabling "Restrict who can push to matching branches" option to allow a user to commit in master, (we are using a bot user for devops commits).

Is there a way to add a user exception to the option "Require pull request reviews before merging" or do a pre-merge hook(so I can publish before the merge in ci)?


问:
flutter how can i cast String to TextEditingController
hi i'm looking for a way to cast String variable into TextEditingController

```<code>  final TextEditingController _testController=TextEditingController();
</code>```

and this is what i'm doing

```<code>var test = "_"+"testController"
</code>```

and inside TextFormField Controller i'm calling controller like this

```<code>TextFormField(
controller: test,
),
</code>```

I know i could've just called it by the name of TextEditingController _testController but i have to do it this way, any ideas how ? i tried casting the variable to TextEditingController but i get this error saying that

```<code>type 'String' is not a subtype of type 'TextEditingController' in type cast
</code>```

答:
As you mentioned in the comments you have 28 TextEditingControllers.

You could get access to the right one by creating a Map.

```<code>var test = "_"+"testController"
final TextEditingController _testController=TextEditingController();
final TextEditingController _nameController=TextEditingController(); //Second controller

Map<String, TextEditingController> textMap = {'_testController': _testController, '_nameController': _nameController}; //Map declaration
</code>```

and then use it as:

```<code>    TextFormField(
     controller: textMap[test], //Access to the right controller by String Key
     ),
</code>```

Body:
hi i'm looking for a way to cast String variable into TextEditingController

  final TextEditingController _testController=TextEditingController();

and this is what i'm doing

var test = "_"+"testController"

and inside TextFormField Controller i'm calling controller like this

TextFormField(
controller: test,
),

I know i could've just called it by the name of TextEditingController _testController but i have to do it this way, any ideas how ? i tried casting the variable to TextEditingController but i get this error saying that

type 'String' is not a subtype of type 'TextEditingController' in type cast

Body:
As you mentioned in the comments you have 28 TextEditingControllers.

You could get access to the right one by creating a Map.

var test = "_"+"testController"
final TextEditingController _testController=TextEditingController();
final TextEditingController _nameController=TextEditingController(); //Second controller

Map<String, TextEditingController> textMap = {'_testController': _testController, '_nameController': _nameController}; //Map declaration

and then use it as:

    TextFormField(
     controller: textMap[test], //Access to the right controller by String Key
     ),


问:
sin function returning numbers outside of range [-1, 1]
I am working in Haskell and have had an error where, for really large floats z, sin(z) returns some value outside of the range [-1, 1].

I'm learning Haskell for the first time, so I have had very little luck debugging and the program just crashes when sin(z) does return a value outside of the above range as sin(z) is an input into another function that only accepts values inside the range [-1, 1].

Additionally, I don't have access to the other function, I only can send in a value, but it keeps crashing when sin(z) returns a number either greater than 1 or less than -1.

Is there any way to figure out why sin(z) is doing this?

答:
It seems like this is a floating point error; see this similar post. So for very large values, the sin function is returning a value slightly above 1, due to rounding errors.

To solve your problem, I would cap the return value at 1. Specifically, return the min 1 (sin z) instead of just the sin z directly.

Edit: replaced max with min.


问:
Using scriptAll is not grabbing all values in dropdown
I am dipping my toes into Karate UI so please bear with me if I am missing something obvious here.

I am trying to grab all values under a specific dropdown and then trying to write a JS script to randomly pick one of them to run my test.

The dropdown html looks like:

```<code><select class=id="CarId" name="CarId" aria-describedby="CarId-error" aria-invalid="false" xpath="1">
<option value="1">Mercedes</option>
<option value="2">BMW</option>
<option value="3">Lexus</option>
</select>
</code>```

After some research, I found I can use scriptAll to grab all values so I used:

```<code> * def getCars = scriptAll('#CarId', '_.textContent')
</code>```

However, I keep returning an empty array when I do a karate.log on the getCars variable. Any ideas?

答: I figured it out, I had to first add a click() action on the #CarId element. I am assuming one can also get around this by using Select().</p>

Body:
I am dipping my toes into Karate UI so please bear with me if I am missing something obvious here.

I am trying to grab all values under a specific dropdown and then trying to write a JS script to randomly pick one of them to run my test.

The dropdown html looks like:

<select class=id="CarId" name="CarId" aria-describedby="CarId-error" aria-invalid="false" xpath="1">
<option value="1">Mercedes</option>
<option value="2">BMW</option>
<option value="3">Lexus</option>
</select>

After some research, I found I can use scriptAll to grab all values so I used:

 * def getCars = scriptAll('#CarId', '_.textContent')

However, I keep returning an empty array when I do a karate.log on the getCars variable. Any ideas?


问:
Best practices on limiting memory usage of Elasticsearch for local development environment
I have a Ruby on Rails app for which I use Docker Compose to develop locally. I always use a copy of our production PostgreSQL database which is pretty large with around 500,000 rows. A lot of that data gets indexed for search in Elasticsearch using the Searchkick gem. I want to reproduce the production environment as closely as possible but I'm getting slowed down by the huge RAM usage of Elasticsearch on my laptop. I'm getting over 10GB of RAM usage often.

Has anyone thought of a solution for limiting the RAM usage of Elasticsearch just for local development?

Here are the Elasticsearch settings in my docker-compose.yml file:

```<code>  elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch:7.11.1
    environment:
      - "discovery.type=single-node"
      - "ELASTIC_USERNAME=elastic"
      - "ELASTIC_PASSWORD=DkIedPPSCb"
      - "xpack.security.enabled=true"
    ports: ['9200:9200', '9300:9300']
</code>```

答:
This is more of a docker config than elasticsearch.
If you are using v2 of docker-compose , set the following flag in docker compose

Ref: Mem and CPU V2

```<code>  elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch:7.11.1
    environment:
      - "discovery.type=single-node"
      - "ELASTIC_USERNAME=elastic"
      - "ELASTIC_PASSWORD=DkIedPPSCb"
      - "xpack.security.enabled=true"
    ports: ['9200:9200', '9300:9300']
    mem_limit: 1024m
</code>```

If its v3 , set memory config like so :

Ref: Mem and CPU V3

```<code>  elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch:7.11.1
    environment:
      - "discovery.type=single-node"
      - "ELASTIC_USERNAME=elastic"
      - "ELASTIC_PASSWORD=DkIedPPSCb"
      - "xpack.security.enabled=true"
    ports: ['9200:9200', '9300:9300']
    deploy:
      resources:
        limits:
          cpus: '0.50'
          memory: 50M
        reservations:
          cpus: '0.25'
          memory: 20M
</code>```

Body:
I have a Ruby on Rails app for which I use Docker Compose to develop locally. I always use a copy of our production PostgreSQL database which is pretty large with around 500,000 rows. A lot of that data gets indexed for search in Elasticsearch using the Searchkick gem. I want to reproduce the production environment as closely as possible but I'm getting slowed down by the huge RAM usage of Elasticsearch on my laptop. I'm getting over 10GB of RAM usage often.

Has anyone thought of a solution for limiting the RAM usage of Elasticsearch just for local development?

Here are the Elasticsearch settings in my docker-compose.yml file:

  elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch:7.11.1
    environment:
      - "discovery.type=single-node"
      - "ELASTIC_USERNAME=elastic"
      - "ELASTIC_PASSWORD=DkIedPPSCb"
      - "xpack.security.enabled=true"
    ports: ['9200:9200', '9300:9300']

Body:
This is more of a docker config than elasticsearch.
If you are using v2 of docker-compose , set the following flag in docker compose

Ref: Mem and CPU V2

  elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch:7.11.1
    environment:
      - "discovery.type=single-node"
      - "ELASTIC_USERNAME=elastic"
      - "ELASTIC_PASSWORD=DkIedPPSCb"
      - "xpack.security.enabled=true"
    ports: ['9200:9200', '9300:9300']
    mem_limit: 1024m

If its v3 , set memory config like so :

Ref: Mem and CPU V3

  elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch:7.11.1
    environment:
      - "discovery.type=single-node"
      - "ELASTIC_USERNAME=elastic"
      - "ELASTIC_PASSWORD=DkIedPPSCb"
      - "xpack.security.enabled=true"
    ports: ['9200:9200', '9300:9300']
    deploy:
      resources:
        limits:
          cpus: '0.50'
          memory: 50M
        reservations:
          cpus: '0.25'
          memory: 20M


问:
Need help creating a Regex
I need a regex to validate:

just numbers

it have to start with the number 20

the five number needs to be 0 or 1

the seven number needs to be 1, 2 or 3

答:
```<code>20\d{2}[01]\d{1}[123]
</code>```

Probably not very optimized, but it works :)

Title: Need help creating a Regex

Body:
20\d{2}[01]\d{1}[123]

Probably not very optimized, but it works :)


问:
ASP.NET Storing TimeSpan in EF Database
I am trying to store timespan objects in a EF Sql Database as:

```<code>public class Test
{
  [Required, Key]
  public int TestId { get; set; }
  public TimeSpan Time { get; set; }
}

modelBuilder.Entity<Test>().HasData(
                new Test {TestId = 1, Time = TimeSpan.FromDays(5)}
)
</code>```

But I get the error:

```<code>System.Data.SqlClient.SqlException (0x80131904): Conversion failed when converting date and/or time from character string.
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserState
Object stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite, String methodName)
   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary`2 paramete
rValues)
   at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues)
   at Microsoft.EntityFrameworkCore.Migrations.MigrationCommand.ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues)
   at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IEnumerable`1 migrationCommands, IRelationalConnection connection)
   at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_1.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
ClientConnectionId:b2ff74ea-6a41-49c5-9e24-fefe36619f40
Error Number:241,State:1,Class:16
Conversion failed when converting date and/or time from character string.
</code>```

How can I store them in a format SQL is happy with?

答:
Expanding on Tiago Silva's answer, it's worth mentioning the shorthand form in EF Core for default value conversions:

```<code>builder.Entity<Test>()
    .Property(s => s.Time)
    .HasConversion<long>();
</code>```

When the entity property is of type TimeSpan, that call will default to the built-in converter TimeSpanToTicksConverter.

Reference: https://learn.microsoft.com/en-us/ef/core/modeling/value-conversions?tabs=data-annotations#built-in-converters

Title: ASP.NET Storing TimeSpan in EF Database

Body:
I am trying to store timespan objects in a EF Sql Database as:

public class Test
{
  [Required, Key]
  public int TestId { get; set; }
  public TimeSpan Time { get; set; }
}

modelBuilder.Entity<Test>().HasData(
                new Test {TestId = 1, Time = TimeSpan.FromDays(5)}
)

But I get the error:

System.Data.SqlClient.SqlException (0x80131904): Conversion failed when converting date and/or time from character string.
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserState
Object stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite, String methodName)
   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary`2 paramete
rValues)
   at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues)
   at Microsoft.EntityFrameworkCore.Migrations.MigrationCommand.ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues)
   at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IEnumerable`1 migrationCommands, IRelationalConnection connection)
   at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_1.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
ClientConnectionId:b2ff74ea-6a41-49c5-9e24-fefe36619f40
Error Number:241,State:1,Class:16
Conversion failed when converting date and/or time from character string.

How can I store them in a format SQL is happy with?

Body:
Expanding on Tiago Silva's answer, it's worth mentioning the shorthand form in EF Core for default value conversions:

builder.Entity<Test>()
    .Property(s => s.Time)
    .HasConversion<long>();

When the entity property is of type TimeSpan, that call will default to the built-in converter TimeSpanToTicksConverter.

Reference: https://learn.microsoft.com/en-us/ef/core/modeling/value-conversions?tabs=data-annotations#built-in-converters


问:
What will be the BROKER_CLIENT_URL for Snyk broker setup for gitlab private instance
I am trying to setup Snyk broker for gitlab private instance and broker should run in docker container.
docker run --restart=always

-p 8000:8000

-e BROKER_TOKEN=secret-broker-token

-e GITLAB_TOKEN=secret-gitlab-token

-e GITLAB=your.gitlab.domain.com

-e BROKER_CLIENT_URL=http://my.broker.client:8000

-e PORT=8000

snyk/broker:gitlab

Here what will be the BROKER_CLIENT_URL

答: The BROKER_CLIENT_URL is important for webhooks, so it needs to be reachable from your Gitlab instance. It would generally be the IP address or FQDN of your Broker container.


问:
How to change reference highlight color in ssms 2017?
In ssms2017 text editor, when you click some words(variable/field/tablename..etc), others same words would highlight, but this color not enough HIGHLIGHT, I want change it, but i can't find out the item in Tool>options>font and color.

答:
What worked for me was using the Highlighted Reference option.  This helps when you're using tools like SQL Complete that like to highlight a lot.

Go to Tools -> Options -> Environment -> Fonts and Colors.
Under Display items select "Highlighted Reference" and change the item foreground and background options.


问:
How to get dash app plotly to display data by year
I'm new to dash and trying to get it to display a pie chart based on audit years that will display the amount of money 'Collected', 'Uncollected', 'Decreased', 'Written off'. Here's an example of what the pie charts look when i've coded them using plotly and not the dash feature.. So here is how it looks now via the dash app

Below is the code I used to make the dashboard

```<code>import pandas as pd
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.express as px

df1=pd.read_csv('Data 4.0.csv')

app=dash.Dash(__name__)

app.layout=html.Div([
    html.Div([
    html.Label(['Audit Yield']),
    dcc.Dropdown(
        id='my_dropdown',
        options=[
            {'label':'Year','value':'Yield Year'},
            {'label':'Status','value':'Status'},
            {'label':'Amount','value':'Amount'}
        ],
        value='Amount',
        multi=False,
        clearable=False,
        style={"width":"50%"}
    )
]),

html.Div([
    dcc.Graph(id='the_graph')
]),

])

@app.callback(
    Output(component_id='the_graph', component_property='figure'),
    [Input(component_id='my_dropdown', component_property='value')]

)

def update_graph(my_dropdown):
    dff=df1

    piechart=px.pie(
            data_frame=dff,
            names=my_dropdown,
            hole=.3,
            )
    return(piechart)

if __name__ == '__main__':
    app.run_server()
</code>```

So essentially I would like the dashboard to be called by year and show the amount collected for that year and where the money went. Just like how 7 pie charts show that data per year. Any help or direction would be greatly appreciated it.Thanks!

Here is a link to the dataset: Dataset for this code

答:
So if I understood correctly, you want to select the year in the dropdown menu and show the corresponding pie chart?

import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.express as px
from dash.dependencies import Input, Output

df1 = pd.read_csv('Data 4.0.csv')
years = df1['Yield Year'].unique()

app = dash.Dash(__name__)

app.layout = html.Div([
    html.Div([
        html.Label(['Audit Yield']),
        dcc.Dropdown(
            id='my_dropdown',
            options=[{'label': y, 'value': y} for y in years],
            value=years[0],
            multi=False,
            clearable=False,
            style={"width": "50%"}
        )
    ]),

    html.Div([
        dcc.Graph(id='the_graph')
    ]),

])

@app.callback(
    Output(component_id='the_graph', component_property='figure'),
    [Input(component_id='my_dropdown', component_property='value')]
)
def update_graph(year):
    piechart = px.pie(
        df1[df1['Yield Year'] == int(year)],
        values='Amount',
        names='Status',
        hole=.3,
    )
    return piechart

if __name__ == '__main__':
    app.run_server()
```

Output:

Body:
I'm new to dash and trying to get it to display a pie chart based on audit years that will display the amount of money 'Collected', 'Uncollected', 'Decreased', 'Written off'. Here's an example of what the pie charts look when i've coded them using plotly and not the dash feature.. So here is how it looks now via the dash app

Below is the code I used to make the dashboard

import pandas as pd
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.express as px

df1=pd.read_csv('Data 4.0.csv')

app=dash.Dash(__name__)

app.layout=html.Div([
    html.Div([
    html.Label(['Audit Yield']),
    dcc.Dropdown(
        id='my_dropdown',
        options=[
            {'label':'Year','value':'Yield Year'},
            {'label':'Status','value':'Status'},
            {'label':'Amount','value':'Amount'}
        ],
        value='Amount',
        multi=False,
        clearable=False,
        style={"width":"50%"}
    )
]),

html.Div([
    dcc.Graph(id='the_graph')
]),

])

@app.callback(
    Output(component_id='the_graph', component_property='figure'),
    [Input(component_id='my_dropdown', component_property='value')]

)

def update_graph(my_dropdown):
    dff=df1

    piechart=px.pie(
            data_frame=dff,
            names=my_dropdown,
            hole=.3,
            )
    return(piechart)

if __name__ == '__main__':
    app.run_server()

So essentially I would like the dashboard to be called by year and show the amount collected for that year and where the money went. Just like how 7 pie charts show that data per year. Any help or direction would be greatly appreciated it.Thanks!

Here is a link to the dataset: Dataset for this code

Body:
So if I understood correctly, you want to select the year in the dropdown menu and show the corresponding pie chart?

import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.express as px
from dash.dependencies import Input, Output

df1 = pd.read_csv('Data 4.0.csv')
years = df1['Yield Year'].unique()

app = dash.Dash(__name__)

app.layout = html.Div([
    html.Div([
        html.Label(['Audit Yield']),
        dcc.Dropdown(
            id='my_dropdown',
            options=[{'label': y, 'value': y} for y in years],
            value=years[0],
            multi=False,
            clearable=False,
            style={"width": "50%"}
        )
    ]),

    html.Div([
        dcc.Graph(id='the_graph')
    ]),

])

@app.callback(
    Output(component_id='the_graph', component_property='figure'),
    [Input(component_id='my_dropdown', component_property='value')]
)
def update_graph(year):
    piechart = px.pie(
        df1[df1['Yield Year'] == int(year)],
        values='Amount',
        names='Status',
        hole=.3,
    )
    return piechart

if __name__ == '__main__':
    app.run_server()

Output:


问:
CSS button hover effects not working with id's
I do not have any inline styling. I am sorry for any inconvenience as I am a self-learner and this is my first question.

Many thanks for your support.

#submit {
  background-color: yellow;
  font-weight: bold;
  font-size: 15px;
  border-width: medium;
}

#submit a:hover {
  background-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="form">
  <label for="email" id="email-label"></label><br>
  <input id="email" type="email" required name="Form-elements" placeholder="Enter your Email Address" /><br><br>

    <input type="submit" id="submit" value="Get Started"></code>```

答:
There are a few problems here:

You have put an <input> inside of an anchor ().  Please note that interactive elements are not permitted children of the anchor element.  You can imagine the issues if it were-- how would the browser determine which element you intended to interact with-- the anchor, or the button it contains?  If you want an anchor that looks like a button, you can simply use CSS to style it appropriately.  Malformed HTML can lead to strange, difficult to debug issues, so I suggest you resolve this.

Even with the malformed HTML, your styles are not written quite correctly to match as you have set here.  You have a  that contains an <input>, but the selector #submit a:hover reads as "target a hovered  that is inside of an element with id #submit".  So the rule is inverted from the actual case.  You could rewrite this a number of ways to make it match; here's one:

#submit {
  background-color: yellow;
  font-weight: bold;
  font-size: 15px;
  border-width: medium;
}

a:hover #submit {
  background-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="form">
  <label for="email" id="email-label"></label><br>
  <input id="email" type="email" required name="Form-elements" placeholder="Enter your Email Address" /><br><br>

    <input type="submit" id="submit" value="Get Started"></code>```

...however, I would recommend that you don't go with this solution alone, but instead clean up your HTML and start from a solid foundation.

Body:
I do not have any inline styling. I am sorry for any inconvenience as I am a self-learner and this is my first question.

Many thanks for your support.

#submit {
  background-color: yellow;
  font-weight: bold;
  font-size: 15px;
  border-width: medium;
}

#submit a:hover {
  background-color: red;
}

<form id="form">

  <input id="email" type="email" required name="Form-elements" placeholder="Enter your Email Address" />

    <input type="submit" id="submit" value="Get Started">

Body:
There are a few problems here:

You have put an <input> inside of an anchor (<a>).  Please note that interactive elements are not permitted children of the anchor element.  You can imagine the issues if it were-- how would the browser determine which element you intended to interact with-- the anchor, or the button it contains?  If you want an anchor that looks like a button, you can simply use CSS to style it appropriately.  Malformed HTML can lead to strange, difficult to debug issues, so I suggest you resolve this.

Even with the malformed HTML, your styles are not written quite correctly to match as you have set here.  You have a <a> that contains an <input>, but the selector #submit a:hover reads as "target a hovered <a> that is inside of an element with id #submit".  So the rule is inverted from the actual case.  You could rewrite this a number of ways to make it match; here's one:

#submit {
  background-color: yellow;
  font-weight: bold;
  font-size: 15px;
  border-width: medium;
}

a:hover #submit {
  background-color: red;
}

<form id="form">
  <label for="email" id="email-label"></label><br>
  <input id="email" type="email" required name="Form-elements" placeholder="Enter your Email Address" /><br><br>
  <a href="https://www.freecodecamp.org/email-submit">
    <input type="submit" id="submit" value="Get Started"></a>

...however, I would recommend that you don't go with this solution alone, but instead clean up your HTML and start from a solid foundation.


问:
How do I create dynamic column names in a WHILE DATE Loop query?
Here is my working query:

```<code>DECLARE @StartDate AS DATETIME
DECLARE @EndDate AS DATETIME
DECLARE @CurrentDate AS DATETIME

SET @StartDate = '2021-01-01'
SET @EndDate = GETDATE()
SET @CurrentDate = @StartDate

WHILE (@CurrentDate < @EndDate)
    BEGIN

        SELECT
        SUM(CASE WHEN [CreatedDateTime] BETWEEN @CurrentDate AND @CurrentDate + 6 THEN 1 ELSE 0 END)

        FROM Table
        WHERE OwnedBy = 'Service Desk'

        SET @CurrentDate = convert(varchar(30), dateadd(day,6, @CurrentDate), 101);

    END
</code>```

which produces the following result:

I'm trying to create a dynamic column name that shows the Date range for each result.

For example:

The 1st result should have the column name: "Jan 1-Jan 7"

The 2nd result should have the column name: "Jan 8-Jan 14"

etc.

Is there a way to do this?

Thanks.

答:
This is a very unusual way to approach this kind of database problem. You might instead consider using two columns, without loops, like this:

```<code>DECLARE @StartDate AS DATETIME = '20210101';
WITH e1(n) AS
(
    SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
    SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
    SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
)-- 10*1
,e2(n) AS (SELECT 1 FROM e1 CROSS JOIN e1 AS b) -- 10*10
,e3(n) AS (SELECT 1 FROM e1 CROSS JOIN e2) -- 10*100
,Dates as (
    SELECT DATEADD(d, ROW_NUMBER() over (ORDER BY n)-1, @StartDate) AS BaseDate
    FROM e3
)
SELECT d.BaseDate As PeriodStart -- datetime value
    , FORMAT(d.BaseDate, 'MMM dd')+ '-' + FORMAT(DATEADD(d, 6, d.BaseDate), 'MMM dd') as PeriodRange -- string value
    , COUNT(t.*) As TicketCount
FROM Dates d
INNER JOIN [Table] t ON t.[CreatedDateTime] >= d.BaseDate
    AND t.[CreatedDateTime] < DATEADD(d, 7, d.BaseDate)
    AND t.OwnedBy='Service Desk'
WHERE d.BaseDate < CURRENT_TIMESTAMP
GROUP BY d.BaseDate;
</code>```

This is likely to run many times faster, and will generally be easier to consume in client code and reporting tools.

One other notable change in here is instead of a BETWEEN expression for six days in the future, I used two separate conditions where the ending condition is an exclusive upper bound for seven days in the future, which is also generally the better way to handle date ranges.

Body:
Here is my working query:

DECLARE @StartDate AS DATETIME
DECLARE @EndDate AS DATETIME
DECLARE @CurrentDate AS DATETIME

SET @StartDate = '2021-01-01'
SET @EndDate = GETDATE()
SET @CurrentDate = @StartDate

WHILE (@CurrentDate < @EndDate)
    BEGIN

        SELECT
        SUM(CASE WHEN [CreatedDateTime] BETWEEN @CurrentDate AND @CurrentDate + 6 THEN 1 ELSE 0 END)

        FROM Table
        WHERE OwnedBy = 'Service Desk'

        SET @CurrentDate = convert(varchar(30), dateadd(day,6, @CurrentDate), 101);

    END

which produces the following result:

I'm trying to create a dynamic column name that shows the Date range for each result.

For example:

The 1st result should have the column name: "Jan 1-Jan 7"

The 2nd result should have the column name: "Jan 8-Jan 14"

etc.

Is there a way to do this?

Thanks.

Body:
This is a very unusual way to approach this kind of database problem. You might instead consider using two columns, without loops, like this:

DECLARE @StartDate AS DATETIME = '20210101';
WITH e1(n) AS
(
    SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
    SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
    SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
)-- 10*1
,e2(n) AS (SELECT 1 FROM e1 CROSS JOIN e1 AS b) -- 10*10
,e3(n) AS (SELECT 1 FROM e1 CROSS JOIN e2) -- 10*100
,Dates as (
    SELECT DATEADD(d, ROW_NUMBER() over (ORDER BY n)-1, @StartDate) AS BaseDate
    FROM e3
)
SELECT d.BaseDate As PeriodStart -- datetime value
    , FORMAT(d.BaseDate, 'MMM dd')+ '-' + FORMAT(DATEADD(d, 6, d.BaseDate), 'MMM dd') as PeriodRange -- string value
    , COUNT(t.*) As TicketCount
FROM Dates d
INNER JOIN [Table] t ON t.[CreatedDateTime] >= d.BaseDate
    AND t.[CreatedDateTime] < DATEADD(d, 7, d.BaseDate)
    AND t.OwnedBy='Service Desk'
WHERE d.BaseDate < CURRENT_TIMESTAMP
GROUP BY d.BaseDate;

This is likely to run many times faster, and will generally be easier to consume in client code and reporting tools.

One other notable change in here is instead of a BETWEEN expression for six days in the future, I used two separate conditions where the ending condition is an exclusive upper bound for seven days in the future, which is also generally the better way to handle date ranges.


问:
Matching files using python program
I have to two files as follows

```<code>File1
ids
CID5265
CID7263
CID9289
....

File 2
ids
CID7363  3.5e-06 -3837
CID5265  4.5      -938
CID9289  8.9      -9873
....
</code>```

I want  compare file1 with file2  to match any ids in file1 is present in file2 if yes  i should print whole line as follows

```<code>CIDS9289  8.9  -9873
....
</code>```

to acheive this wrote python script as follows

```<code>infile = open("file1","r")

searchtxt = open("file2.txt","r")

for line in infile.readlines():

    if searchtxt in line:

       print line
</code>```

but i gives following error

```<code>Traceback (most recent call last):
  File "finding_words.py", line 7, in <module>
    if searchtxt in line:
TypeError: 'in <string>' requires string as left operand, not file
</code>```

I know im doing very simple mistake but not able to figure it out can anybody tell how to solve this..

THanks in advance

NI

答: Your program fails because searchtxt is a file object, not a string. Presumably, you want to add another loop over that file object, checking for the text read from searchtxt in line.

Title: Matching files using python program

Body:
I have to two files as follows

File1
ids
CID5265
CID7263
CID9289
....

File 2
ids
CID7363  3.5e-06 -3837
CID5265  4.5      -938
CID9289  8.9      -9873
....

I want  compare file1 with file2  to match any ids in file1 is present in file2 if yes  i should print whole line as follows

CIDS9289  8.9  -9873
....

to acheive this wrote python script as follows

infile = open("file1","r")

searchtxt = open("file2.txt","r")

for line in infile.readlines():

    if searchtxt in line:

       print line

but i gives following error

Traceback (most recent call last):
  File "finding_words.py", line 7, in <module>
    if searchtxt in line:
TypeError: 'in <string>' requires string as left operand, not file

I know im doing very simple mistake but not able to figure it out can anybody tell how to solve this..

THanks in advance

NI


问:
How to read excel sheet with multiple Headers
how to read the data from excel worksheet using microsoft oldb providers in dotnet c# and i want read the data and save into db.

below is sample format for data reading in excel sheets.

thanks in adavance

答:
If you're allowed to use ClosedXml you can do something like this

```<code>private static IReadOnlyCollection<Planet> GetPlanets()
{
    // open the workbook
    var workbook = new XLWorkbook("Book1.xlsx");
    var sheet1 = workbook.Worksheet(1);
    var headers = sheet1.Row(1);
    var headersCount = headers.Cells().Count(cell => !cell.IsEmpty());

    var planets = new List<Planet>();

    // loop around each header
    for (int i = 2; i < headersCount + 3; i=i+2)
    {
        var name = headers.Cell(i).Value?.ToString();
        if (string.IsNullOrEmpty(name))
        {
            break;
        }
        var produced = new Produced(
            int.Parse(sheet1.Cell(3, i).Value?.ToString()),
            int.Parse(sheet1.Cell(4, i).Value?.ToString())
        );
        var sold = new Sold(
            int.Parse(sheet1.Cell(3, i + 1).Value?.ToString()),
            int.Parse(sheet1.Cell(4, i + 1).Value?.ToString())
        );
        planets.Add(new Planet(
            name,
            produced,
            sold
        ));
    }

    return planets;
}
</code>```

where

```<code>public sealed record Planet(string? Name, Produced Produced, Sold Sold);
public sealed record Produced(int TeddyBears, int BoardGames) : Metric(TeddyBears, BoardGames);
public sealed record Sold(int TeddyBears, int BoardGames) : Metric(TeddyBears, BoardGames);
public abstract record Metric(int TeddyBears, int BoardGames);
</code>```

This of course assumes the exact structure from your example, but its easy to configure it to do whatever you need

Body:
If you're allowed to use ClosedXml you can do something like this

private static IReadOnlyCollection<Planet> GetPlanets()
{
    // open the workbook
    var workbook = new XLWorkbook("Book1.xlsx");
    var sheet1 = workbook.Worksheet(1);
    var headers = sheet1.Row(1);
    var headersCount = headers.Cells().Count(cell => !cell.IsEmpty());

    var planets = new List<Planet>();

    // loop around each header
    for (int i = 2; i < headersCount + 3; i=i+2)
    {
        var name = headers.Cell(i).Value?.ToString();
        if (string.IsNullOrEmpty(name))
        {
            break;
        }
        var produced = new Produced(
            int.Parse(sheet1.Cell(3, i).Value?.ToString()),
            int.Parse(sheet1.Cell(4, i).Value?.ToString())
        );
        var sold = new Sold(
            int.Parse(sheet1.Cell(3, i + 1).Value?.ToString()),
            int.Parse(sheet1.Cell(4, i + 1).Value?.ToString())
        );
        planets.Add(new Planet(
            name,
            produced,
            sold
        ));
    }

    return planets;
}

where

public sealed record Planet(string? Name, Produced Produced, Sold Sold);
public sealed record Produced(int TeddyBears, int BoardGames) : Metric(TeddyBears, BoardGames);
public sealed record Sold(int TeddyBears, int BoardGames) : Metric(TeddyBears, BoardGames);
public abstract record Metric(int TeddyBears, int BoardGames);

This of course assumes the exact structure from your example, but its easy to configure it to do whatever you need


问:
Xamarin Forms ListView ItemTapped/ItemSelected Command Binding on XAML
How can I bind a ICommand object from my ViewModel (currently in BindingContext) to the ItemTapped or ItemSelected from a ListView in XAML?

This is a simple task when using a Button, I just set Command="MyViewModelCommand" and everything works.

答:
Here is the updated answer using the Xamarin community-toolkit

```<code><ContentPage
   xmlns="http://xamarin.com/schemas/2014/forms"
   xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
   xmlns:xct="http://xamarin.com/schemas/2020/toolkit"
   >

<ListView  .... >
<ListView.Behaviors>
    <xct:EventToCommandBehavior
        EventName="ItemSelected"
        Command="{Binding MyCustomCommand}" />
</ListView.Behaviors>

</ListView >
</code>```

Ref
https://learn.microsoft.com/en-us/xamarin/community-toolkit/behaviors/eventtocommandbehavior

Body:
Here is the updated answer using the Xamarin community-toolkit

<ContentPage
   xmlns="http://xamarin.com/schemas/2014/forms"
   xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
   xmlns:xct="http://xamarin.com/schemas/2020/toolkit"
   >

<ListView  .... >
<ListView.Behaviors>
    <xct:EventToCommandBehavior
        EventName="ItemSelected"
        Command="{Binding MyCustomCommand}" />
</ListView.Behaviors>

</ListView >

Ref
https://learn.microsoft.com/en-us/xamarin/community-toolkit/behaviors/eventtocommandbehavior


问:
Snowflake SQL stored procedure and save value from query to variable
I am writing a SQL stored procedure in Snowflake (language SQL NOT Javascript). I pass in a database name and I have a cursor to get all schemas for that database. I loop through them one by one and am creating a new role and then doing a bunch of other things related to granting permissions. If the role already exists I want to skip that schema and continue on to the next schema.

I am having a hard time determining if the role exists. FYI, I am doing CREATE ROLE IF NOT EXISTS name_of_schema...  However, I do not want to continue on to the rest of the code if the role exists because some of the code will fail such as granting future grants.

As far as I can tell, there isn't a way to do something like IF EXISTS ROLE name of role...

I could query the snowflake.account_usage.roles view but that can be delayed 2 hours and the role could have been created in less time but if that is my only option I would have to live with it.  I think I could use the result_scan function...something like this and the status would contain the words " already exists, statement succeeded."

```<code>CREATE ROLE IF NOT EXISTS  <role name>;
query := 'SELECT status FROM table(result_scan(last_query_id()));';
</code>```

However, I don't know how to get the value of status into a variable where I can then check to see if it is LIKE '%already exists%'.

Can anyone provide guidance or give me an example?  I think I could probably put this in a cursor and then loop to accomplish this.  That seems like a lot of code to retrieve a value.  It seems like I should be able to capture a value from a query into a variable when only one row would be returned.

Thanks in advance for any help!

答:
According to this example, you can use Snowflake Scripting within a SQL procedure.

And Snowflake scripting can use conditionals

So you would have something like this. I used a table creation instead, but it's the exact same idea:

create or replace procedure myprocedure()
  returns int
  language sql
  as
  $$
    DECLARE
        status string;
    BEGIN
        CREATE TABLE IF NOT EXISTS TEST(i int);
        status := (SELECT "status" FROM table(result_scan(last_query_id())));

        IF (status LIKE '%already exists%') THEN
            RETURN 1;
        ELSE
            RETURN 2;
        END IF;
    END;
$$;
```

sidenote: the $$ are needed in the classic web interface, but you may not need them.

Body:
I am writing a SQL stored procedure in Snowflake (language SQL NOT Javascript). I pass in a database name and I have a cursor to get all schemas for that database. I loop through them one by one and am creating a new role and then doing a bunch of other things related to granting permissions. If the role already exists I want to skip that schema and continue on to the next schema.

I am having a hard time determining if the role exists. FYI, I am doing CREATE ROLE IF NOT EXISTS name_of_schema...  However, I do not want to continue on to the rest of the code if the role exists because some of the code will fail such as granting future grants.

As far as I can tell, there isn't a way to do something like IF EXISTS ROLE name of role...

I could query the snowflake.account_usage.roles view but that can be delayed 2 hours and the role could have been created in less time but if that is my only option I would have to live with it.  I think I could use the result_scan function...something like this and the status would contain the words " already exists, statement succeeded."

CREATE ROLE IF NOT EXISTS  <role name>;
query := 'SELECT status FROM table(result_scan(last_query_id()));';

However, I don't know how to get the value of status into a variable where I can then check to see if it is LIKE '%already exists%'.

Can anyone provide guidance or give me an example?  I think I could probably put this in a cursor and then loop to accomplish this.  That seems like a lot of code to retrieve a value.  It seems like I should be able to capture a value from a query into a variable when only one row would be returned.

Thanks in advance for any help!

Body:
According to this example, you can use Snowflake Scripting within a SQL procedure.

And Snowflake scripting can use conditionals

So you would have something like this. I used a table creation instead, but it's the exact same idea:

create or replace procedure myprocedure()
  returns int
  language sql
  as
  $$
    DECLARE
        status string;
    BEGIN
        CREATE TABLE IF NOT EXISTS TEST(i int);
        status := (SELECT "status" FROM table(result_scan(last_query_id())));

        IF (status LIKE '%already exists%') THEN
            RETURN 1;
        ELSE
            RETURN 2;
        END IF;
    END;
$$;

sidenote: the $$ are needed in the classic web interface, but you may not need them.


答:
```<code>20\d{2}(0|1)\d[1-3]
</code>```

I think this will work

Title: Need help creating a Regex

Body:
I need a regex to validate:

just numbers

it have to start with the number 20

the five number needs to be 0 or 1

the seven number needs to be 1, 2 or 3

Body:
20\d{2}(0|1)\d[1-3]

I think this will work


问:
Way to overcome Excel Vlookup function limit of 256 characters
I have a excel array with multiple values. Some are less than 256 characters and some have a length greater than 256.

When I tried to do a VLookup using a sample string, I can get results when it matches the rows with less than 256 characters. For rows greater that 256 characters, it returns a '#N/A'.

Is there a way of using Vlookup or by using some other in-built function in Excel that I can overcome this limit?

答: XLookup no longer has such limitation. I was able to Lookup > 500 Characters with it.</p>


问:
How to change font size in Material Design TabLayout android?
I have been trying to explore online to set my font size for TabLayout TabItems
But none of them seems to be working for me. This is what I tried referring last link

below are the things which I have implemented so far,
Not sure why it's not picking textSize from style.

in xml:

```<code><com.google.android.material.tabs.TabLayout
                android:id="@+id/tabLayoutForgot"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="@dimen/header_height"
                app:layout_constraintTop_toBottomOf="@+id/imageViewLogo"
                app:tabIndicatorColor="@color/text_color"
                app:tabSelectedTextColor="@color/text_color"
                app:tabGravity="fill"
                app:tabTextAppearance="@style/MyCustomTabLayout"
                app:tabMode="fixed"
                app:tabIndicatorFullWidth="false"
                app:tabTextColor="@color/text_color" />
</code>```

in themes.xml:

```<code><style name="MyCustomTabLayout" parent="@android:style/TextAppearance.Widget.TabWidget">
        <item name="textAllCaps">false</item>
        <item name="android:textSize">20sp</item>
        <item name="android:fontFamily">@font/roboto_medium</item>
        <item name="android:textColor">@color/text_color</item>
    </style>
</code>```

this does everything else like textAllCaps and fontFamily but doesn't seems to take textSize.

Appreciate any help.

答:
Well, I was able to find a solution to my issue.

Adding the below line of code in dimens.xml somehow made it work for me.

<dimen name="design_tab_text_size_2line" tools:override="true">20sp</dimen>

Body:
I have been trying to explore online to set my font size for TabLayout TabItems
But none of them seems to be working for me. This is what I tried referring last link

below are the things which I have implemented so far,
Not sure why it's not picking textSize from style.

in xml:

<com.google.android.material.tabs.TabLayout
                android:id="@+id/tabLayoutForgot"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="@dimen/header_height"
                app:layout_constraintTop_toBottomOf="@+id/imageViewLogo"
                app:tabIndicatorColor="@color/text_color"
                app:tabSelectedTextColor="@color/text_color"
                app:tabGravity="fill"
                app:tabTextAppearance="@style/MyCustomTabLayout"
                app:tabMode="fixed"
                app:tabIndicatorFullWidth="false"
                app:tabTextColor="@color/text_color" />

in themes.xml:

this does everything else like textAllCaps and fontFamily but doesn't seems to take textSize.

Appreciate any help.


问:
How to copy files containing the given character using terminal in Linux Mint?
In Linux Mint, I have a directory that has many files and I want to copy files that contain x in their filename and paste them into other destination.

How can I do it using a terminal?

答:
Go to the directory that contains all of your files, then try this one. this commnad can help you.

```<code>find . -name '*x*' -exec cp "{}" YourDestination  \;
</code>```

replace YourDestination wtih every where you want.

Body:
Go to the directory that contains all of your files, then try this one. this commnad can help you.

find . -name '*x*' -exec cp "{}" YourDestination  \;

replace YourDestination wtih every where you want.


问:
How can I change the color of scroll ion-content?
I am looking for a way to change the color of this scroll to green color, which belongs to ion-content, in Ionic. Do you know how I can do it?

Here is mi HTML

```<code>    <ion-header>
  <ion-toolbar>
    <ion-buttons slot="start">
      <ion-back-button id="h" defaultHref="home" ></ion-back-button>
    </ion-buttons>
    <ion-title>Validación de apartado 1º...</ion-title>
    <ion-icon slot="end" name="search-outline"></ion-icon>
  </ion-toolbar>
  <ion-text>Realizadas 74 de 200</ion-text>
</ion-header>

<ion-content >
  <ion-progress-bar value="0.37"></ion-progress-bar>
  <ion-list lines="full">
    <ion-item *ngFor="let item of items; let i = index">
      <ion-label>{{item + " - index: " + i}}</ion-label>
    </ion-item>
  </ion-list>
</ion-content>
</code>```

答:
Try the directive below it's based off the package https://www.npmjs.com/package/ion-custom-scrollbar but just grabbed the directive instead</p>
```<code>import { Directive, ElementRef, Input, OnInit } from '@angular/core';

@Directive({
    selector: '[scrollbar]'
})
export class ScrollbarDirective implements OnInit {

    @Input() scrollbar: string
    @Input() allowAllScreens: boolean | string

    hostElement: HTMLElement

    constructor(public elementRef: ElementRef) { }

    ngOnInit() {
        this.hostElement = this.elementRef.nativeElement
        if (this.hostElement && this.hostElement.tagName && this.hostElement.tagName == 'ION-CONTENT') {
            let el = document.createElement('style')
            el.innerText = this.scrollbar || this.getCustomStyle()
            this.hostElement.shadowRoot.appendChild(el)
        }
    }

    getCustomStyle() {
        if (this.allowAllScreens === true || this.allowAllScreens === 'true') {
            return `::-webkit-scrollbar {
           width: 1rem !important;
        }
        ::-webkit-scrollbar-track {
          background: #23232e;
        }
        ::-webkit-scrollbar-thumb {
           background: #df49a6;
        }
        ::-webkit-scrollbar-thumb:hover {
          background: #ff7eef;
        }
        // ::-webkit-scrollbar-track:hover {
        //   background: #f7f7f7;
        // }

        // .inner-scroll {
        //   scrollbar-width: thin
        // }
        `
        } else {
            return `@media(pointer: fine) {
        ::-webkit-scrollbar {
           width: 1rem !important;
        }
        ::-webkit-scrollbar-track {
          background: #23232e;
        }
        ::-webkit-scrollbar-thumb {
           background: #df49a6;
        }
        ::-webkit-scrollbar-thumb:hover {
          background: #ff7eef;
        }
        // ::-webkit-scrollbar-track:hover {
        //   background: #f7f7f7;
        // }
        // .inner-scroll {
        //   scrollbar-width: thin
        // }
      }`
        }
    }

}
</code>```

Body:
I am looking for a way to change the color of this scroll to green color, which belongs to ion-content, in Ionic. Do you know how I can do it?

Here is mi HTML

    <ion-header>
  <ion-toolbar>
    <ion-buttons slot="start">
      <ion-back-button id="h" defaultHref="home" ></ion-back-button>
    </ion-buttons>
    <ion-title>Validación de apartado 1º...</ion-title>
    <ion-icon slot="end" name="search-outline"></ion-icon>
  </ion-toolbar>
  <ion-text>Realizadas 74 de 200</ion-text>
</ion-header>

<ion-content >
  <ion-progress-bar value="0.37"></ion-progress-bar>
  <ion-list lines="full">
    <ion-item *ngFor="let item of items; let i = index">
      <ion-label>{{item + " - index: " + i}}</ion-label>
    </ion-item>
  </ion-list>
</ion-content>

Body:
Try the directive below it's based off the package https://www.npmjs.com/package/ion-custom-scrollbar but just grabbed the directive instead

import { Directive, ElementRef, Input, OnInit } from '@angular/core';

@Directive({
    selector: '[scrollbar]'
})
export class ScrollbarDirective implements OnInit {

    @Input() scrollbar: string
    @Input() allowAllScreens: boolean | string

    hostElement: HTMLElement

    constructor(public elementRef: ElementRef) { }

    ngOnInit() {
        this.hostElement = this.elementRef.nativeElement
        if (this.hostElement && this.hostElement.tagName && this.hostElement.tagName == 'ION-CONTENT') {
            let el = document.createElement('style')
            el.innerText = this.scrollbar || this.getCustomStyle()
            this.hostElement.shadowRoot.appendChild(el)
        }
    }

    getCustomStyle() {
        if (this.allowAllScreens === true || this.allowAllScreens === 'true') {
            return `::-webkit-scrollbar {
           width: 1rem !important;
        }
        ::-webkit-scrollbar-track {
          background: #23232e;
        }
        ::-webkit-scrollbar-thumb {
           background: #df49a6;
        }
        ::-webkit-scrollbar-thumb:hover {
          background: #ff7eef;
        }
        // ::-webkit-scrollbar-track:hover {
        //   background: #f7f7f7;
        // }

        // .inner-scroll {
        //   scrollbar-width: thin
        // }
        `
        } else {
            return `@media(pointer: fine) {
        ::-webkit-scrollbar {
           width: 1rem !important;
        }
        ::-webkit-scrollbar-track {
          background: #23232e;
        }
        ::-webkit-scrollbar-thumb {
           background: #df49a6;
        }
        ::-webkit-scrollbar-thumb:hover {
          background: #ff7eef;
        }
        // ::-webkit-scrollbar-track:hover {
        //   background: #f7f7f7;
        // }
        // .inner-scroll {
        //   scrollbar-width: thin
        // }
      }`
        }
    }

}


问:
How to dynamiclly bind to a property path of an Object?
i have the following ItemsControl defined, i want to bind the Content of a Button to a object Property path, which will be provided as a string through a method. The Items are generic. How can i achieve this ? because i can't set DisplayMemberPath and bind it to the ItemTemplate. (i cant't set both DisplayMemberPath and ItemTemplate)

```<code><ScrollViewer Grid.Row="2"
                  Grid.Column="1"
                  Margin="5 3"
                  HorizontalScrollBarVisibility="Disabled"
                  VerticalScrollBarVisibility="Auto">
        <ItemsControl ItemsSource="{Binding Items}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Button Command="{x:Static materialDesign:DialogHost.CloseDialogCommand}"
                            Style="{DynamicResource MaterialDesignFlatButton}"
                            Margin="2"
                            CommandParameter="{Binding}">
                        <Button.Content>
                            <TextBlock Text="{Binding}" />
                        </Button.Content>
                    </Button>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </ScrollViewer>
</code>```

ViewModel:

```<code>public class SelectionViewModel<T> : DialogViewModelBase, IDialogViewModel
{
    // Fields
    private string _title;
    private bool _showTitleSeparator;
    private string _displayMemberPath;
    private IEnumerable<T> _items;

    // Properties
    public string Title
    {
        get { return _title; }
        set { _title = value; Notify(); }
    }
    public IEnumerable<T> Items
    {
        get { return _items; }
        set { _items = value; Notify(); }
    }
    // Member Path to bind to
    public string DisplayMemberPath
    {
        get { return _displayMemberPath; }
        set { _displayMemberPath = value; Notify(); }
    }
}
</code>```

if i remove the ItemTemplate and simply bind the DisplayMemberPath of the ItemsControl to the Property in my ViewModel it works fine.

答:
I was able to do this using a converter and reflection.</p>
```<code>        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (values.Contains(DependencyProperty.UnsetValue))
            { return null; }

            object source = values[0];
            string path = (string)values[1];

            Type sourceType = source.GetType();
            System.Reflection.PropertyInfo propertyInfo = sourceType.GetProperty(path);
            return propertyInfo.GetValue(source, null);
        }
</code>```

Body:
i have the following ItemsControl defined, i want to bind the Content of a Button to a object Property path, which will be provided as a string through a method. The Items are generic. How can i achieve this ? because i can't set DisplayMemberPath and bind it to the ItemTemplate. (i cant't set both DisplayMemberPath and ItemTemplate)

<ScrollViewer Grid.Row="2"
                  Grid.Column="1"
                  Margin="5 3"
                  HorizontalScrollBarVisibility="Disabled"
                  VerticalScrollBarVisibility="Auto">
        <ItemsControl ItemsSource="{Binding Items}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Button Command="{x:Static materialDesign:DialogHost.CloseDialogCommand}"
                            Style="{DynamicResource MaterialDesignFlatButton}"
                            Margin="2"
                            CommandParameter="{Binding}">
                        <Button.Content>
                            <TextBlock Text="{Binding}" />
                        </Button.Content>
                    </Button>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </ScrollViewer>

ViewModel:

public class SelectionViewModel<T> : DialogViewModelBase, IDialogViewModel
{
    // Fields
    private string _title;
    private bool _showTitleSeparator;
    private string _displayMemberPath;
    private IEnumerable<T> _items;

    // Properties
    public string Title
    {
        get { return _title; }
        set { _title = value; Notify(); }
    }
    public IEnumerable<T> Items
    {
        get { return _items; }
        set { _items = value; Notify(); }
    }
    // Member Path to bind to
    public string DisplayMemberPath
    {
        get { return _displayMemberPath; }
        set { _displayMemberPath = value; Notify(); }
    }
}

if i remove the ItemTemplate and simply bind the DisplayMemberPath of the ItemsControl to the Property in my ViewModel it works fine.

Body:
I was able to do this using a converter and reflection.

        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (values.Contains(DependencyProperty.UnsetValue))
            { return null; }

            object source = values[0];
            string path = (string)values[1];

            Type sourceType = source.GetType();
            System.Reflection.PropertyInfo propertyInfo = sourceType.GetProperty(path);
            return propertyInfo.GetValue(source, null);
        }


问:
AttributeError("module 'apache_beam.io.gcp.internal.clients.storage' has no attribute 'StorageV1'")
I get this error while trying to use the library apache_beam.io.gcp.gcsfilesystem. I want to use the function copy().

I tried a simple example:

```<code>from apache_beam.io.gcp.gcsfilesystem import GCSFileSystem
GCSFileSystem(pipeline_options = None).copy(source_file_names = image_urls, destination_file_names = destination_urls)
</code>```

Is it possible that the problem is due to passing no pipeline options? or what library could be missing, since every else using apache beam, and GCP APIs are working fine.

答:
Looking at

https://github.com/apache/beam/blob/master/sdks/python/apache_beam/io/gcp/internal/clients/storage/__init__.py

it could be because you don't have apitools installed. Did you install apache_beam[grpc]?

Body:
I get this error while trying to use the library apache_beam.io.gcp.gcsfilesystem. I want to use the function copy().

I tried a simple example:

from apache_beam.io.gcp.gcsfilesystem import GCSFileSystem
GCSFileSystem(pipeline_options = None).copy(source_file_names = image_urls, destination_file_names = destination_urls)

Is it possible that the problem is due to passing no pipeline options? or what library could be missing, since every else using apache beam, and GCP APIs are working fine.


问:
How to output logs in a containerized application?
Normally, in docker/k8s, it's recommended that directly ouput the logs to the stdout.

Then we can use kubectl logs or docker logs to see the logs.

like: time=123 action=write msg=hello world , as a tty, it might be colorized for human friendliness.

However, if we want to export the logs to a log processing center, like EFK (elasticsearch-fluentd-kibana), we need a json-format log file.

like: {"time"=123,"action"="write","msg"="hello world"}

What I want?

Is there a log method that can take into account both human friendliness and json format?

I'm looking for a way that if I use docker logs, then I can get human-readable logs, and at the same time, the log collector can still get the logs in json-format

Conclusion

Thanks for the answer below. I have got 2 methods:

different log format in different env:

1.1 use text-format in developing: docker logs will print colorized and human readable logs.

1.2 use json-format in production: EFK can process json-format well.

log collector's format convertion
2.1 we use text-format, but in log collector like fluentd we can define some scripts to translate text-format kv pair to json-format kv pair.

答:
Kubernetes has such option of structured logging for its system components.
Klog library  allows to use   --logging-format=json flag that enables to change the format of logs to JSON output - more information about it here and here.


问:
How can I mock requests and the response?
I am trying to use Pythons mock package to mock Pythons requests module. What are the basic calls to get me working in below scenario?

In my views.py, I have a function that makes variety of requests.get() calls with different response each time

```<code>def myview(request):
  res1 = requests.get('aurl')
  res2 = request.get('burl')
  res3 = request.get('curl')
</code>```

In my test class I want to do something like this but cannot figure out exact method calls

Step 1:

```<code># Mock the requests module
# when mockedRequests.get('aurl') is called then return 'a response'
# when mockedRequests.get('burl') is called then return 'b response'
# when mockedRequests.get('curl') is called then return 'c response'
</code>```

Step 2:

Call my view

Step 3:

verify response contains 'a response', 'b response' , 'c response'

How can I complete Step 1 (mocking the requests module)?

答:
For those, who don't want to install additional libs for pytest, there is an example. I will duplicate it here with some extension, based on examples above:

```<code>import datetime

import requests

class MockResponse:
    def __init__(self, json_data, status_code):
        self.json_data = json_data
        self.status_code = status_code
        self.elapsed = datetime.timedelta(seconds=1)

    # mock json() method always returns a specific testing dictionary
    def json(self):
        return self.json_data

def test_get_json(monkeypatch):
    # Any arguments may be passed and mock_get() will always return our
    # mocked object, which only has the .json() method.
    def mock_get(*args, **kwargs):
        return MockResponse({'mock_key': 'mock_value'}, 418)

    # apply the monkeypatch for requests.get to mock_get
    monkeypatch.setattr(requests, 'get', mock_get)

    # app.get_json, which contains requests.get, uses the monkeypatch
    response = requests.get('https://fakeurl')
    response_json = response.json()

    assert response_json['mock_key'] == 'mock_value'
    assert response.status_code == 418
    assert response.elapsed.total_seconds() == 1

============================= test session starts ==============================
collecting ... collected 1 item

test_so.py::test_get_json PASSED                                          [100%]

============================== 1 passed in 0.07s ===============================
</code>```

Body:
I am trying to use Pythons mock package to mock Pythons requests module. What are the basic calls to get me working in below scenario?

In my views.py, I have a function that makes variety of requests.get() calls with different response each time

def myview(request):
  res1 = requests.get('aurl')
  res2 = request.get('burl')
  res3 = request.get('curl')

In my test class I want to do something like this but cannot figure out exact method calls

Step 1:

# Mock the requests module
# when mockedRequests.get('aurl') is called then return 'a response'
# when mockedRequests.get('burl') is called then return 'b response'
# when mockedRequests.get('curl') is called then return 'c response'

Step 2:

Call my view

Step 3:

verify response contains 'a response', 'b response' , 'c response'

How can I complete Step 1 (mocking the requests module)?

Body:
For those, who don't want to install additional libs for pytest, there is an example. I will duplicate it here with some extension, based on examples above:

import datetime

import requests

class MockResponse:
    def __init__(self, json_data, status_code):
        self.json_data = json_data
        self.status_code = status_code
        self.elapsed = datetime.timedelta(seconds=1)

    # mock json() method always returns a specific testing dictionary
    def json(self):
        return self.json_data

def test_get_json(monkeypatch):
    # Any arguments may be passed and mock_get() will always return our
    # mocked object, which only has the .json() method.
    def mock_get(*args, **kwargs):
        return MockResponse({'mock_key': 'mock_value'}, 418)

    # apply the monkeypatch for requests.get to mock_get
    monkeypatch.setattr(requests, 'get', mock_get)

    # app.get_json, which contains requests.get, uses the monkeypatch
    response = requests.get('https://fakeurl')
    response_json = response.json()

    assert response_json['mock_key'] == 'mock_value'
    assert response.status_code == 418
    assert response.elapsed.total_seconds() == 1

============================= test session starts ==============================
collecting ... collected 1 item

test_so.py::test_get_json PASSED                                          [100%]

============================== 1 passed in 0.07s ===============================