问:
Unable to Successfully Split HTML-Like Strings with Python RE Using Lookarounds
```<code>'''
Trying to split string 'text' below so that all segments are found and split.
There are three flavors of segments:
    A:    <tag attr1="one" attr2>some text</tag>
    B:    <tag attr1="one" attr2 text="some text"/>
    C:    some tagless text
I can't use an HTML parser, because C segments are in plain English.

I would like to be able to accept '/' as part of the text.
So, '/' is just a char unless it precedes '>' or comes before 'tag'.
In a perfect world, I would also like to accept '<' and '>', too.
So '<' is just a char unless it precedes 't' or '/'.

Currently I use patt[1] to split text with A and C segments, but now I want to be
able to split strings with B segments, too. Also, patt[1] does not allow '/' to be
passed in as a regular char without breaking the routine. Although it seems
to work, I don't like that the regexp limits matching according to '/'.

The goal is to properly split the text string into the expected output strings. Can someone
tell me what I'm doing wrong?  Running the regexp on https://pythex.org/ looks okay, but it
still doesn't run properly under CPython 3.6 - 3.9.
'''
import pprint, re, sys, unittest

class TestClass(unittest.TestCase):

    sub = False # True #
    patt = {}
    patt[1] = r'(<t(?:ag)?\s*[^>]*>[^>]*</t(?:ag)?>)' # orig, works for A and C but not B

    patt[2] = r'(<t(?:ag)?.*?(?:/t(?:ag)?>|/>))' # misses one
    #           1  2    2    3    4    4     31
    patt[3] = r'(<t(?:ag)?[^/]*/t?>)' # misses one
    #           1  2    2          1
    patt[4] = r'(<t(?:ag)?.*?(?<=/)(?:t(?:ag)?)?>)' # with lookarounds. still misses one.
    patt[5] = r'(<t(?:ag)?(?!/>)(?!/t).*?(?<=/)(?:t(?:ag)?)?>)' # with lookarounds. tried adding negs
    patt[6] = r'(<t(?:ag)?.*?(?!/>)(?!/t)(?<=/)(?:t(?:ag)?)?>)'

    text = "start: <t s=10 B=1>Size 10 bold</t><t siz=6>Size 6\nNew Line </t>" \
           "<t u w=bold>Underlined and Bolded\n</t><t it>Italics</t><t>default</t>" \
           '<t fam="Courier New" siz=18>Courier 18</t>' \
           "<t bitmap=question/><t bitmap=info/> and <t fg=red>red/and/yellow</t>" \
           "<t fg=red>lesser < or greater > or both <></t><t>bye</t>"

    if sub:
        text = re.sub(r"/>", "></t>", text)
    expected_output = ['start: ', '<t s=10 B=1>Size 10 bold</t>', '<t siz=6>Size 6\nNew Line </t>',
         '<t u w=bold>Underlined and Bolded\n</t>', '<t it>Italics</t>', '<t>default</t>',
         '<t fam="Courier New" siz=18>Courier 18</t>',
         '<t bitmap=question/>', '<t bitmap=info/>', ' and ', '<t fg=red>red/and/yellow</t>',
         "<t fg=red>lesser < or greater > or both <></t>", '<t>bye</t>', ]
    if sub:
        expected_output = expected_output[:7] + ['<t bitmap=question></t>', '<t bitmap=info></t>'] + expected_output[9:]
    exp_len = len(expected_output)

    def test_patt1(self, i=1):
        fields = [f for f in re.split(TestClass.patt[i], TestClass.text) if f]
        print(f'\nPATT[{i}] {TestClass.patt[i]!r} gives {len(fields)} of the {TestClass.exp_len} expected fields:')
        print(pprint.pformat(fields), '\n\n')
        self.assertEqual(fields, TestClass.expected_output)

    def test_patt2(self, i=2):
        fields = [f for f in re.split(TestClass.patt[i], TestClass.text) if f]
        print(f'\nPATT[{i}] {TestClass.patt[i]!r} gives {len(fields)} of the {TestClass.exp_len} expected fields:')
        print(pprint.pformat(fields), '\n\n')
        self.assertEqual(fields, TestClass.expected_output)

    def test_patt3(self, i=3):
        fields = [f for f in re.split(TestClass.patt[i], TestClass.text) if f]
        print(f'\nPATT[{i}] {TestClass.patt[i]!r} gives {len(fields)} of the {TestClass.exp_len} expected fields:')
        print(pprint.pformat(fields), '\n\n')
        self.assertEqual(fields, TestClass.expected_output)

    def test_patt4(self, i=4):
        fields = [f for f in re.split(TestClass.patt[i], TestClass.text) if f]
        print(f'\nPATT[{i}] {TestClass.patt[i]!r} gives {len(fields)} of the {TestClass.exp_len} expected fields:')
        print(pprint.pformat(fields), '\n\n')
        self.assertEqual(fields, TestClass.expected_output)

    def test_patt5(self, i=5):
        fields = [f for f in re.split(TestClass.patt[i], TestClass.text) if f]
        print(f'\nPATT[{i}] {TestClass.patt[i]!r} gives {len(fields)} of the {TestClass.exp_len} expected fields:')
        print(pprint.pformat(fields), '\n\n')
        self.assertEqual(fields, TestClass.expected_output)

    def test_patt6(self, i=6):
        fields = [f for f in re.split(TestClass.patt[i], TestClass.text) if f]
        print(f'\nPATT[{i}] {TestClass.patt[i]!r} gives {len(fields)} of the {TestClass.exp_len} expected fields:')
        print(pprint.pformat(fields), '\n\n')
        self.assertEqual(fields, TestClass.expected_output)

if __name__ == '__main__':
    unittest.main()
</code>```

答: I think you should use Python Beautifulsoup module.


来源: stackexchange

问:
Error connecting to server localhost on port 1,527 when I have provided another port, 5432 in my persistence xml
In Java EE, I have a persistence.xml provided and is packaged correctly.

```<code><?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
             version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
    <persistence-unit name="ArticleManagement">
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <class>com.pauljabines.portfolio.Article</class>
        <properties>
            <property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/postgres" />
            <property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver" />
            <property name="javax.persistence.jdbc.user" value="postgres" />
            <property name="javax.persistence.jdbc.password" value="************************" />
            <property name="eclipselink.logging.level" value="ALL" />
        </properties>
    </persistence-unit>
</persistence>
</code>```

Question: With these connection properties, why is glassfish throwing error and saying that it can't connect to port 1527?

Here is a bit of the stacktrace:

```<code>org.glassfish.deployment.common.DeploymentException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.7.0.v20170811-d680af5): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: Error in allocating a connection. Cause: Connection could not be allocated because: java.net.ConnectException : Error connecting to server localhost on port 1,527 with message Connection refused: connect.
</code>```

答:
The solution for this is to create a jdbc connection pool for postgresql in the glassfish. To do this:

Download postgresql jdbc driver here and place it in glassfish5\glassfish\domains\domain1\lib.

Restart your glassfish.

Go to glassfish admin webpage localhost:4848.

Go to JDBC -> JDBC Connection Pools

Click new to create one.

PoolName = anything you want

Resource Type = javax.sql.ConnectionPoolDataSource

Datasource Classname = org.postgresql.jdbc3.Jdbc3PoolingDataSource

For the properties, create these:

user = postgres, your user

portNumber = 5432, the port number to your database

password = the password to connect to your database

databaseName = portfolio, the database name to connect to

servername = localhost, your servername

Ping to test.

Save it.

Go to JDBC -> resources and edit jdbc/__default.

Set pool name to the poolname of your created pool.

ContentLicense: CC BY-SA 4.0

Body:
In Java EE, I have a persistence.xml provided and is packaged correctly.

<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
             version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
    <persistence-unit name="ArticleManagement">
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <class>com.pauljabines.portfolio.Article</class>
        <properties>
            <property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/postgres" />
            <property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver" />
            <property name="javax.persistence.jdbc.user" value="postgres" />
            <property name="javax.persistence.jdbc.password" value="************************" />
            <property name="eclipselink.logging.level" value="ALL" />
        </properties>
    </persistence-unit>
</persistence>

Question: With these connection properties, why is glassfish throwing error and saying that it can't connect to port 1527?

Here is a bit of the stacktrace:

org.glassfish.deployment.common.DeploymentException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.7.0.v20170811-d680af5): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: Error in allocating a connection. Cause: Connection could not be allocated because: java.net.ConnectException : Error connecting to server localhost on port 1,527 with message Connection refused: connect.


问:
Phonegap Build config.xml and geolocation
I have a really odd issue with using geolocation with PhoneGap build. I have it working with my config.xml that looks like this:

```<code><?xml version='1.0' encoding='utf-8'?>
<widget id="net.seekadventure" version="0.0.2" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
  <name>Seek Adventure Map</name>
  <description>
      A map to help you find your next Adventure!
  </description>
  <author email="myEmail" href="https://www.seekadventure.net">
      Seek ADventure Team
  </author>
  <content src="index.html" />
  <plugin name="cordova-plugin-whitelist" spec="1" />

    <preference name="permissions" value="none"/>
    <feature name="http://api.phonegap.com/1.0/geolocation"/>

    <plugin name="cordova-plugin-geolocation" spec="1" />

<icon src="icon.png" />

  <access origin="*" />
  <allow-intent href="http://*/*" />
  <allow-intent href="https://*/*" />
  <allow-intent href="tel:*" />
  <allow-intent href="sms:*" />
  <allow-intent href="mailto:*" />
  <allow-intent href="geo:*" />
  <platform name="android">
      <allow-intent href="market:*" />
  </platform>
  <platform name="ios">
      <allow-intent href="itms:*" />
      <allow-intent href="itms-apps:*" />
  </platform>
</widget>
</code>```

The off part is that when I install it and open it on my phone it gives me a pop up that says this:

"This app was built for an older version of Android and may not work properly. Try checking for updates, or contact the developer"

Since I got that error I did some research and added this to my config.xml

```<code><preference name="android-minSdkVersion" value="27" />
  <preference name="android-maxSdkVersion" value="29" />
  <preference name="android-targetSdkVersion" value="28" />
</code>```

When I add the above code it fixes the error about being built on an old version but the GPS permissions don't work.... Any ideas?

Update:

I also tried specifying source and version for the plugin and that didn't help:

```<code><plugin name="cordova-plugin-geolocation" source="npm" spec="4.0.2" />
</code>```

答:
I was not specifying the CLI version in my config/xml which is what caused the issue:</p>

```<code>  <preference name="phonegap-version" value="cli-9.0.0" />
</code>```

Body:
I have a really odd issue with using geolocation with PhoneGap build. I have it working with my config.xml that looks like this:

<?xml version='1.0' encoding='utf-8'?>
<widget id="net.seekadventure" version="0.0.2" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
  <name>Seek Adventure Map</name>
  <description>
      A map to help you find your next Adventure!
  </description>
  <author email="myEmail" href="https://www.seekadventure.net">
      Seek ADventure Team
  </author>
  <content src="index.html" />
  <plugin name="cordova-plugin-whitelist" spec="1" />

    <preference name="permissions" value="none"/>
    <feature name="http://api.phonegap.com/1.0/geolocation"/>

    <plugin name="cordova-plugin-geolocation" spec="1" />

<icon src="icon.png" />

  <access origin="*" />
  <allow-intent href="http://*/*" />
  <allow-intent href="https://*/*" />
  <allow-intent href="tel:*" />
  <allow-intent href="sms:*" />
  <allow-intent href="mailto:*" />
  <allow-intent href="geo:*" />
  <platform name="android">
      <allow-intent href="market:*" />
  </platform>
  <platform name="ios">
      <allow-intent href="itms:*" />
      <allow-intent href="itms-apps:*" />
  </platform>
</widget>

The off part is that when I install it and open it on my phone it gives me a pop up that says this:

"This app was built for an older version of Android and may not work properly. Try checking for updates, or contact the developer"

Since I got that error I did some research and added this to my config.xml

<preference name="android-minSdkVersion" value="27" />
  <preference name="android-maxSdkVersion" value="29" />
  <preference name="android-targetSdkVersion" value="28" />

When I add the above code it fixes the error about being built on an old version but the GPS permissions don't work.... Any ideas?

Update:

I also tried specifying source and version for the plugin and that didn't help:

<plugin name="cordova-plugin-geolocation" source="npm" spec="4.0.2" />

Body:
I was not specifying the CLI version in my config/xml which is what caused the issue:

  <preference name="phonegap-version" value="cli-9.0.0" />


问:
What is the trailing x
I noticed that their are a lot of technologies that uses X in their names like Directx and PhysX and X server ... is there a something common? Or is there any reason to choose X?

答:
The meaning of the X varies by usage; in PhysX it seems to be the kewl[sic] way to spell Physics; whereas in X Server (part of the X Window System) takes it's name from being the natural evolution of a system named W (probably short for Window, or just the letter after V; the name of the system on which it ran).

DirectX has already been explained in another answer; so there's that.

But the main reason, most of the time; is that Poor Literacy Is Kewl[sic].

ContentLicense: CC BY-SA 3.0

Title: What is the trailing x


问:
What is the "current" Delphi web app framework?
I'm looking at Delphi web server apps, and the first thing I notice when I go into the New Items dialog is that there are several different frameworks.

WebBroker looks the nicest from a conceptual standpoint, but in the documentation it looks like its DB and session-management code is tied to the BDE, which makes it somewhat less than useful today.

WebSnap looks very similar, but the documentation says it's deprecated and IW ("VCL for the Web") should be used instead.

So I look at IW, and I can't make heads or tails of how it's supposed to work.  The sample code is full of stuff that looks like it belongs in a desktop app, like clicking a button to fire an event handler to change the caption of a form element.  (Wouldn't that have to be done client-side in JavaScript if we're creating a webpage?)

So what's the current standard framework for building a web server in Delphi?

答:
Old question but still deserves an up-to-date answer.

Current 'settled in' solutions are:

IntraWeb:

https://www.atozed.com/intraweb/

uniGUI:

http://unigui.com/

```<code>Introduction
uniGUI Web Application Framework extends Web application development experience to a new dimension. uniGUI enables Delphi developers to create, design and debug web applications in IDE using a unique set of visual components. Each component is designed to provide same functionality of its counterpart visual component in Delphi VCL. This provides a very comfortable development environment very close to native VCL application development with an easy learning curve.  uniGUI Web applications can be deployed to a server using one of the available deployment options such as Windows Service, Standalone Server or ISAPI Module.

Product Highlights:

Based on industry's most advanced JavaScript library Sencha Ext JS.
Includes OEM license for Sencha Ext JS. (Please see licensing for details).
A unique platform to create stateful web applications.
Complete IDE support for creating projects, designing forms, frames and handling data modules.
Advanced support for scripting client side JavaScript events.
Library core is fully optimized to achieve highest level of scalability.
Including advanced Stress Test Tool utility.
Comes with various deployment options: ISAPI Module, Standalone Server and Windows Service.
Supported Delphi versions: Turbo Delphi Pro, Delphi 2006, Delphi 2007, Delphi 2009, Delphi 2010, Delphi XE, XE2, XE3, XE4, X5, XE6, XE7, XE8, Delphi 10 Seattle, 10.1 Berlin, 10.2.3 Tokyo and 10.3.3 Rio (Win32 & Win64 platforms). (Linux support is in the roadmap)
C++ Builder supported.
Supported Browsers: IE 9+, Microsoft Edge, FireFox, Chrome, Safari and Opera
New state-of-the-art uniGUI HyperServer technology.
</code>```

TMS WebCore:

https://www.tmssoftware.com/site/tmswebcore.asp

```<code>RADical Web
Modern SPA web application model
Pure HTML5/CSS3/Javascript based applications
Standard component framework for common UI controls and access to browser features
Debugging in Pascal code via the browser
Backed by a solid & proven Delphi Pascal to Javascript compiler that was years in development

Reuse skills and components Component based RAD development integrated
in the Delphi IDE A truly revolutionary & innovative TMS FNC component
framework that is now also web enabled, allowing to create UI controls
that can be used on VCL, FMX, LCL and WEB! Open to consume other
existing Javascript frameworks & libraries Open to use HTML/CSS for
design Open to use other jQuery controls or even other Javascript
frameworks Offers Pascal class wrappers for jQuery controls from the
jQWidgets library Easy interfacing to REST cloud services including to
TMS XData for database

Easy Deployment Application consists of HTML & Javascript files only
that can be easily deployed on any light or heavyweight webservers Use
any existing load-balancing software and/or techniques for highest
performance Small and convenient debug webserver is included for fast
RAD development
</code>```

Body:
Old question but still deserves an up-to-date answer.

Current 'settled in' solutions are:

IntraWeb:

https://www.atozed.com/intraweb/

uniGUI:

http://unigui.com/

Introduction
uniGUI Web Application Framework extends Web application development experience to a new dimension. uniGUI enables Delphi developers to create, design and debug web applications in IDE using a unique set of visual components. Each component is designed to provide same functionality of its counterpart visual component in Delphi VCL. This provides a very comfortable development environment very close to native VCL application development with an easy learning curve.  uniGUI Web applications can be deployed to a server using one of the available deployment options such as Windows Service, Standalone Server or ISAPI Module.

Product Highlights:

Based on industry's most advanced JavaScript library Sencha Ext JS.
Includes OEM license for Sencha Ext JS. (Please see licensing for details).
A unique platform to create stateful web applications.
Complete IDE support for creating projects, designing forms, frames and handling data modules.
Advanced support for scripting client side JavaScript events.
Library core is fully optimized to achieve highest level of scalability.
Including advanced Stress Test Tool utility.
Comes with various deployment options: ISAPI Module, Standalone Server and Windows Service.
Supported Delphi versions: Turbo Delphi Pro, Delphi 2006, Delphi 2007, Delphi 2009, Delphi 2010, Delphi XE, XE2, XE3, XE4, X5, XE6, XE7, XE8, Delphi 10 Seattle, 10.1 Berlin, 10.2.3 Tokyo and 10.3.3 Rio (Win32 & Win64 platforms). (Linux support is in the roadmap)
C++ Builder supported.
Supported Browsers: IE 9+, Microsoft Edge, FireFox, Chrome, Safari and Opera
New state-of-the-art uniGUI HyperServer technology.

TMS WebCore:

https://www.tmssoftware.com/site/tmswebcore.asp

RADical Web
Modern SPA web application model
Pure HTML5/CSS3/Javascript based applications
Standard component framework for common UI controls and access to browser features
Debugging in Pascal code via the browser
Backed by a solid & proven Delphi Pascal to Javascript compiler that was years in development

Reuse skills and components Component based RAD development integrated
in the Delphi IDE A truly revolutionary & innovative TMS FNC component
framework that is now also web enabled, allowing to create UI controls
that can be used on VCL, FMX, LCL and WEB! Open to consume other
existing Javascript frameworks & libraries Open to use HTML/CSS for
design Open to use other jQuery controls or even other Javascript
frameworks Offers Pascal class wrappers for jQuery controls from the
jQWidgets library Easy interfacing to REST cloud services including to
TMS XData for database

Easy Deployment Application consists of HTML & Javascript files only
that can be easily deployed on any light or heavyweight webservers Use
any existing load-balancing software and/or techniques for highest
performance Small and convenient debug webserver is included for fast
RAD development


问:
How do pull images from a wordpress post to display it on the screen?
I am trying to display something like a thumbnail for my post. Is there any wordpress function that can do that? I read about wordpress featured images but I dont see the option to set one on the wordpress admin page.

I also tried using the_post_thumbnail() but it didnt work.

this is what my div looks like at the moment:

```<code><div class="card" style="width: 22rem;">
          <img src="<?php the_post_thumbnail(); ?>" class="card-img-top" alt="...">
          <div class="card-body">
            <h5 class="card-title"><?php the_title() ?></h5>
            <p class="card-text">Random Card content</p>
          </div>
</div>
</code>```

答:
Just use:

```<code><?php the_post_thumbnail(); ?>
</code>```

Like below codes:

```<code><div class="card" style="width: 22rem;">
      <?php the_post_thumbnail('post-thumbnail', ['class' => 'card-img-top']);?>

      <div class="card-body">
        <h5 class="card-title"><?php the_title(); ?></h5>
        <p class="card-text">Random Card content</p>
      </div>
</div>
</code>```

When you use the_post_thumbnail() dont use extra img tag!

Body:
I am trying to display something like a thumbnail for my post. Is there any wordpress function that can do that? I read about wordpress featured images but I dont see the option to set one on the wordpress admin page.

I also tried using the_post_thumbnail() but it didnt work.

this is what my div looks like at the moment:

          <img src="<?php the_post_thumbnail(); ?>" class="card-img-top" alt="...">

<?php the_title() ?>

Random Card content

Body:
Just use:

<?php the_post_thumbnail(); ?>

Like below codes:

<div class="card" style="width: 22rem;">
      <?php the_post_thumbnail('post-thumbnail', ['class' => 'card-img-top']);?>

      <div class="card-body">
        <h5 class="card-title"><?php the_title(); ?></h5>
        <p class="card-text">Random Card content</p>
      </div>
</div>

When you use the_post_thumbnail() dont use extra img tag!


问:
django tables2 display sort arrows on header
I'm using django tables2, and I think it would be useful to have up and down arrows on header columns to indicate the current sorting order, especially when the default sort is on a column other than the first.

Tried playing with CSS but no luck, any suggestions or examples on how to do this?

答:
The answer provided in this question may solve your problem, though it it hard to know for sure without knowing what you have tried already with CSS.

The templates that come built-in with django-tables2 all render column attributes to the final HTML, so that a column that is defined as orderable=True will produce column header tags with an "orderable" class (e.g. ). Furthermore, columns that have been selected to sort ascending or descending will have asc or desc class identifiers added on render.

So, you can set up a CSS rule that will render three different arrow images depending on the state of the orderable column:

```<code>table.table thead th.orderable {
    background: url(path_to_unsorted_indicator_image)
}

table.table thead th.asc.orderable {
    background: url(path_to_ascending_indicator_image)
}

table.table thead th.desc.orderable {
    background: url(path_to_descending_indicator_image)
}
</code>```

Body:
The answer provided in this question may solve your problem, though it it hard to know for sure without knowing what you have tried already with CSS.

The templates that come built-in with django-tables2 all render column attributes to the final HTML, so that a column that is defined as orderable=True will produce column header tags with an "orderable" class (e.g. <th class="orderable">). Furthermore, columns that have been selected to sort ascending or descending will have asc or desc class identifiers added on render.

So, you can set up a CSS rule that will render three different arrow images depending on the state of the orderable column:

table.table thead th.orderable {
    background: url(path_to_unsorted_indicator_image)
}

table.table thead th.asc.orderable {
    background: url(path_to_ascending_indicator_image)
}

table.table thead th.desc.orderable {
    background: url(path_to_descending_indicator_image)
}


问:
Reading a string from a file with C. Fopen with w+ mode is not working
I made a C program that reads a string from a .txt file, then it encrypts the string, and finally it writes the string in the same file.

The thing is that if I use fopen("D:\\Prueba.txt","w+"), the program doesn't work, it prints garbage like this )PHI N.

I've debugged and I know the error is there in that line, because if I use fopen("D:\\Prueba.txt","r+"), the program works, and it writes what it should.

But I want to use w+ because it will rewrite what the .txt file had. Why is w+ not working?

答:
If you're opening with w+ to first read the content, that's not going to work. From C11:

w+: truncate to zero length or create text file for update.

What's probably happening is that you read data from the now empty file but don't correctly check that it worked. That would explain the weird "content" you see of )PHI  N.

One solution is to open the file as with r, open another file with w, and transfer the contents, encrypting them as part of that process. Then close both, delete the original, and rename the new one to the original name. This will allow you to process arbitrarily-sized files since you process them a bit at a time.

If you don't want to use a temporary file, and you're sure you can store the entire content in memory, you could open it r+, get the content, the reopen it with a new mode, such as with:

```<code>FILE *readFh = fopen( "myfile.txt", "r+");
// Read in content, massage as needed.

FILE *writeFh = frepoen( NULL, "w+", readFh);
// Provided that worked, you should now have an empty file to write to.
// Write back your massaged data.
</code>```

Body:
If you're opening with w+ to first read the content, that's not going to work. From C11:

w+: truncate to zero length or create text file for update.

What's probably happening is that you read data from the now empty file but don't correctly check that it worked. That would explain the weird "content" you see of )PHI  N.

One solution is to open the file as with r, open another file with w, and transfer the contents, encrypting them as part of that process. Then close both, delete the original, and rename the new one to the original name. This will allow you to process arbitrarily-sized files since you process them a bit at a time.

If you don't want to use a temporary file, and you're sure you can store the entire content in memory, you could open it r+, get the content, the reopen it with a new mode, such as with:

FILE *readFh = fopen( "myfile.txt", "r+");
// Read in content, massage as needed.

FILE *writeFh = frepoen( NULL, "w+", readFh);
// Provided that worked, you should now have an empty file to write to.
// Write back your massaged data.


问:
Highlight rows depending on month

I have a table and a input where a person is supposed to enter a month 1-12, and when submitting, the rows from that month should turn red. How do I get the month out of these dates to determine which month they are from? I am unsure how to continue.

```<code> <input type="text" placeholder="Kuukausi" id="searchMonth"/>
            <button type="submit" id="searchbutton">
            <span>Etsi</span></button>
            </div>
            <table style="width: 100%" id="table">
            <tr>
                <th>Lintu</th>
                <th>Päivä</th>
            </tr>
            <tr>
                <td>Varis</td>
                <td>20.4.2018</td>
            </tr>
            <tr>
                <td>Huuhkaja</td>
                <td>14.9.2018</td>
            </tr>
            <tr>
                <td>Pääskynen</td>
                <td>24.4.2018</td>
            </tr>
            <tr>
                <td>Peippo</td>
                <td>30.3.2018</td>
            </tr>
</code>```

答:
Use a type="number" input element

No need to "Submit" buttons.

Add an ID to tbody

Use JS TableElement rows and TableRowElement cells objects

Use the "input" event to trigger a searchMonth() function

Loop your TBODY TR elements, find the 1th index cell and split its content by . dots to retrieve the month string.

Check if the splitted date month equals to the inputed one

Use JS Element.classList.toggle('className', boolean) to toggle the CSS .highlight class

const tbody = document.querySelector("#tableTbody");

const searchMonth = evt => {
  const monthValue = evt.target.value.trim();
  [...tbody.rows].forEach(row => {
    const month = row.cells[1].textContent.split('.')[1];
    row.classList.toggle('highlight', monthValue == month);
  })
};

document.querySelector("#searchMonth").addEventListener('input', searchMonth);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.highlight td {
  background: yellow;
}</code>```

Month: <input type="number" id="searchMonth" min=1 max=12>

      Foo
      Date

      a
      20.4.2018

      b
      14.9.2018

      c
      24.4.2018

      d
      30.3.2018

```

Title: Highlight rows depending on month

Body:
I have a table and a input where a person is supposed to enter a month 1-12, and when submitting, the rows from that month should turn red. How do I get the month out of these dates to determine which month they are from? I am unsure how to continue.

 <input type="text" placeholder="Kuukausi" id="searchMonth"/>
            <button type="submit" id="searchbutton">
            Etsi</button>

                Lintu
                Päivä

                Varis
                20.4.2018

                Huuhkaja
                14.9.2018

                Pääskynen
                24.4.2018

                Peippo
                30.3.2018

Body:
Use a type="number" input element

No need to "Submit" buttons.

Add an ID to tbody

Use JS TableElement rows and TableRowElement cells objects

Use the "input" event to trigger a searchMonth() function

Loop your TBODY TR elements, find the 1th index cell and split its content by . dots to retrieve the month string.

Check if the splitted date month equals to the inputed one

Use JS Element.classList.toggle('className', boolean) to toggle the CSS .highlight class

const tbody = document.querySelector("#tableTbody");

const searchMonth = evt => {
  const monthValue = evt.target.value.trim();
  [...tbody.rows].forEach(row => {
    const month = row.cells[1].textContent.split('.')[1];
    row.classList.toggle('highlight', monthValue == month);
  })
};

document.querySelector("#searchMonth").addEventListener('input', searchMonth);

.highlight td {
  background: yellow;
}

<label>Month: <input type="number" id="searchMonth" min=1 max=12></label>

<table>
  <thead>
    <tr>
      <th>Foo</th>
      <th>Date</th>
    </tr>
  </thead>
  <tbody id="tableTbody">
    <tr>
      <td>a</td>
      <td>20.4.2018</td>
    </tr>
    <tr>
      <td>b</td>
      <td>14.9.2018</td>
    </tr>
    <tr>
      <td>c</td>
      <td>24.4.2018</td>
    </tr>
    <tr>
      <td>d</td>
      <td>30.3.2018</td>
    </tr>
  </tbody>
</table>


答:
Something like this would work:

// handle click and add class
$('#searchbutton').on("click", function() {
  $('.highlight').removeClass('highlight');
  var rows = $('#table').find('tr');
  var value = $('#searchMonth').val().trim();
  $.each(rows, function() {
    var dateCol = $(this).find('td').eq(1);
    if (dateCol.length > 0) {
      var date = dateCol.text();
      var month = (date.match(/\d{2}.(\d{1,2}).\d{4}/) || [])[1];
      if (month == value) {
        $(this).addClass('highlight');
      }
    }
  });

})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.highlight {
  background: red;
}</code>```

<input type="text" placeholder="Kuukausi" id="searchMonth"/>
            <button type="submit" id="searchbutton">
            Etsi</button>

                Lintu
                Päivä

                Varis
                20.4.2018

                Huuhkaja
                14.9.2018

                Pääskynen
                24.4.2018

                Peippo
                30.3.2018

```

Title: Highlight rows depending on month

Body:
Something like this would work:

// handle click and add class
$('#searchbutton').on("click", function() {
  $('.highlight').removeClass('highlight');
  var rows = $('#table').find('tr');
  var value = $('#searchMonth').val().trim();
  $.each(rows, function() {
    var dateCol = $(this).find('td').eq(1);
    if (dateCol.length > 0) {
      var date = dateCol.text();
      var month = (date.match(/\d{2}.(\d{1,2}).\d{4}/) || [])[1];
      if (month == value) {
        $(this).addClass('highlight');
      }
    }
  });

})

.highlight {
  background: red;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" placeholder="Kuukausi" id="searchMonth"/>
            <button type="submit" id="searchbutton">
            <span>Etsi</span></button>
            <table style="width: 100%" id="table">
            <tr>
                <th>Lintu</th>
                <th>Päivä</th>
            </tr>
            <tr>
                <td>Varis</td>
                <td>20.4.2018</td>
            </tr>
            <tr>
                <td>Huuhkaja</td>
                <td>14.9.2018</td>
            </tr>
            <tr>
                <td>Pääskynen</td>
                <td>24.4.2018</td>
            </tr>
            <tr>
                <td>Peippo</td>
                <td>30.3.2018</td>
            </tr>
            </table>


问:
Function isn't giving response
This is my code:

function findTriad(numbers, sum) {
  for (let i = 0; i < numbers.length - 1; i++) {
    const firstNumber = numbers[i];
    const newSum = sum - firstNumber;
    let startOfCheckIndex = i + 1;
    const endOfCheckIndex = numbers.length - 1;

    while (startOfCheckIndex < endOfCheckIndex) {
      const possibleAnswer =
        numbers[startOfCheckIndex] + numbers[endOfCheckIndex];
      if (possibleAnswer === newSum) {
        return [
          numbers[i],
          numbers[startOfCheckIndex],
          numbers[endOfCheckIndex]
        ];
      } else if (sum < newSum) {
        startOfCheckIndex++;
      }
    }
  }
  return ["N/A"];
}

function logFindTriad(numbers, sum) {
  const answer = findTriad(numbers, sum);

  console.log("Sum required: " + sum);
  console.log("Numbers given: " + numbers.join(", "));
  console.log("Found: " + answer.join(", ") + "\n");
}

logFindTriad([10, 15, 3, 7], 20);```

Does anyone know why this code isn't giving me any value back?
It is supposed to give me back [10, 3, 7] if you find any errors or areas to improve on my code please tell me even if it doesn't resolve the issue.

答:
First, function findTriad you are not defined

Then, your code has execute to else statement because condition in if and else if is wrong so you go to infinity loop (because you don't update value of startOfCheckIndex after loop, you can debug your code and find a true way to give condition in if elsestatement. I can give code sample here

Happy coding !

Title: Function isn't giving response

Body:
This is my code:

function findTriad(numbers, sum) {
  for (let i = 0; i < numbers.length - 1; i++) {
    const firstNumber = numbers[i];
    const newSum = sum - firstNumber;
    let startOfCheckIndex = i + 1;
    const endOfCheckIndex = numbers.length - 1;

    while (startOfCheckIndex < endOfCheckIndex) {
      const possibleAnswer =
        numbers[startOfCheckIndex] + numbers[endOfCheckIndex];
      if (possibleAnswer === newSum) {
        return [
          numbers[i],
          numbers[startOfCheckIndex],
          numbers[endOfCheckIndex]
        ];
      } else if (sum < newSum) {
        startOfCheckIndex++;
      }
    }
  }
  return ["N/A"];
}

function logFindTriad(numbers, sum) {
  const answer = findTriad(numbers, sum);

  console.log("Sum required: " + sum);
  console.log("Numbers given: " + numbers.join(", "));
  console.log("Found: " + answer.join(", ") + "\n");
}

logFindTriad([10, 15, 3, 7], 20);

Does anyone know why this code isn't giving me any value back?
It is supposed to give me back [10, 3, 7] if you find any errors or areas to improve on my code please tell me even if it doesn't resolve the issue.


问:
Is it possible to reload the page on key press in javascript (without focusing the page)?
I want to reload my page on key press in JavaScript. I already use this code,

```<code>document.addEventListener('keyup', function (e) {
    if (e.keyCode == 13)
        window.location.reload();
});
</code>```

from this post-Refresh page on ENTER / RETURN key press

But the problem is when the current page is not in focus it does not work. For example when I open the developer tools or click on it. Then the keypress event is not working for focus out (I think so).

Is it possible to do it without focusing on the page using JavaScript?

答: It's not possible to do in that way in JavaScript, But, why and in which case you need to reload the page? I mean when you not focused on page.</p>

Body:
I want to reload my page on key press in JavaScript. I already use this code,

document.addEventListener('keyup', function (e) {
    if (e.keyCode == 13)
        window.location.reload();
});

from this post-Refresh page on ENTER / RETURN key press

But the problem is when the current page is not in focus it does not work. For example when I open the developer tools or click on it. Then the keypress event is not working for focus out (I think so).

Is it possible to do it without focusing on the page using JavaScript?


问:
How to transform data in Column Date using cut function in R
I have a Release date column in my dataset and need to add a column Decade which supposed to have 4 levels of "1980s", "1990s", "2000s", "2010s".

1980s within 1980-01-01 to 1989-12-31

1990s within 1990-01-01 to 1999-12-31
etc.

Sample of Release Date Column

Here is my code so far:

```<code>df$Decade <- cut(df$Release, c(1970,1980,1990,2000))
levels(df$Decade) <- c("1980s", "1990s", "2000s", "2010s")
</code>```

Here's the error I'm getting:

Error in cut.Date(df$Release, 10 + c(1970, 1980, 1990, 2000)) :
    invalid specification of 'breaks'

Any help will be greatly appreciated.

答:
One way would be to convert Release into date, extract only first 3 characters of the year. So 199 for 1991 or 198 for 1987 and then add "0s" to get the decade.

```<code>df <- data.frame(Release = c('5/21/1980', '12/12/1980', '5/12/1991'))
df$Decade <- paste0(substring(as.Date(x, '%m/%d/%Y'), 1, 3), "0s")
df
#     Release Decade
#1  5/21/1980  1980s
#2 12/12/1980  1980s
#3  5/12/1991  1990s
</code>```

Body:
I have a Release date column in my dataset and need to add a column Decade which supposed to have 4 levels of "1980s", "1990s", "2000s", "2010s".

1980s within 1980-01-01 to 1989-12-31

1990s within 1990-01-01 to 1999-12-31
etc.

Sample of Release Date Column

Here is my code so far:

df$Decade <- cut(df$Release, c(1970,1980,1990,2000))
levels(df$Decade) <- c("1980s", "1990s", "2000s", "2010s")

Here's the error I'm getting:

Error in cut.Date(df$Release, 10 + c(1970, 1980, 1990, 2000)) :
    invalid specification of 'breaks'

Any help will be greatly appreciated.

Body:
One way would be to convert Release into date, extract only first 3 characters of the year. So 199 for 1991 or 198 for 1987 and then add "0s" to get the decade.

df <- data.frame(Release = c('5/21/1980', '12/12/1980', '5/12/1991'))
df$Decade <- paste0(substring(as.Date(x, '%m/%d/%Y'), 1, 3), "0s")
df
#     Release Decade
#1  5/21/1980  1980s
#2 12/12/1980  1980s
#3  5/12/1991  1990s


问:
Execute binary file inside C code (No system())
I am trying to execute a binary executable file inside C code without using system since it has security and resource management issues.

The system used here is Debian Buster with kernel 5.4.0-2-amd64 and gcc 9.2.1.

I used the method in this question:
execute binary machine code from C

which is to convert executable into hexadecimal code with xxd -i, but constantly get Segmentation fault.

The procedures I used are:

First attempt

executable.c:

```<code>#include <stdio.h>
int main(void)
{
    printf("Hello, World!\n");
    return 0;
}
</code>```

after compiling it with gcc -o executable executable.c

xxd -i executable will display binary file into hex

Then copy and paste the output to embedded.c

embedded.c:

```<code>#include <string.h>
#include <unistd.h>
#include <sys/mman.h>

const unsigned char[] executable = {
    0x7f, 0x45, 0x4c, 0x46, 0x02, 0x01,
    ...
};

int main(void)
{
    void *buf = mmap(
        NULL, sizeof(executable), PROT_READ | PROT_WRITE | PROT_EXEC,
        MAP_PRIVATE | MAP_ANON, -1, 0);
    memcpy(buf, sizeof(executable);
    __builtin___clear_cache(buf, buf + sizeof(executable) - 1);

    int i = ((int (*) (void)buf)();
    return 0;
}
</code>```

when compiled and run, the terminal displays Segmentation fault.

Second attempt

Another method I tried is by using ld which also displayed Segmentation fault:

embedded.c:

```<code>extern const char _binary_executable_start[];
extern const char _binary_executable_end[];

// And same as the previous code.
</code>```

The code was compiled using:

gcc -c -o embedded.o embedded.c

ld -r -b binary -o executable.o executable

gcc -o embedded embedded.o executable.o

And failed.

Is there anything I missed or is it impossible to embed binary file into C code and run it?

答:
The executable content you're providing is an ELF executable, not raw machine code.  On Linux, ELF is the container format that is used to contain executables and shared libraries, and it wraps the actual executable code and associated data, like strings and arrays, with a format that allows it to be loaded easily.

As a result, the code you're trying to execute isn't actually machine code, it's ELF header data.  Even if you extract the executable code out of the ELF, it generally still needs to be relocated by the dynamic linker, so it won't easily be able to be executed directly.

Instead, consider putting the additional code into a shared library and executing it there.  If you need to load the code dynamically, you can use the dlopen(3) function to load a shared library and dlsym(3) to find the function you want to execute, provided you link with -ldl.

Body:
I am trying to execute a binary executable file inside C code without using system since it has security and resource management issues.

The system used here is Debian Buster with kernel 5.4.0-2-amd64 and gcc 9.2.1.

I used the method in this question:
execute binary machine code from C

which is to convert executable into hexadecimal code with xxd -i, but constantly get Segmentation fault.

The procedures I used are:

First attempt

executable.c:

#include <stdio.h>
int main(void)
{
    printf("Hello, World!\n");
    return 0;
}

after compiling it with gcc -o executable executable.c

xxd -i executable will display binary file into hex

Then copy and paste the output to embedded.c

embedded.c:

#include <string.h>
#include <unistd.h>
#include <sys/mman.h>

const unsigned char[] executable = {
    0x7f, 0x45, 0x4c, 0x46, 0x02, 0x01,
    ...
};

int main(void)
{
    void *buf = mmap(
        NULL, sizeof(executable), PROT_READ | PROT_WRITE | PROT_EXEC,
        MAP_PRIVATE | MAP_ANON, -1, 0);
    memcpy(buf, sizeof(executable);
    __builtin___clear_cache(buf, buf + sizeof(executable) - 1);

    int i = ((int (*) (void)buf)();
    return 0;
}

when compiled and run, the terminal displays Segmentation fault.

Second attempt

Another method I tried is by using ld which also displayed Segmentation fault:

embedded.c:

extern const char _binary_executable_start[];
extern const char _binary_executable_end[];

// And same as the previous code.

The code was compiled using:

gcc -c -o embedded.o embedded.c

ld -r -b binary -o executable.o executable

gcc -o embedded embedded.o executable.o

And failed.

Is there anything I missed or is it impossible to embed binary file into C code and run it?


问:
Append from txt to worksheet - Powershell
I'm trying to build a script which takes the content of text file and appends it to the worksheet but it stops at the first match. I want it to go through the whole text file and append EVERY match to the worksheet.

Text file:

```<code>Node: ABC
Name: PC
Cluster: HS1
Node: XZZ
Name: CC
Cluster: HS2
Node: XYZ
Name: DD
Cluster: HS3

</code>```

How I want it to be

```<code>Node|Name|Cluster
ABC    PC   HS1
XZZ    CC   HS2
XYZ    DD   HS3
</code>```

I'm using the following code:

```<code>$WorkbookPath = "Destination Path"
$Patterns = "Name"
$Testbestand = get-content "Source Path"
$sheetName = "Sheet1"
$objExcel = New-Object -ComObject Excel.Application
$WorkBook = $objExcel.Workbooks.Open($WorkbookPath)
$WorkSheet = $WorkBook.sheets.item($sheetName)
$usedRange = $WorkSheet.usedRange
$lastCell = $usedRange.SpecialCells(11)
$newRow = $lastCell.row + 1
foreach ($Pattern in $Patterns){
$AlertValue = $Testbestand | Select-string -pattern $Pattern -list -quiet
$AlertValue = ($AlertValue -split " ")[-1]
$col = ($Worksheet.Columns.Find($pattern))
$WorkSheet.cells.item($newRow, $col.Column).value = $AlertValue
}#foreach pattern
$WorkBook.Save()
$objExcel.Quit()
</code>```

答:
As for this...

Thanks for your reply. Isn't it possible to loop through the patterns
  and append with text files? –

... sure, several ways to convert that to something more usable...

Yet, you should really hit up the folks to fix the file on the export from whatever tool this came from, to a proper file format you can use before you get it. Saving everyone precious time. Yet, sometimes we have to deal with what we get.

```<code>@'
Node: ABC
Name: PC
Cluster: HS1
Node: XZZ
Name: CC
Cluster: HS2
Node: XYZ
Name: DD
Cluster: HS3
'@ | Out-File -FilePath 'D:\Temp\TextData.txt'

$FileContent = Get-Content -Path 'D:\Temp\TextData.txt'
0..(($FileContent -match '^Node' -replace '^Node: ' ).Count -1) |
Select-Object @{Name = "Node";Expression = {($FileContent -match '^Node' -replace '^Node: ')[$PSitem]}},
@{Name = "Name";Expression = {($FileContent -match '^Name' -replace '^Name: ')[$PSitem]}},
@{Name = "Cluster";Expression = {($FileContent -match '^Cluster' -replace '^Cluster: ')[$PSitem]}} |
Export-Csv -Path 'D:\Temp\TextData.csv' -NoTypeInformation

Get-Content -Path 'D:\Temp\TextData.csv'
Import-Csv -Path 'D:\Temp\TextData.csv'

<#
Node Name Cluster
---- ---- -------
ABC  PC   HS1
XZZ  CC   HS2
XYZ  DD   HS3
#>

# Or this way
$FileContent = Get-Content -Path 'D:\Temp\TextData.txt'
0..(($FileContent -match '^Node' -replace '^Node: ' ).Count -1) |
ForEach{
    [PSCustomObject]@{
        Node = (($FileContent -match '^Node' -replace '^Node: ')[$_] )
        Name = (($FileContent -match '^Name' -replace '^Name: ')[$_] )
        Cluster = (($FileContent -match '^Cluster' -replace '^Cluster: ')[$_])
    }
} |
Export-Csv -Path 'D:\Temp\TextData.csv' -NoTypeInformation

Get-Content -Path 'D:\Temp\TextData.csv'
Import-Csv -Path 'D:\Temp\TextData.csv'

<#
Node Name Cluster
---- ---- -------
ABC  PC   HS1
XZZ  CC   HS2
XYZ  DD   HS3
#>
</code>```

Once you have the above, append as you need to.

There are always ways. some more elegant than others, but you need to research that and decide what works for your use case.

Body:
I'm trying to build a script which takes the content of text file and appends it to the worksheet but it stops at the first match. I want it to go through the whole text file and append EVERY match to the worksheet.

Text file:

Node: ABC
Name: PC
Cluster: HS1
Node: XZZ
Name: CC
Cluster: HS2
Node: XYZ
Name: DD
Cluster: HS3

How I want it to be

Node|Name|Cluster
ABC    PC   HS1
XZZ    CC   HS2
XYZ    DD   HS3

I'm using the following code:

$WorkbookPath = "Destination Path"
$Patterns = "Name"
$Testbestand = get-content "Source Path"
$sheetName = "Sheet1"
$objExcel = New-Object -ComObject Excel.Application
$WorkBook = $objExcel.Workbooks.Open($WorkbookPath)
$WorkSheet = $WorkBook.sheets.item($sheetName)
$usedRange = $WorkSheet.usedRange
$lastCell = $usedRange.SpecialCells(11)
$newRow = $lastCell.row + 1
foreach ($Pattern in $Patterns){
$AlertValue = $Testbestand | Select-string -pattern $Pattern -list -quiet
$AlertValue = ($AlertValue -split " ")[-1]
$col = ($Worksheet.Columns.Find($pattern))
$WorkSheet.cells.item($newRow, $col.Column).value = $AlertValue
}#foreach pattern
$WorkBook.Save()
$objExcel.Quit()

Body:
As for this...

Thanks for your reply. Isn't it possible to loop through the patterns
  and append with text files? –

... sure, several ways to convert that to something more usable...

Yet, you should really hit up the folks to fix the file on the export from whatever tool this came from, to a proper file format you can use before you get it. Saving everyone precious time. Yet, sometimes we have to deal with what we get.

@'
Node: ABC
Name: PC
Cluster: HS1
Node: XZZ
Name: CC
Cluster: HS2
Node: XYZ
Name: DD
Cluster: HS3
'@ | Out-File -FilePath 'D:\Temp\TextData.txt'

$FileContent = Get-Content -Path 'D:\Temp\TextData.txt'
0..(($FileContent -match '^Node' -replace '^Node: ' ).Count -1) |
Select-Object @{Name = "Node";Expression = {($FileContent -match '^Node' -replace '^Node: ')[$PSitem]}},
@{Name = "Name";Expression = {($FileContent -match '^Name' -replace '^Name: ')[$PSitem]}},
@{Name = "Cluster";Expression = {($FileContent -match '^Cluster' -replace '^Cluster: ')[$PSitem]}} |
Export-Csv -Path 'D:\Temp\TextData.csv' -NoTypeInformation

Get-Content -Path 'D:\Temp\TextData.csv'
Import-Csv -Path 'D:\Temp\TextData.csv'

<#
Node Name Cluster
---- ---- -------
ABC  PC   HS1
XZZ  CC   HS2
XYZ  DD   HS3
#>

# Or this way
$FileContent = Get-Content -Path 'D:\Temp\TextData.txt'
0..(($FileContent -match '^Node' -replace '^Node: ' ).Count -1) |
ForEach{
    [PSCustomObject]@{
        Node = (($FileContent -match '^Node' -replace '^Node: ')[$_] )
        Name = (($FileContent -match '^Name' -replace '^Name: ')[$_] )
        Cluster = (($FileContent -match '^Cluster' -replace '^Cluster: ')[$_])
    }
} |
Export-Csv -Path 'D:\Temp\TextData.csv' -NoTypeInformation

Get-Content -Path 'D:\Temp\TextData.csv'
Import-Csv -Path 'D:\Temp\TextData.csv'

<#
Node Name Cluster
---- ---- -------
ABC  PC   HS1
XZZ  CC   HS2
XYZ  DD   HS3
#>

Once you have the above, append as you need to.

There are always ways. some more elegant than others, but you need to research that and decide what works for your use case.


问:
onClick JS not go to top of the page
I have a page with an initial description, followed by 2 buttons, where the user can choose typeA or typeB. They work by "target": when the user clicks typeA comes the content relative to typeA, bellow the buttons; same to typeB.

typeA is the most common selection, then, when the page loads, a javascript emulates the click to typeA and opens respective content. To avoid hidden the initial description, there is another javascript to put the page at the top. Worked on Chrome and Edge, not on Firefox.

I would like to repeat the same process when the user clicks: opens the respective content, but positioning the page at the top, or, at least, showing the buttons. I thought event onClick calling the same js backToTop would worked - but not.

I put an alert on js and enters there but not execute: always keeps the content of the button selected in its better visibility.

I tried:

```<code>window.location.href = '#top';
window.scrollBy(0, -500);
document.html.scrollTop = document.documentElement.scrollTop = 0;
</code>```

without success.

What am I doing wrong?

<meta charset="UTF-8">
<title>TOP PAGE TEST</title>
<meta name="viewport" content="width=device-width, initial-scale=1">

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
<div id="top">Top Page</div>

<br>textExp1<br>textExp2<br>textExp3<br>textExp4<br>textExp5

<div class="menuFAQ">
  <ul>
    <li>TypeA</li>
    <li>TypeB</li>
  </ul>
</div>

<div class="items">
  <div id="typeA">
    <nav>
      A long and variable text size to explain TypeA  <br>text1A<br>text2A<br>text3A<br>text4A<br>text5A<br>text6A<br>text7A<br>text8A<br>text9A<br>textAA<br>textBA<br>textCA<br>textDA
      <br>[...]
    </nav>
  </div>
</div>

<div class="items">
  <div id="typeB">
    <nav>
      A long and variable text size to explain TypeB
      <p>text1B</p><p>text2B</p><p>text3B</p>
      <br>[...]
    </nav>
  </div>
</div>

<script>
const allTargetLinks = document.querySelectorAll('.target')

allTargetLinks.forEach(targetLink => {
   targetLink.addEventListener('click', () => {
        allTargetLinks.forEach(targetLink => {
           targetLink.classList.remove('active')
        })
   targetLink.classList.add('active')
   })
})

window.onload = function() {assignPreferedFAQ()};

function assignPreferedFAQ() {
    document.getElementById("preferedFAQ").click();
    backToTop();
};

function backToTop() {
   //document.html.scrollTop = document.documentElement.scrollTop = 0;
   //document.body.scrollTop = document.documentElement.scrollTop = 0;

     document.body.scrollTop = 0;
     document.documentElement.scrollTop = 0;
};
</script></code>```

答:
Hope this help you.

< script >
  window.onload = function() {
    document.getElementById("preferedFAQ").click();
    backToTop();
  };

function backToTop() {
  document.documentElement.scrollTop = document.body.scrollTop = 0;
  //alert("enter backToTop");
  var elmnt = document.getElementById("top");
  var x = elmnt.scrollLeft;
  var y = elmnt.scrollTop;
}; <
/script>```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body,
html {
  margin-left: auto;
  margin-right: auto;
  width: 70%;
  font-family: verdana;
  font-size: 1.2em;
}

.menuFAQ {
  background: #aaa;
  font-size: 2em;
  width: 100%;
}

.menuFAQ ul {
  list-style-type: none;
  position: relative;
  margin-left: -40px;
  /* to avoid user agent chrome */
}

.menuFAQ li {
  display: inline-block;
  margin-top: 10px;
  margin-bottom: 10px;
  width: 49%;
  background: #fff;
  text-align: center;
  box-shadow: 2px 3px 4px 0px rgba(170, 170, 170, 1);
  font-weight: 400;
  line-height: 80px;
}

.menuFAQ li a {
  display: block;
  color: #020062;
  background: #fff;
  font-weight: 400;
  text-decoration: none;
}

.menuFAQ li .active,
.menuFAQ li:hover a {
  color: #fff;
  font-weight: 400;
  background-image: linear-gradient(#165686, #0f3a5a);
}

:target {
  color: #fff;
  font-size: 1em;
}

div.items>div:not(:target) {
  display: none
}

div.items>div:target {
  display: block;
  margin-left: auto;
  margin-right: auto;
  color: #000;
  border: 1px solid #aaa;
}</code>```

Top Page

textExp1
textExp2
textExp3
textExp4
textExp5
textExp6
textExp7
textExp8
textExp9
textExpA
textExpB
textExpC
textExpD

textExpE

TypeA

TypeB

      A long and variable text size to explain TypeA
text1A
text2A
text3A
text4A
text5A
text6A
text7A
text8A
text9A
textAA
textBA
textCA
textDA

[...]

      A long and variable text size to explain TypeB

text1B

text2B

text3B

[...]

  </di```

Title: onClick JS not go to top of the page

Body:
I have a page with an initial description, followed by 2 buttons, where the user can choose typeA or typeB. They work by "target": when the user clicks typeA comes the content relative to typeA, bellow the buttons; same to typeB.

typeA is the most common selection, then, when the page loads, a javascript emulates the click to typeA and opens respective content. To avoid hidden the initial description, there is another javascript to put the page at the top. Worked on Chrome and Edge, not on Firefox.

I would like to repeat the same process when the user clicks: opens the respective content, but positioning the page at the top, or, at least, showing the buttons. I thought event onClick calling the same js backToTop would worked - but not.

I put an alert on js and enters there but not execute: always keeps the content of the button selected in its better visibility.

I tried:

window.location.href = '#top';
window.scrollBy(0, -500);
document.html.scrollTop = document.documentElement.scrollTop = 0;

without success.

What am I doing wrong?

<meta charset="UTF-8">
<title>TOP PAGE TEST</title>
<meta name="viewport" content="width=device-width, initial-scale=1">

Top Page

textExp1
textExp2
textExp3
textExp4
textExp5

TypeA

TypeB

      A long and variable text size to explain TypeA
text1A
text2A
text3A
text4A
text5A
text6A
text7A
text8A
text9A
textAA
textBA
textCA
textDA

[...]

      A long and variable text size to explain TypeB

text1B

text2B

text3B

[...]

Body:
Hope this help you.

< script >
  window.onload = function() {
    document.getElementById("preferedFAQ").click();
    backToTop();
  };

function backToTop() {
  document.documentElement.scrollTop = document.body.scrollTop = 0;
  //alert("enter backToTop");
  var elmnt = document.getElementById("top");
  var x = elmnt.scrollLeft;
  var y = elmnt.scrollTop;
}; <
/script>

body,
html {
  margin-left: auto;
  margin-right: auto;
  width: 70%;
  font-family: verdana;
  font-size: 1.2em;
}

.menuFAQ {
  background: #aaa;
  font-size: 2em;
  width: 100%;
}

.menuFAQ ul {
  list-style-type: none;
  position: relative;
  margin-left: -40px;
  /* to avoid user agent chrome */
}

.menuFAQ li {
  display: inline-block;
  margin-top: 10px;
  margin-bottom: 10px;
  width: 49%;
  background: #fff;
  text-align: center;
  box-shadow: 2px 3px 4px 0px rgba(170, 170, 170, 1);
  font-weight: 400;
  line-height: 80px;
}

.menuFAQ li a {
  display: block;
  color: #020062;
  background: #fff;
  font-weight: 400;
  text-decoration: none;
}

.menuFAQ li .active,
.menuFAQ li:hover a {
  color: #fff;
  font-weight: 400;
  background-image: linear-gradient(#165686, #0f3a5a);
}

:target {
  color: #fff;
  font-size: 1em;
}

div.items>div:not(:target) {
  display: none
}

div.items>div:target {
  display: block;
  margin-left: auto;
  margin-right: auto;
  color: #000;
  border: 1px solid #aaa;
}

<div id="top">Top Page</div> <br>textExp1<br>textExp2<br>textExp3<br>textExp4<br>textExp5<br>textExp6<br>textExp7<br>textExp8<br>textExp9<br>textExpA<br>textExpB<br>textExpC<br>textExpD
<br>textExpE

<div class="menuFAQ">
  <ul>
    <li><a id="preferedFAQ" onclick="backToTop()" class="target" href="#typeA">TypeA</a></li>
    <li><a onclick="backToTop()" class="target" href="#typeB">TypeB</a></li>
  </ul>
</div>

<div class="items">
  <div id="typeA">
    <nav>
      A long and variable text size to explain TypeA <br>text1A<br>text2A<br>text3A<br>text4A<br>text5A<br>text6A<br>text7A<br>text8A<br>text9A<br>textAA<br>textBA<br>textCA<br>textDA
      <br>[...]
    </nav>
  </div>
</div>

<div class="items">
  <div id="typeB">
    <nav>
      A long and variable text size to explain TypeB
      <p>text1B</p>
      <p>text2B</p>
      <p>text3B</p>
      <br>[...]
    </nav>
  </div>
  </di


问:
Prevent destroying (or restore state) of Fragment B when navigating back from D - Navigation Component
I have fragments: A, B, C, D. I navigate A -> B . Fragment B gets and saves state from arguments. Then I navigate B -> C. And then C -> D. When I call two times findNavController().popBackStack() I get correct behavior: D -> B and B still has correct state. It works because fragment B has never been destroyed, just its view. And then view is recreated when coming back. But calling two times popBackStack() isn't recommended action. We should instead use the action with app:popUpTo and app:popUpToInclusive="true":

```<code><action
    android:id="@+id/action_fragmentD_to_fragmentB"
    app:destination="@id/fragmentB"
    app:popUpTo="@+id/fragmentB"
    app:popUpToInclusive="true" />
</code>```

But it forces fragment B to be destroyed completely and then recreated. Bu with no previous state.

In other words I want to achieve the same behavior as with Activities when used FLAG_ACTIVITY_CLEAR_TOP + FLAG_ACTIVITY_SINGLE_TOP: https://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_CLEAR_TOP

答:
There's no requirement to have an app:destination="@id/fragmentB" on an action if you don't want to navigate to a new instance of fragmentB (since that's what app:destination does). Therefore you can use:

```<code><action
    android:id="@+id/action_fragmentD_to_fragmentB"
    app:popUpTo="@+id/fragmentB" />
</code>```

This is identical to calling popBackStack(R.id.fragmentB, false) - i.e., pop back to fragmentB, but don't pop fragmentB itself.

Body:
I have fragments: A, B, C, D. I navigate A -> B . Fragment B gets and saves state from arguments. Then I navigate B -> C. And then C -> D. When I call two times findNavController().popBackStack() I get correct behavior: D -> B and B still has correct state. It works because fragment B has never been destroyed, just its view. And then view is recreated when coming back. But calling two times popBackStack() isn't recommended action. We should instead use the action with app:popUpTo and app:popUpToInclusive="true":

<action
    android:id="@+id/action_fragmentD_to_fragmentB"
    app:destination="@id/fragmentB"
    app:popUpTo="@+id/fragmentB"
    app:popUpToInclusive="true" />

But it forces fragment B to be destroyed completely and then recreated. Bu with no previous state.

In other words I want to achieve the same behavior as with Activities when used FLAG_ACTIVITY_CLEAR_TOP + FLAG_ACTIVITY_SINGLE_TOP: https://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_CLEAR_TOP

Body:
There's no requirement to have an app:destination="@id/fragmentB" on an action if you don't want to navigate to a new instance of fragmentB (since that's what app:destination does). Therefore you can use:

<action
    android:id="@+id/action_fragmentD_to_fragmentB"
    app:popUpTo="@+id/fragmentB" />

This is identical to calling popBackStack(R.id.fragmentB, false) - i.e., pop back to fragmentB, but don't pop fragmentB itself.


答:
The first time the code enters the while (startOfCheckIndex < endOfCheckIndex) {
startOfCheckIndex  is 1 and endOfCheckIndex is 3
That means possibleAnswer is 10 + 7 = 17.
newSum is 10 and sum is 20
That means that neither

if (possibleAnswer === newSum) {

or

} else if (sum < newSum) {

are true. Resulting in startOfCheckIndex never getting changed.

In turn, while (startOfCheckIndex < endOfCheckIndex) { will always be true, resulting in an infinite loop.

You need to add an else clause or some other leaving condition.

Here is an example to demonstrate the issue.

let loopRestriction = 100

function findTriad(numbers, sum) {
  for (let i = 0; i < numbers.length - 1; i++) {
    const firstNumber = numbers[i];
    const newSum = sum - firstNumber;
    let startOfCheckIndex = i + 1;
    const endOfCheckIndex = numbers.length - 1;

    while (startOfCheckIndex < endOfCheckIndex) {

      const possibleAnswer = numbers[startOfCheckIndex] + numbers[endOfCheckIndex];
      if (loopRestriction-- <= 0) {
        console.log("Stuck in while loop for atleast 100 iterations.")
        break
      }
      console.log({
        startOfCheckIndex,
        endOfCheckIndex,
        possibleAnswer,
        sum,
        newSum
      })

      if (possibleAnswer === newSum) {
        return [
          numbers[i],
          numbers[startOfCheckIndex],
          numbers[endOfCheckIndex]
        ];
      } else if (sum < newSum) {
        startOfCheckIndex++;
      }
    }
  }
  return ["N/A"];
}

function logFindTriad(numbers, sum) {
  const answer = findTriad(numbers, sum);

  console.log("Sum required: " + sum);
  console.log("Numbers given: " + numbers.join(", "));
  console.log("Found: " + answer.join(", ") + "\n");
}

logFindTriad([10, 15, 3, 7], 20);```

Title: Function isn't giving response


问:
What is the difference between asDouble() and doubleValue() in Jackson API?
I am little confused while using these methods. If both methods return same value then why Jackson API has provided two different methods?</p>

答:
According to the jackson-databind 2.2.0 API

public double asDouble()

Method that will try to convert value of this node to a Java double. Numbers are coerced using default Java rules; booleans convert to 0.0 (false) and 1.0 (true), and Strings are parsed using default Java language integer parsing rules.
  If representation can not be converted to an int (including structured types like Objects and Arrays), default value of 0.0 will be returned; no exceptions are thrown.

public double doubleValue()

Returns 64-bit floating point (double) value for this node, if and only if this node is numeric (isNumber() returns true). For other types returns 0.0. For integer values, conversion is done using coercion; this may result in overflows with BigInteger values.

Example:

```<code>public static void main(String[] args) throws IOException {
    String jsonString = "{\"name\":\"Altaf Java\",\"salary\":\"12345.67\",\"amount\":98765.43}";
    System.out.println(jsonString);
    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode rootNode = objectMapper.readTree(jsonString);
    JsonNode salaryNode = rootNode.get("salary");
    System.out.println("salaryNode.isNumber()=" + salaryNode.isNumber());
    System.out.println("salaryNode.asDouble()="+salaryNode.asDouble());
    System.out.println("salaryNode.doubleValue()="+salaryNode.doubleValue());
    JsonNode amountNode = rootNode.get("amount");
    System.out.println("amountNode.isNumber()=" + amountNode.isNumber());
    System.out.println("amountNode.asDouble()=" + amountNode.asDouble());
    System.out.println("amountNode.doubleValue()=" + amountNode.doubleValue());
}
</code>```

Output:

```<code>{"name":"Altaf Java","salary":"12345.67","amount":98765.43}
salaryNode.isNumber()=false
salaryNode.asDouble()=12345.67
salaryNode.doubleValue()=0.0
amountNode.isNumber()=true
amountNode.asDouble()=98765.43
amountNode.doubleValue()=98765.43
</code>```

As you can see here, salaryNode value is String type. Means it is not Number. Hence doubleValue() method returns default value 0.0 but amountNode value is Number. Hence doubleValue() method returns its original value 98765.43

Body:
According to the jackson-databind 2.2.0 API

public double asDouble()

Method that will try to convert value of this node to a Java double. Numbers are coerced using default Java rules; booleans convert to 0.0 (false) and 1.0 (true), and Strings are parsed using default Java language integer parsing rules.
  If representation can not be converted to an int (including structured types like Objects and Arrays), default value of 0.0 will be returned; no exceptions are thrown.

public double doubleValue()

Returns 64-bit floating point (double) value for this node, if and only if this node is numeric (isNumber() returns true). For other types returns 0.0. For integer values, conversion is done using coercion; this may result in overflows with BigInteger values.

Example:

public static void main(String[] args) throws IOException {
    String jsonString = "{\"name\":\"Altaf Java\",\"salary\":\"12345.67\",\"amount\":98765.43}";
    System.out.println(jsonString);
    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode rootNode = objectMapper.readTree(jsonString);
    JsonNode salaryNode = rootNode.get("salary");
    System.out.println("salaryNode.isNumber()=" + salaryNode.isNumber());
    System.out.println("salaryNode.asDouble()="+salaryNode.asDouble());
    System.out.println("salaryNode.doubleValue()="+salaryNode.doubleValue());
    JsonNode amountNode = rootNode.get("amount");
    System.out.println("amountNode.isNumber()=" + amountNode.isNumber());
    System.out.println("amountNode.asDouble()=" + amountNode.asDouble());
    System.out.println("amountNode.doubleValue()=" + amountNode.doubleValue());
}

Output:

{"name":"Altaf Java","salary":"12345.67","amount":98765.43}
salaryNode.isNumber()=false
salaryNode.asDouble()=12345.67
salaryNode.doubleValue()=0.0
amountNode.isNumber()=true
amountNode.asDouble()=98765.43
amountNode.doubleValue()=98765.43

As you can see here, salaryNode value is String type. Means it is not Number. Hence doubleValue() method returns default value 0.0 but amountNode value is Number. Hence doubleValue() method returns its original value 98765.43


问:
new Date().getFullYear() in React
I'm trying to display a current year in footer and trying to figure out how to get the current year React way?
Is there a way to use new Date().getFullYear()?</p>

答:
exemple using hooks

u cant use react useState to change value of variable date to print in DOM and useEffect to show when DOM REAdy

after caled {date} in jsx to print em docuemt loaded

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

export default function Footer() {

    const [date , setDate] = useState();

    const getYear = () =>  setDate(new Date().getFullYear())

    useEffect(() => {
        getYear();
    }, [])
  return (
    <>
     © Rogerio Orioli - {date}
    </>
  );
}
</code>```

Title: new Date().getFullYear() in React

Body:
exemple using hooks

u cant use react useState to change value of variable date to print in DOM and useEffect to show when DOM REAdy

after caled {date} in jsx to print em docuemt loaded

import React, {useState, useEffect} from 'react';

export default function Footer() {

    const [date , setDate] = useState();

    const getYear = () =>  setDate(new Date().getFullYear())

    useEffect(() => {
        getYear();
    }, [])
  return (
    <>
     &copy; Rogerio Orioli - {date}
    </>
  );
}


答:
For "Date" objects, you can't cut like that. I'm sure there's an R base version, but lubridate can make your life easier, if you don't care too much about the how or if you don't want to learn to do things from scratch.

```<code>library(lubridate)

Decade <- format(floor_date(Release, years(x=10)), "%Y")
</code>```

Title: How to transform data in Column Date using cut function in R

Body:
For "Date" objects, you can't cut like that. I'm sure there's an R base version, but lubridate can make your life easier, if you don't care too much about the how or if you don't want to learn to do things from scratch.

library(lubridate)

Decade <- format(floor_date(Release, years(x=10)), "%Y")


问:
Posting to WCF Service sending NULL values
I'm trying to post to my WCF Service from an iPhone app. I have the app posting to the service and trying to send data in the form of a service data contract in XML like below:

```<code>NSData *myPostData = [[NSString stringWithFormat:@"<AddMediaItem xmlns='http://www.example.com'><Item xmlns:a='http://www.example.com/MediaItem'><a:MediaType>iPhone</a:MediaType><a:Description>Description</a:Description><a:Name>Test</a:Name><a:ImageType>JPEG</a:ImageType></Item></AddMediaItem>"] dataUsingEncoding:NSUTF8StringEncoding];

NSMutableData *myMutablePostData = [NSMutableData dataWithData:myPostData];

[request setPostBody:myMutablePostData];
[request setRequestMethod:@"POST"];
[request addRequestHeader:@"Content-Type" value:@"application/xml"];

[request setDidFinishSelector:@selector(uploadFinished:)];
[request setDidFailSelector:@selector(uploadFailed:)];
[request setDelegate:self];
[request startAsynchronous];
</code>```

For testing purposes, I've setup my service to return the data contract that I send to the service. However, when it returns, some of the values seem to be NULLs although from the code above, I am giving them values.

What also seems strange is that the Name data member always has a value, but the other 3 I'm sending return NULL or with the correct values based on the order they appear in the XML I post to the service.

Below is the code for my service contract:

```<code>[ServiceContract(Namespace = "http://www.example.com")]
public interface IImageDiaryService
{

    [OperationContract]
    [WebInvoke(UriTemplate = "AddMediaItem", Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml)]
    MediaItem AddMediaItem(MediaItem Item);

}
</code>```

Below is my code for my MediaItem data contract:

```<code>[DataContract(Namespace = "http://www.example.com/MediaItem")]
public class MediaItem
{

    [DataMember]
    public Int32 Id { get; set; }

    [DataMember]
    public String Name { get; set; }

    [DataMember]
    public String Description { get; set; }

    [DataMember]
    public String ImageData { get; set; }

    [DataMember]
    public String ImageType { get; set; }

    [DataMember]
    public String MediaType { get; set; }

}
</code>```

Do let me know if you need any further code.

Any help is much appreciated.

答:
The order is important in data contracts - by default the data members are ordered alphabetically, but you can override it by using the Order property of [DataMember]. Try reordering the fields and you'll get the values populated correctly</p>

```<code><AddMediaItem xmlns='http://www.example.com'>
  <Item xmlns:a='http://www.example.com/MediaItem'>
    <a:Description>Description</a:Description>
    <a:ImageType>JPEG</a:ImageType>
    <a:MediaType>iPhone</a:MediaType>
    <a:Name>Test</a:Name>
  </Item>
</AddMediaItem>
</code>```

Body:
I'm trying to post to my WCF Service from an iPhone app. I have the app posting to the service and trying to send data in the form of a service data contract in XML like below:

NSData *myPostData = [[NSString stringWithFormat:@"<AddMediaItem xmlns='http://www.example.com'><Item xmlns:a='http://www.example.com/MediaItem'>iPhoneDescriptionTestJPEG</Item></AddMediaItem>"] dataUsingEncoding:NSUTF8StringEncoding];

NSMutableData *myMutablePostData = [NSMutableData dataWithData:myPostData];

[request setPostBody:myMutablePostData];
[request setRequestMethod:@"POST"];
[request addRequestHeader:@"Content-Type" value:@"application/xml"];

[request setDidFinishSelector:@selector(uploadFinished:)];
[request setDidFailSelector:@selector(uploadFailed:)];
[request setDelegate:self];
[request startAsynchronous];

For testing purposes, I've setup my service to return the data contract that I send to the service. However, when it returns, some of the values seem to be NULLs although from the code above, I am giving them values.

What also seems strange is that the Name data member always has a value, but the other 3 I'm sending return NULL or with the correct values based on the order they appear in the XML I post to the service.

Below is the code for my service contract:

[ServiceContract(Namespace = "http://www.example.com")]
public interface IImageDiaryService
{

    [OperationContract]
    [WebInvoke(UriTemplate = "AddMediaItem", Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml)]
    MediaItem AddMediaItem(MediaItem Item);

}

Below is my code for my MediaItem data contract:

[DataContract(Namespace = "http://www.example.com/MediaItem")]
public class MediaItem
{

    [DataMember]
    public Int32 Id { get; set; }

    [DataMember]
    public String Name { get; set; }

    [DataMember]
    public String Description { get; set; }

    [DataMember]
    public String ImageData { get; set; }

    [DataMember]
    public String ImageType { get; set; }

    [DataMember]
    public String MediaType { get; set; }

}

Do let me know if you need any further code.

Any help is much appreciated.

Body:
The order is important in data contracts - by default the data members are ordered alphabetically, but you can override it by using the Order property of [DataMember]. Try reordering the fields and you'll get the values populated correctly

<AddMediaItem xmlns='http://www.example.com'>
  <Item xmlns:a='http://www.example.com/MediaItem'>
    <a:Description>Description</a:Description>
    <a:ImageType>JPEG</a:ImageType>
    <a:MediaType>iPhone</a:MediaType>
    <a:Name>Test</a:Name>
  </Item>
</AddMediaItem>


问:
Why does include statement return an error that basically states that the language (C++) has a bug?
Some info: I am a person who has gotten into C++ development recently, which means i really don't know how to troubleshoot things like this. You have been warned.

Question: See title

I believe I have what looks to me to be a compiler error, but have not been able to find anything like it anywhere on stack overflow.

Problematic code:

```<code>#include <map> // This is the line that triggered the error.

using namespace std;

class studySet
{

public:

    studySet(int t, double v, string n, string a,map<int, string[2]> s)
    {

        type = t;
        version = v;
        name = n;
        author = a;
        setTerms = s;

    }
    int getType()
    {

        return type;

    }
    double getVersion()
    {

        return version;

    }
    string getName()
    {

        return name;

    }
    string getAuthor()
    {

        return author;

    }

    void study()
    {

    }

private:

    int type;
    double version;
    string name;
    string author;
    map<int, string[2]> setTerms;

};
</code>```

Error shown:

```<code>No viable overloaded '=' //Shown in a file included from above code.
</code>```

OS: MacOS 10.14.3 Mojave

IDE: Xcode

Compiler: IDK, whatever Xcode uses.

Please comment if you need more code from me as i am fairly new to stack overflow as well.

答:
std::map is an allocator-aware container. The assignment operator of such a container has the precondition that the element type, in this case std::pair<const int, std::string[2]>, is CopyAssignable.

However, std::string[2] is an array and array types cannot be assigned to at all.

Therefore you cannot use assignment of allocator-aware containers with std::string[2]. In general built-in array types don't really work in containers.

Built-in arrays often behave in very unintuitive ways. So, I suggest that you use std::array instead, which behaves as one would expect, i.e. instead of

```<code>map<int, string[2]>
</code>```

use

```<code>map<int, array<string, 2>>
</code>```

This requires #include<array>.

Body:
Some info: I am a person who has gotten into C++ development recently, which means i really don't know how to troubleshoot things like this. You have been warned.

Question: See title

I believe I have what looks to me to be a compiler error, but have not been able to find anything like it anywhere on stack overflow.

Problematic code:

#include <map> // This is the line that triggered the error.

using namespace std;

class studySet
{

public:

    studySet(int t, double v, string n, string a,map<int, string[2]> s)
    {

        type = t;
        version = v;
        name = n;
        author = a;
        setTerms = s;

    }
    int getType()
    {

        return type;

    }
    double getVersion()
    {

        return version;

    }
    string getName()
    {

        return name;

    }
    string getAuthor()
    {

        return author;

    }

    void study()
    {

    }

private:

    int type;
    double version;
    string name;
    string author;
    map<int, string[2]> setTerms;

};

Error shown:

No viable overloaded '=' //Shown in a file included from above code.

OS: MacOS 10.14.3 Mojave

IDE: Xcode

Compiler: IDK, whatever Xcode uses.

Please comment if you need more code from me as i am fairly new to stack overflow as well.

Body:
std::map is an allocator-aware container. The assignment operator of such a container has the precondition that the element type, in this case std::pair<const int, std::string[2]>, is CopyAssignable.

However, std::string[2] is an array and array types cannot be assigned to at all.

Therefore you cannot use assignment of allocator-aware containers with std::string[2]. In general built-in array types don't really work in containers.

Built-in arrays often behave in very unintuitive ways. So, I suggest that you use std::array instead, which behaves as one would expect, i.e. instead of

map<int, string[2]>

use

map<int, array<string, 2>>

This requires #include<array>.


问:
Initializing a vector class member in C++
I'm trying to set length and initialize a vector member of a class, but it seems it's only possible if initializing line is out of class.

```<code>//a vector, out of class set size to 5. initialized each value to Zero
vector<double> vec(5,0.0f);//its ok

class Bird{

public:
    int id;
    //attempt to init is not possible if a vector a class of member
    vector<double> vec_(5, 0.0f);//error: expected a type specifier
}
</code>```

How can I do this inside the class?

答:
As Franck mentioned, the modern c++ way of initializing class member vector is </p>

```<code>vector<double> vec_ = vector<double>(5, 0.0f);//vector of size 5, each with value 0.0

</code>```

<p>Note that for vectors of int, float, double etc (AKA in built types) we do not need to zero initialize. So better way to do this is </p>

```<code>vector<double> vec_ = vector<double>(5);//vector of size 5, each with value 0.0

</code>```

Body:
I'm trying to set length and initialize a vector member of a class, but it seems it's only possible if initializing line is out of class.

//a vector, out of class set size to 5. initialized each value to Zero
vector<double> vec(5,0.0f);//its ok

class Bird{

public:
    int id;
    //attempt to init is not possible if a vector a class of member
    vector<double> vec_(5, 0.0f);//error: expected a type specifier
}

How can I do this inside the class?

Body:
As Franck mentioned, the modern c++ way of initializing class member vector is

vector<double> vec_ = vector<double>(5, 0.0f);//vector of size 5, each with value 0.0

Note that for vectors of int, float, double etc (AKA in built types) we do not need to zero initialize. So better way to do this is

vector<double> vec_ = vector<double>(5);//vector of size 5, each with value 0.0


问:
Android Studio's Properties Window Missing
I have no idea where the properties window went. As you can see it should be under Component Tree, but it is not and there is a gray area to the right of it. any ideas?

答:
An updated answer for Android Studio 3.5.3:

Android Studio Screenshot

1) Open a layout file such as the default "activity_main.xml" in the app/res/layout folder (yellow oval).

2) Click on Design view (green oval).

3) If the Attributes window is closed, click on its tab to open it (red oval).

4) If the Attributes pane says "No component selected" click on an element such as the TextView.  The attributes of that element should now be displayed.


问:
I can not get it to display info by month. Is it the GROUP BY or my LOOP that's messed up?
I need to display the amount of money used by each PAYMENTMETHOD by MONTH.

EXAMPLE:

```<code>    JANUARY RENTALS
         CASH    $300
         VISA    $200
    TOTAL: $500
</code>```

I have tried many different GROUP BY statements and I have tried DISTINCT, but I keep getting the error "NOT A GROUP BY EXPRESSION".
The code (without a GROUP BY expression) displays a long list that repeats the same months. I do not know for sure if the problem is even the GROUP BY or if it's how I have the LOOP set up.

NOTE: All of the data is from the same year, but the date is in the format of 16-DEC-04
This is the code:

```<code>SET SERVEROUTPUT ON;

CREATE OR REPLACE FUNCTION NameMonth (MonthNum INT)
        RETURN VARCHAR2 AS
        Month_Name VARCHAR2(9) := 'Default';
    BEGIN
        CASE
        WHEN MonthNum = 1 THEN  Month_Name := 'January';
        WHEN MonthNum = 2 THEN  Month_Name := 'February';
        WHEN MonthNum = 3 THEN  Month_Name := 'March';
        WHEN MonthNum = 4 THEN  Month_Name := 'April';
        WHEN MonthNum = 5 THEN  Month_Name := 'May';
        WHEN MonthNum = 6 THEN  Month_Name := 'June';
        WHEN MonthNum = 7 THEN  Month_Name := 'July';
        WHEN MonthNum = 8 THEN  Month_Name := 'August';
        WHEN MonthNum = 9 THEN  Month_Name := 'September';
        WHEN MonthNum = 10 THEN  Month_Name := 'October';
        WHEN MonthNum = 11 THEN  Month_Name := 'November';
        WHEN MonthNum = 12 THEN  Month_Name := 'December';
        END CASE;

        RETURN Month_Name;
    END;
 /

 DECLARE
    CURSOR cNameOfMonth IS
        SELECT NameMonth(EXTRACT(MONTH FROM RENTAL.RENTDATE)) AS RentMonth, RENTAL.PAYMENTMETHOD, RENTITEM.RENTFEE
        FROM ALLPOWDER.RENTAL, ALLPOWDER.RENTITEM
        WHERE RENTAL.RENTID = RENTITEM.RENTID
        GROUP BY EXTRACT(MONTH FROM RENTAL.RENTDATE)
   -- I've also tried NameMonth(EXTRACT(MONTH FROM RENTAL.RENTDATE)) and just RENTAL.RENTDATE
        ORDER BY RentMonth;

    Rental_Rec cNameOfMonth%ROWTYPE;

BEGIN
    OPEN cNameOfMonth;
    LOOP
        FETCH cNameOfMonth INTO Rental_Rec;
        EXIT WHEN cNameOfMonth%NOTFOUND;

        DBMS_OUTPUT.NEW_LINE;
        DBMS_OUTPUT.PUT_LINE(Rental_Rec.RentMonth || ' Rentals ----------------');
    END LOOP;
    CLOSE cNameOfMonth;
END;
/
</code>```

答:
This is your query with proper JOIN syntax and table aliases.  The problem columns are identified:

```<code>    SELECT NameMonth(EXTRACT(MONTH FROM R.RENTDATE)) AS RentMonth,
           R.PAYMENTMETHOD, RI.RENTFEE
-----------^  --------------^
    FROM ALLPOWDER.RENTAL R JOIN
         ALLPOWDER.RENTITEM RI
         ON R.RENTID = RI.RENTID
    GROUP BY EXTRACT(MONTH FROM R.RENTDATE)
    ORDER BY RentMonth;
</code>```

It is quite unclear what you want to do.  You have GROUP BY with no aggregation functions, so that is suspicious.  Some possibilities:

You don't intend an aggregation query.  So remove GROUP BY.

You want one row per month.  Use aggregation functions on the other columns.

You want one row per month and payment method.  Use an aggregation function on RENTFEE.

Something else.

Body:
I need to display the amount of money used by each PAYMENTMETHOD by MONTH.

EXAMPLE:

    JANUARY RENTALS
         CASH    $300
         VISA    $200
    TOTAL: $500

I have tried many different GROUP BY statements and I have tried DISTINCT, but I keep getting the error "NOT A GROUP BY EXPRESSION".
The code (without a GROUP BY expression) displays a long list that repeats the same months. I do not know for sure if the problem is even the GROUP BY or if it's how I have the LOOP set up.

NOTE: All of the data is from the same year, but the date is in the format of 16-DEC-04
This is the code:

SET SERVEROUTPUT ON;

CREATE OR REPLACE FUNCTION NameMonth (MonthNum INT)
        RETURN VARCHAR2 AS
        Month_Name VARCHAR2(9) := 'Default';
    BEGIN
        CASE
        WHEN MonthNum = 1 THEN  Month_Name := 'January';
        WHEN MonthNum = 2 THEN  Month_Name := 'February';
        WHEN MonthNum = 3 THEN  Month_Name := 'March';
        WHEN MonthNum = 4 THEN  Month_Name := 'April';
        WHEN MonthNum = 5 THEN  Month_Name := 'May';
        WHEN MonthNum = 6 THEN  Month_Name := 'June';
        WHEN MonthNum = 7 THEN  Month_Name := 'July';
        WHEN MonthNum = 8 THEN  Month_Name := 'August';
        WHEN MonthNum = 9 THEN  Month_Name := 'September';
        WHEN MonthNum = 10 THEN  Month_Name := 'October';
        WHEN MonthNum = 11 THEN  Month_Name := 'November';
        WHEN MonthNum = 12 THEN  Month_Name := 'December';
        END CASE;

        RETURN Month_Name;
    END;
 /

 DECLARE
    CURSOR cNameOfMonth IS
        SELECT NameMonth(EXTRACT(MONTH FROM RENTAL.RENTDATE)) AS RentMonth, RENTAL.PAYMENTMETHOD, RENTITEM.RENTFEE
        FROM ALLPOWDER.RENTAL, ALLPOWDER.RENTITEM
        WHERE RENTAL.RENTID = RENTITEM.RENTID
        GROUP BY EXTRACT(MONTH FROM RENTAL.RENTDATE)
   -- I've also tried NameMonth(EXTRACT(MONTH FROM RENTAL.RENTDATE)) and just RENTAL.RENTDATE
        ORDER BY RentMonth;

    Rental_Rec cNameOfMonth%ROWTYPE;

BEGIN
    OPEN cNameOfMonth;
    LOOP
        FETCH cNameOfMonth INTO Rental_Rec;
        EXIT WHEN cNameOfMonth%NOTFOUND;

        DBMS_OUTPUT.NEW_LINE;
        DBMS_OUTPUT.PUT_LINE(Rental_Rec.RentMonth || ' Rentals ----------------');
    END LOOP;
    CLOSE cNameOfMonth;
END;
/

Body:
This is your query with proper JOIN syntax and table aliases.  The problem columns are identified:

    SELECT NameMonth(EXTRACT(MONTH FROM R.RENTDATE)) AS RentMonth,
           R.PAYMENTMETHOD, RI.RENTFEE
-----------^  --------------^
    FROM ALLPOWDER.RENTAL R JOIN
         ALLPOWDER.RENTITEM RI
         ON R.RENTID = RI.RENTID
    GROUP BY EXTRACT(MONTH FROM R.RENTDATE)
    ORDER BY RentMonth;

It is quite unclear what you want to do.  You have GROUP BY with no aggregation functions, so that is suspicious.  Some possibilities:

You don't intend an aggregation query.  So remove GROUP BY.

You want one row per month.  Use aggregation functions on the other columns.

You want one row per month and payment method.  Use an aggregation function on RENTFEE.

Something else.


问:
How does the client knows which transport protocol to use?
Let's assume that I start a server at one of the computers in my private network (192.168.10.10:9900).

Now when making a request from some other computer in the same network, how does the client computer (OS?) knows which protocol to use / which protocol the server follows ? [TCP or UDP]

EDIT: As mentioned in the answers, I was basically looking for a default protocol which will be used by the client in the absence of any transport protocol information.

答: Normally, the client computer will use the TCP protocol as default. If you start the server using UDP protocol mode, then when you use curl -XGET 192.168.10.10:9900/test-page, it will give you back an curl: (7) Failed to connect to 192.168.10.10 port 9900: Connection refused error. You can try it, use the nc -lvp 9900 -u, it will give you that result.


问:
How to stop a loop in powershell
This script is supposed to create a file or files and if there is more  than 1 put 1 after name then 2 then 3 and so on.. and if its  0 or less to say: You must select at least one file to be created</p>

```<code>$Filename=Read-Host "Enter desired filename"
$NewFilePath=Read-Host "Enter desired path"
$AmtOfFiles=Read-Host "Enter desired amount of files"

if($AmtOfFiles -ge 1){
for($AmtOfFiles=1;$AmtOfFiles -gt 0){
New-Item -ItemType file -Path $NewFilePath -Name $Filename$i
$i++
}
}
else{Write-Output "You must select at least one file to be created.”}```
</code>```

答:
You can get help on the for command from PowerShell by typing:

```<code>get-help about_for
</code>```

You can also see this Microsoft site for the same info.

The for command has 3 parameters in the parens, not the two you are using in your example.

```<code>for (<init>; <condition>; <repeat>)
{<statement list>}
</code>```

You need to use a control variable, like $i, in the definition of the For.  So modifying your code, it would look like this:

```<code>If($AmtOfFiles -ge 1){
    for($i=1;$i -lt $AmtOfFiles;$i++)
    {
        New-Item -ItemType file -Path $NewFilePath -Name $Filename$i
    }
}
else{
    Write-Output "You must select at least one file to be created.”
}
</code>```

Please read the documentation for more info on how to use for loops properly.  You'll be happy you did.

Hope this helps.

Title: How to stop a loop in powershell

Body:
This script is supposed to create a file or files and if there is more  than 1 put 1 after name then 2 then 3 and so on.. and if its  0 or less to say: You must select at least one file to be created

$Filename=Read-Host "Enter desired filename"
$NewFilePath=Read-Host "Enter desired path"
$AmtOfFiles=Read-Host "Enter desired amount of files"

if($AmtOfFiles -ge 1){
for($AmtOfFiles=1;$AmtOfFiles -gt 0){
New-Item -ItemType file -Path $NewFilePath -Name $Filename$i
$i++
}
}
else{Write-Output "You must select at least one file to be created.”}```

Body:
You can get help on the for command from PowerShell by typing:

get-help about_for

You can also see this Microsoft site for the same info.

The for command has 3 parameters in the parens, not the two you are using in your example.

for (<init>; <condition>; <repeat>)
{<statement list>}

You need to use a control variable, like $i, in the definition of the For.  So modifying your code, it would look like this:

If($AmtOfFiles -ge 1){
    for($i=1;$i -lt $AmtOfFiles;$i++)
    {
        New-Item -ItemType file -Path $NewFilePath -Name $Filename$i
    }
}
else{
    Write-Output "You must select at least one file to be created.”
}

Please read the documentation for more info on how to use for loops properly.  You'll be happy you did.

Hope this helps.


问:
What does "return a" in this recursive combinations function does?
I went over this function over and over in Chrome debugger and still can't understand what return a does. Thanks for helping me out!

Here's some clarification:
I understand the first round. The anonymous function gets called with the following parameters:

active = "", rest = "abc", a = []

It then calls itself til rest is empty, when it populates the a array:

active = "abc", rest = "", a = ["abc"]

At this point we arrive to return a, and the debugger jumps to the second fn call in the else statement instead of the first if statement. The parameters already look like this:

active = "ab", rest = "c", a = ["abc"]

This is the part I don't understand at all. I know the recursion is only over when active and rest is empty, but after return a the if statements don't even get checked in the debugger, it just highlights the mentioned second function call, and at that point "c" is already assigned to rest. I guess the reason why this function doesn't produce duplicates also lies here, but that might be another question if not. Anyway, thanks again for the help!

```<code>combinations("abc");

function combinations(str) {
    var fn = function(active, rest, a) {
        if (!active && !rest)
            return;
        if (!rest) {
            a.push(active);
        } else {
            fn(active + rest[0], rest.slice(1), a);
            fn(active, rest.slice(1), a);
        }
        return a;
    }
    return fn("", str, []);
}
</code>```

答:
While I understand that this question is primarily about how that particular recursive implementation works (and there's already an excellent answer to that!), I think it's worth pointing out that it's an odd implementation, and something like this is probably cleaner:

const combinations = (str, active = '') =>
  str .length == 0
    ? active .length == 0
      ? []
      : [active]
    : [
        ... combinations (str .slice (1), active + str [0]),
        ... combinations (str .slice (1), active)
      ]

console .log (combinations ('abc'))```

Body:
I went over this function over and over in Chrome debugger and still can't understand what return a does. Thanks for helping me out!

Here's some clarification:
I understand the first round. The anonymous function gets called with the following parameters:

active = "", rest = "abc", a = []

It then calls itself til rest is empty, when it populates the a array:

active = "abc", rest = "", a = ["abc"]

At this point we arrive to return a, and the debugger jumps to the second fn call in the else statement instead of the first if statement. The parameters already look like this:

active = "ab", rest = "c", a = ["abc"]

This is the part I don't understand at all. I know the recursion is only over when active and rest is empty, but after return a the if statements don't even get checked in the debugger, it just highlights the mentioned second function call, and at that point "c" is already assigned to rest. I guess the reason why this function doesn't produce duplicates also lies here, but that might be another question if not. Anyway, thanks again for the help!

combinations("abc");

function combinations(str) {
    var fn = function(active, rest, a) {
        if (!active && !rest)
            return;
        if (!rest) {
            a.push(active);
        } else {
            fn(active + rest[0], rest.slice(1), a);
            fn(active, rest.slice(1), a);
        }
        return a;
    }
    return fn("", str, []);
}