问:
Vue js keep previous element open using the same select
this is my first Vue.js project and I'm using it via CDN just to list some data from DB. I have nested v-for to list users and their posts. Inside of each primary v-for I have a select loading posts titles with another v-for. When I select a title I want to open the corresponding post.

It works almost 100%. My problem is that when I select a new option (title) in a second user, the first post that was open is closing. So it alternates between one and another.

I created an element using another v-for to list all posts but created a condition to display only the corresponding one with its title.

And I tried to create some other condition along with the existing ones, using true if open but it didn't work. Is it possible to reuse the same element for this case?

I remember it was easy to do that using filters when I worked with angularjs. Is there anything similar in this case?

```<code><div v-for="(item, index) in hosters" v-bind:key="item.id" class="col-md-6 mb-50">
    <h4 class="mb-0">{{ item.name }} {{ item.lastname }}</h4>

    <div class="tour-options-select">
        <select id="select-suggestions" name="tour-options-dropdown"
                v-model="selected" class="tour-options-dropdown"
                @change="showTour = selected">

            <option v-for="(tour, key) in item.tours" :key="key" :value="tour.tourID">
                {{ tour.title }}
            </option>
        </select>
    </div>

    // here each post is listed by selecting its title
    <div v-for="(tour, key) in item.tours" v-if="showTour == tour.tourID" class="tour-suggestions">
        <div class="tour-list">
          <div class="tour-list-title">
             <p>{{ tour.title }}</p>
          </div>
          <div class="tour-list-description">
             <p>
                {{ tour.description }}
             </p>
          </div>
          <div class="tour-list-pics">
             <ul class="pics-list">
                <li v-for="image in tour.images">
                   <div class="pics-list-image-container"
                  v-bind:style="{'background-image': 'url(http://localhost/tours/'+image.image + ')' }"
                  @click="openModal = true, showModal(image.image)"></div>
                </li>
             </ul>
          </div>
       </div>
       <div @click="showTour = false" class="close-suggestions">
          <span>X</span>
       </div>
    </div>

</div>
</code>```

答:
new Vue({
  el: '#app',
  data() {
    return {
      selected: {},
      toursObj: {},
      hosters: [{
          id: "0",
          name: "name0",
          lastname: "lastname0",
          tours: [{
              tourID: "tourID0_0",
              title: "title0_0",
              description: "description0_0",
            },
            {
              tourID: "tourID0_1",
              title: "title0_1",
              description: "description0_1",
            },
            {
              tourID: "tourID0_1",
              title: "title0_1",
              description: "description0_1",
            },
          ],
        },
        {
          id: "1",
          name: "name1",
          lastname: "lastname1",
          tours: [{
              tourID: "tourID1_0",
              title: "title1_0",
              description: "description1_0",
            },
            {
              tourID: "tourID1_1",
              title: "title1_1",
              description: "description1_1",
            },
            {
              tourID: "tourID1_1",
              title: "title1_1",
              description: "description1_1",
            },
          ],
        },
      ],
    }
  },
  template: `

{{ item.name }} {{ item.lastname }}

        <select :id="'select-suggestions' + item.id" name="tour-options-dropdown" v-model="selected[item.id]" class="tour-options-dropdown">
            <option v-for="(tour, key) in item.tours" :key="key" :value="tour.tourID">
                {{ tour.title }}
            </option>
        </select>

{{ toursObj[selected[item.id]].title }}

                {{ toursObj[selected[item.id]].description }}

       <button type="button" @click="closeTour(item.id)">
          X

  `,
  created() {
    this.setToursObj();
  },
  methods: {
    setToursObj() {
      const TOURS_OBJ = {};
      this.hosters.forEach(hoster => {
        hoster.tours.forEach(tour => {
          TOURS_OBJ[tour.tourID] = tour;
        });
      });
      this.toursObj = TOURS_OBJ;
    },
    closeTour(id) {
      this.selected[id] = undefined;
    },
  },
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app"></div></code>```

Body:
this is my first Vue.js project and I'm using it via CDN just to list some data from DB. I have nested v-for to list users and their posts. Inside of each primary v-for I have a select loading posts titles with another v-for. When I select a title I want to open the corresponding post.

It works almost 100%. My problem is that when I select a new option (title) in a second user, the first post that was open is closing. So it alternates between one and another.

I created an element using another v-for to list all posts but created a condition to display only the corresponding one with its title.

And I tried to create some other condition along with the existing ones, using true if open but it didn't work. Is it possible to reuse the same element for this case?

I remember it was easy to do that using filters when I worked with angularjs. Is there anything similar in this case?

{{ item.name }} {{ item.lastname }}

        <select id="select-suggestions" name="tour-options-dropdown"
                v-model="selected" class="tour-options-dropdown"
                @change="showTour = selected">

            <option v-for="(tour, key) in item.tours" :key="key" :value="tour.tourID">
                {{ tour.title }}
            </option>
        </select>

    // here each post is listed by selecting its title

{{ tour.title }}

                {{ tour.description }}

          X

Body:
new Vue({
  el: '#app',
  data() {
    return {
      selected: {},
      toursObj: {},
      hosters: [{
          id: "0",
          name: "name0",
          lastname: "lastname0",
          tours: [{
              tourID: "tourID0_0",
              title: "title0_0",
              description: "description0_0",
            },
            {
              tourID: "tourID0_1",
              title: "title0_1",
              description: "description0_1",
            },
            {
              tourID: "tourID0_1",
              title: "title0_1",
              description: "description0_1",
            },
          ],
        },
        {
          id: "1",
          name: "name1",
          lastname: "lastname1",
          tours: [{
              tourID: "tourID1_0",
              title: "title1_0",
              description: "description1_0",
            },
            {
              tourID: "tourID1_1",
              title: "title1_1",
              description: "description1_1",
            },
            {
              tourID: "tourID1_1",
              title: "title1_1",
              description: "description1_1",
            },
          ],
        },
      ],
    }
  },
  template: `
  <div>
    <div v-for="(item, index) in hosters" v-bind:key="item.id" class="col-md-6 mb-50">
    <h4 class="mb-0">{{ item.name }} {{ item.lastname }}</h4>

    <div class="tour-options-select">
        <select :id="'select-suggestions' + item.id" name="tour-options-dropdown" v-model="selected[item.id]" class="tour-options-dropdown">
            <option v-for="(tour, key) in item.tours" :key="key" :value="tour.tourID">
                {{ tour.title }}
            </option>
        </select>
    </div>

    <div v-if="toursObj[selected[item.id]]"  class="tour-suggestions">
        <div class="tour-list">
          <div class="tour-list-title">
             <p>{{ toursObj[selected[item.id]].title }}</p>
          </div>
          <div class="tour-list-description">
             <p>
                {{ toursObj[selected[item.id]].description }}
             </p>
          </div>
       </div>
       <button type="button" @click="closeTour(item.id)">
          <span>X</span>
       </div>
    </div>
  </div>
</div>
  `,
  created() {
    this.setToursObj();
  },
  methods: {
    setToursObj() {
      const TOURS_OBJ = {};
      this.hosters.forEach(hoster => {
        hoster.tours.forEach(tour => {
          TOURS_OBJ[tour.tourID] = tour;
        });
      });
      this.toursObj = TOURS_OBJ;
    },
    closeTour(id) {
      this.selected[id] = undefined;
    },
  },
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app"></div>


来源: stackexchange

问:
PHP backend file not found error with react front end
I'm using React front end with a PHP back end to communicate with database. I have a login.js page in which I'm sending the state values to a PHP file to communicate and process those logins. When I run the application It's giving me a 404 not found error for the PHP file.

Here is my Login.js

```<code>const API = "../../api/dbConnect.php";
</code>```

```<code><form>
.....
<button type="submit" name="submit" onClick={this.handleSignin}>Sign In</button>
</form>
</code>```

And the handleSignin function,

```<code>handleSignin = (event) => {
        event.preventDefault();

        axios({
            method:'POST',
            url:`${API}`,
            data:this.state,
            headers: { 'content-type': 'application/json' },
        })
        .then(result => {
            console.log(result)
        })
        .catch(error => console.log(error))
    }
</code>```

The API location is correct as per my folder structure,

```<code>root>
    api/dbConnect.php
    public/
    src/components/Login.js
</code>```

Error is as follows,
GET http://localhost:3000/base/api/dbConnect.php 404 (Not Found)

I'm using a basename as base in App.js as <Router basename="/base">.

答:
I found the mistake. We have to specify the absolute path of the back end file and the file should be served from a http server. In my case it'll something like</p>

```<code>const API = "http://localhost/react/api/dbConnect.php";
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm using React front end with a PHP back end to communicate with database. I have a login.js page in which I'm sending the state values to a PHP file to communicate and process those logins. When I run the application It's giving me a 404 not found error for the PHP file.

Here is my Login.js

const API = "../../api/dbConnect.php";

<form>
.....
<button type="submit" name="submit" onClick={this.handleSignin}>Sign In</button>
</form>

And the handleSignin function,

handleSignin = (event) => {
        event.preventDefault();

        axios({
            method:'POST',
            url:`${API}`,
            data:this.state,
            headers: { 'content-type': 'application/json' },
        })
        .then(result => {
            console.log(result)
        })
        .catch(error => console.log(error))
    }

The API location is correct as per my folder structure,

root>
    api/dbConnect.php
    public/
    src/components/Login.js

Error is as follows,
GET http://localhost:3000/base/api/dbConnect.php 404 (Not Found)

I'm using a basename as base in App.js as <Router basename="/base">.

Body:
I found the mistake. We have to specify the absolute path of the back end file and the file should be served from a http server. In my case it'll something like

const API = "http://localhost/react/api/dbConnect.php";


问:
Unable to debug SQL Server 2005 stored procedures in Visual Studio Team System 2008
I have been trying to debug SQL Server 2005 stored procedures, in Visual Studio Team System 2008.

I connected to the database server and did a right-click "Execute", on the stored procedure.  I even tried "Step Into Stored Procedure", with no luck.

(source: googlepages.com)

The IDE shows it is running, but I can not seem to break or step into the stored procedure.

(source: googlepages.com)

I have checked the event viewer and there are no logs.  There are no output or messages showing where the problem is.

Visual studio contains the following components :-

(source: googlepages.com)

Loads of forums mention debugging issues, but no simple solution were found.

Am I missing something ? Or does anyone know of a more concise site, that walks through successfull stored procedure debugging  ?

答:
Check this, specially the remote debugging part: http://www.dbazine.com/sql/sql-articles/cook1

For other general information on debugging sql check http://msdn.microsoft.com/en-us/library/zefbf0t6.aspx

OwnerDisplayName: Ferds

LastEditorDisplayName: gbn

OwnerDisplayName: Freddy Rios

ContentLicense: CC BY-SA 2.5


问:
Test SetUp Vs TearDown
We've seen test setUp and tearDown are being used regardless of platform and tools. But why do they matter in your tests? Why and how test setUp and tearDown play crucial role in your test execution?

In my opinion, test setUp is the initial state for all the tests. But you can reset the initial state before each test is run or executed. Whereas, tearDown is cleanup process and it will run after test is executed. In other word test tearDown is run on last-in first-out basis.
The simple example of test setUp cloud be Open Browser and tearDown could be Close Browser.

This is an open question you can have your thought.

答:
Neither of them is crucial in respect to functionality, since they could be substituted in other ways, such as calling a function with the startup statements at the start of all test functions or calling another one after running the tests.

However, for the sake of organization and to avoid repetition, they are very helpful.

For example, I have a unit test for a database of mine, where I need to test whether my sign-up and login functions work. Since the sign-up function adds a user to the database, I need to restore it before the other tests, so that they are not compromised, and the setUp functions are very helpful for that.

Title: Test SetUp Vs TearDown


问:
How do I overlay a pattern on a PNG using Pillow in Python
I want to overlay a certain pattern on a shirt in Pillow Python, this is my code -

```<code>design =Image.open("source/stripe.png").convert("RGBA")
shirtsketchtrans = Image.open("source/shirtsketchtrans.png").convert("RGBA")

design.paste(shirtsketchtrans, (0,0), shirtsketchtrans)
design.show()
</code>```

The outcome coming is this -

I don't really mind the size, that can be fixed.
But what I want to do is have the striped pattern overlay only on my shirt PNG and not in the whole background, basically get the pattern only on my shirt and nowhere else.

Is there any solution to this?
Any help is appreciated! Thanks!

Edit: Input/Source Images -

答:
PIL on its own isn't smart enough to know what's "inside" or "outside" the shirt. You need to make a Transparency Mask and then use PIL.Image.composite to combine them.

Example:

```<code>design = Image.open("source/stripe.png").convert("RGBA")
shirt_sketch_trans = Image.open("source/shirtsketchtrans.png").convert("RGBA")
shirt_sketch_mask = Image.open("source/shirtsketchmask.png").convert("RGBA")

full_design = Image.composite(design, shirt_sketch_trans, shirt_sketch_mask)
full_design.show()
</code>```

Body:
I want to overlay a certain pattern on a shirt in Pillow Python, this is my code -

design =Image.open("source/stripe.png").convert("RGBA")
shirtsketchtrans = Image.open("source/shirtsketchtrans.png").convert("RGBA")

design.paste(shirtsketchtrans, (0,0), shirtsketchtrans)
design.show()

The outcome coming is this -

I don't really mind the size, that can be fixed.
But what I want to do is have the striped pattern overlay only on my shirt PNG and not in the whole background, basically get the pattern only on my shirt and nowhere else.

Is there any solution to this?
Any help is appreciated! Thanks!

Edit: Input/Source Images -

Body:
PIL on its own isn't smart enough to know what's "inside" or "outside" the shirt. You need to make a Transparency Mask and then use PIL.Image.composite to combine them.

Example:

design = Image.open("source/stripe.png").convert("RGBA")
shirt_sketch_trans = Image.open("source/shirtsketchtrans.png").convert("RGBA")
shirt_sketch_mask = Image.open("source/shirtsketchmask.png").convert("RGBA")

full_design = Image.composite(design, shirt_sketch_trans, shirt_sketch_mask)
full_design.show()


问:
How to print a word from list upon executing a bot command
So I have this list of some cars below, and when I type in !car, the bot should be able to send only one word from the list but in an embedded message.
So every time I type in this command, the bot sends a single word, until it reaches the end of the list (ascending order).

Example:

List of cars: BMW, Mercedes, Porsche, Honda, Pontiac

User: !car

Bot: BMW

User: !car

Bot: Mercedes

Etc...

Here's my code: How can I modify it to fulfill my request?

```<code>import discord

client = discord.Client()

@client.event
async def on_message(message):

    cars = ['BMW', 'Mercedes', 'Porsche', 'Honda', 'Pontiac']

    if message.content == '!car'
        embed = discord.Embed(title=cars, description=None, color=0xfffb00)
        # It prints the whole list, I would like only one word from the list.
        await message.channel.send(content=None, embed=embed)

client.run('token')
</code>```

Any help would be appreciated

答:
Using the length of the list, you can keep track of how many requests have been fulfilled and use that number to index into your list. As the list is static, I would move it outside your function, and use it like this:

```<code>import discord

client = discord.Client()
cars = ['BMW', 'Mercedes', 'Porsche', 'Honda', 'Pontiac']
num_cars = len(cars)
num_cars_requested = 0

@client.event
async def on_message(message):

    if message.content == '!car'
        embed = discord.Embed(title=cars[num_cars_requested % num_cars], description=None, color=0xfffb00)
        num_cars_requested += 1
        # It prints the whole list, I would like only one word from the list.
        await message.channel.send(content=None, embed=embed)
</code>```

So now your title is one element from the list, and it will rotate through the list by indexing using the number of requests, modulo the length of the list, which will be between 0 and the length of the list minus 1 -- perfect for indexing. And the num_cars_requested += 1 will increment to obtain the next value on the next request.

Happy Coding (and happy Friday)!

Body:
So I have this list of some cars below, and when I type in !car, the bot should be able to send only one word from the list but in an embedded message.
So every time I type in this command, the bot sends a single word, until it reaches the end of the list (ascending order).

Example:

List of cars: BMW, Mercedes, Porsche, Honda, Pontiac

User: !car

Bot: BMW

User: !car

Bot: Mercedes

Etc...

Here's my code: How can I modify it to fulfill my request?

import discord

client = discord.Client()

@client.event
async def on_message(message):

    cars = ['BMW', 'Mercedes', 'Porsche', 'Honda', 'Pontiac']

    if message.content == '!car'
        embed = discord.Embed(title=cars, description=None, color=0xfffb00)
        # It prints the whole list, I would like only one word from the list.
        await message.channel.send(content=None, embed=embed)

client.run('token')

Any help would be appreciated

Body:
Using the length of the list, you can keep track of how many requests have been fulfilled and use that number to index into your list. As the list is static, I would move it outside your function, and use it like this:

import discord

client = discord.Client()
cars = ['BMW', 'Mercedes', 'Porsche', 'Honda', 'Pontiac']
num_cars = len(cars)
num_cars_requested = 0

@client.event
async def on_message(message):

    if message.content == '!car'
        embed = discord.Embed(title=cars[num_cars_requested % num_cars], description=None, color=0xfffb00)
        num_cars_requested += 1
        # It prints the whole list, I would like only one word from the list.
        await message.channel.send(content=None, embed=embed)

So now your title is one element from the list, and it will rotate through the list by indexing using the number of requests, modulo the length of the list, which will be between 0 and the length of the list minus 1 -- perfect for indexing. And the num_cars_requested += 1 will increment to obtain the next value on the next request.

Happy Coding (and happy Friday)!


问:
How do I query an association table in SQLAlchemy?
I'm trying to convert an SQL query into an SQLAlchemy query to user inside get API. The problem is that I cannot query anything from the association table. (I'm sure I don't know the method).

ORM:

```<code>roles_users = db.Table(
    'roles_users',
    db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
    db.Column('role_id', db.Integer(), db.ForeignKey('role.id'))
     )

class Role(db.Model, RoleMixin):
   id = db.Column(db.Integer(), primary_key=True)
   name = db.Column(db.String(50), unique=True)
   description = db.Column(db.String(255))

   def __str__(self):
      return self.name

class User(db.Model, UserMixin):
   id = db.Column(db.Integer, primary_key=True)
   first_name = db.Column(db.String(50))
   last_name = db.Column(db.String(50))
   email = db.Column(db.String(50), unique=True)
   password = db.Column(db.String(255))
        .
        .
        .
   roles = db.relationship('Role', secondary=roles_users,
                        backref=db.backref('users', lazy='dynamic'))

   def __str__(self):
       return self.email
</code>```

Working SQL query:

```<code>select first_name, last_name, role.name from user
    join roles_users
       join role on user.id = roles_users.user_id
           and role.id = roles_users.role_id;
</code>```

SQLAlchemy query that I'm having trouble with:

```<code>roles_users.query.join(Role).join(User)
   .filter(roles_users.user_id == User.id and
       roles_users.role_id == Role.id).all()
</code>```

Error that I'm getting using above SQLAlchemy query:

```<code>AttributeError: 'Table' object has no attribute 'query'
</code>```

How do I perform the equivalent of my SQL query using SQLAlchemy?

答:
It's also possible to use a select_from statement.

This is for when you have declared your association table as an object and are using flask_user:

```<code>from flask_user import UserMixin
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class User(db.Model, UserMixin):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)

    name = db.Column(db.String(100, collation='NOCASE'),
                       nullable=False, server_default='')
    password = db.Column(db.String(255), nullable=False, server_default='')

    roles = db.relationship('Role', secondary='user_roles')

class Role(db.Model):
    __tablename__ = 'roles'
    id = db.Column(db.Integer(), primary_key=True)
    name = db.Column(db.String(50), unique=True)

# Associatin Table:
class UserRoles(db.Model):
    __tablename__ = 'user_roles'
    id = db.Column(db.Integer(), primary_key=True)
    user_id = db.Column(db.Integer(), db.ForeignKey('users.id',
                                                    ondelete='CASCADE'))
    role_id = db.Column(db.Integer(), db.ForeignKey('roles.id',
                                                    ondelete='CASCADE'))
</code>```

You can then query the user roles like this:

```<code>from app.db_model import db, Broker, UserRoles
from flask_user import current_user

user_id = current_user.id

all_user_roles =\
    (db.session.query(Role.name)
     .select_from(UserRoles, Role)
     .join(UserRoles)
     .filter(UserRoles.user_id == user_id)
     .all())
</code>```

EDIT: Ok, it's even simpler with current_user

```<code># a list of all Role objects in roles
current_user.roles

# print out all names
print([role.name for role in current_user.roles])
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to convert an SQL query into an SQLAlchemy query to user inside get API. The problem is that I cannot query anything from the association table. (I'm sure I don't know the method).

ORM:

roles_users = db.Table(
    'roles_users',
    db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
    db.Column('role_id', db.Integer(), db.ForeignKey('role.id'))
     )

class Role(db.Model, RoleMixin):
   id = db.Column(db.Integer(), primary_key=True)
   name = db.Column(db.String(50), unique=True)
   description = db.Column(db.String(255))

   def __str__(self):
      return self.name

class User(db.Model, UserMixin):
   id = db.Column(db.Integer, primary_key=True)
   first_name = db.Column(db.String(50))
   last_name = db.Column(db.String(50))
   email = db.Column(db.String(50), unique=True)
   password = db.Column(db.String(255))
        .
        .
        .
   roles = db.relationship('Role', secondary=roles_users,
                        backref=db.backref('users', lazy='dynamic'))

   def __str__(self):
       return self.email

Working SQL query:

select first_name, last_name, role.name from user
    join roles_users
       join role on user.id = roles_users.user_id
           and role.id = roles_users.role_id;

SQLAlchemy query that I'm having trouble with:

roles_users.query.join(Role).join(User)
   .filter(roles_users.user_id == User.id and
       roles_users.role_id == Role.id).all()

Error that I'm getting using above SQLAlchemy query:

AttributeError: 'Table' object has no attribute 'query'

How do I perform the equivalent of my SQL query using SQLAlchemy?

Body:
It's also possible to use a select_from statement.

This is for when you have declared your association table as an object and are using flask_user:

from flask_user import UserMixin
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class User(db.Model, UserMixin):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)

    name = db.Column(db.String(100, collation='NOCASE'),
                       nullable=False, server_default='')
    password = db.Column(db.String(255), nullable=False, server_default='')

    roles = db.relationship('Role', secondary='user_roles')

class Role(db.Model):
    __tablename__ = 'roles'
    id = db.Column(db.Integer(), primary_key=True)
    name = db.Column(db.String(50), unique=True)

# Associatin Table:
class UserRoles(db.Model):
    __tablename__ = 'user_roles'
    id = db.Column(db.Integer(), primary_key=True)
    user_id = db.Column(db.Integer(), db.ForeignKey('users.id',
                                                    ondelete='CASCADE'))
    role_id = db.Column(db.Integer(), db.ForeignKey('roles.id',
                                                    ondelete='CASCADE'))

You can then query the user roles like this:

from app.db_model import db, Broker, UserRoles
from flask_user import current_user

user_id = current_user.id

all_user_roles =\
    (db.session.query(Role.name)
     .select_from(UserRoles, Role)
     .join(UserRoles)
     .filter(UserRoles.user_id == user_id)
     .all())

EDIT: Ok, it's even simpler with current_user

# a list of all Role objects in roles
current_user.roles

# print out all names
print([role.name for role in current_user.roles])


问:
Duplicate entries in apache solr index upon reindexing in Drupal
I am using apache solr search integration on my Drupal 6 website: govoluntourism.com. I have my search results themed using views and a search-result.tpl.php file.

The search-result.tpl.php contains:

```<code>$nid = $result['fields']['nid']['value'];
echo views_embed_view($name = 'search', $display_id = 'default', $nid);
</code>```

When I add content to my site and run cron, it seems that duplicate entries are being made in the apache index, because I am getting duplicates in the search results only of the content that was previously indexed.

Is this a server-side issue or a mistake in my configuration? Not sure where to go from here.
thanks.

the site is: govoluntourism.com

答:
I looked at your site and the duplicate search results all point to the same nodes, so that means you probably don't have actual duplicate content.

The first thing to do if you suspect your index is corrupt and you can't find the problem, is probably to reindex all of your content. You can do that by going here: http://govoluntourism.com/admin/settings/apachesolr/index.

Next, you can choose "Delete the Index", then "Re-index All Content". What this will do is rebuild your entire index from scratch. Note that if you choose "Re-Index All Content", it will happen immediately. If you have cron running, cron will slowly rebuild the index, which will use less resources but take much longer.

Once you have done that you'll have a better idea of what's going on.

If that doesn't work then you probably have an issue with the search results theme customization.

Body:
I am using apache solr search integration on my Drupal 6 website: govoluntourism.com. I have my search results themed using views and a search-result.tpl.php file.

The search-result.tpl.php contains:

$nid = $result['fields']['nid']['value'];
echo views_embed_view($name = 'search', $display_id = 'default', $nid);

When I add content to my site and run cron, it seems that duplicate entries are being made in the apache index, because I am getting duplicates in the search results only of the content that was previously indexed.

Is this a server-side issue or a mistake in my configuration? Not sure where to go from here.
thanks.

the site is: govoluntourism.com


问:
Decimal rounding issues
I have a scenario in which some variable values have decimal values, the values can have leading .0, .234, .124, .125, numbers like this, and so on. If the number has leading decimal and zero it should ignore and if a number has leading 3 or more numbers it should round off to two.
Let's say the code is as follows:

```<code>var anone    = "23"
var antwo    = "23.0"
var anthree  = "23.467"
var anfour   = "23.125"
</code>```

In order to remove the leading decimal and zero I have used the following method:

```<code> var removingzero = antwo.Replace(".0", "");
 // The result will be = 23
</code>```

In order to round off and limit the number to two decimal points I have used the following method:

```<code> var convertodecimal = Decimal.Parse(anthree);
 var roundtotwo      = Math.Round(convertodecimal, 2);
 // The result will be = 23.47
</code>```

similarly in order to convert the last one I follow the same method:

```<code> var convertodecimal = Decimal.Parse(anfour);
 var roundtotwo      = Math.Round(convertodecimal, 2);
 // The result will be = 23.12
 // But the Result should be = 23.13
</code>```

So, the problem is when I am trying to round off any number like the last example it does not do it, how can I fix it.

答:
Try by changing your Math.Round() to below one:

Math.Round(num,2, MidpointRounding.AwayFromZero)

Title: Decimal rounding issues

Body:
I have a scenario in which some variable values have decimal values, the values can have leading .0, .234, .124, .125, numbers like this, and so on. If the number has leading decimal and zero it should ignore and if a number has leading 3 or more numbers it should round off to two.
Let's say the code is as follows:

var anone    = "23"
var antwo    = "23.0"
var anthree  = "23.467"
var anfour   = "23.125"

In order to remove the leading decimal and zero I have used the following method:

 var removingzero = antwo.Replace(".0", "");
 // The result will be = 23

In order to round off and limit the number to two decimal points I have used the following method:

 var convertodecimal = Decimal.Parse(anthree);
 var roundtotwo      = Math.Round(convertodecimal, 2);
 // The result will be = 23.47

similarly in order to convert the last one I follow the same method:

 var convertodecimal = Decimal.Parse(anfour);
 var roundtotwo      = Math.Round(convertodecimal, 2);
 // The result will be = 23.12
 // But the Result should be = 23.13

So, the problem is when I am trying to round off any number like the last example it does not do it, how can I fix it.


问:
How to pass the javascript variable value from one html page to the another html page?
I am creating the quiz application using JavaScript and Django. Actually entire logic was done in the JavaScript . For the quiz application ,I have a score variable that score variable value i am showing in the index.html as show below:

```<code>          resultCont.innerHTML = 'Your Score:- ' + score + '/80' ;
</code>```

Here score is the JavaScript variable.

Another thing I need to store this score variable into my DB . So that I need to use the ajax to post the score variable to my views.py file where my function is running to submit the score along with username to the Django models.

models.py:

```<code>class Results(models.Model):
    username = models.CharField(max_length=50,default='')
    score = models.IntegerField()

    def __str__(self):
        return self.username
</code>```

Here I have taken the username and score variable . And the username is the foreign key.

views.py

```<code>def score(request):
    if request.method == 'GET':
        return render(request, 'quiz/html/end.html',{'form':Score()})
    else:
        try:
            form = Score(data=request.POST)
            newscore = form.save(commit=False)
            newscore.owner = request.user
            newscore.save()
            return redirect('category')
        except ValueError:
            return render(request, 'quiz/html/end.html',{'form':Score(), 'error' :'please fill the form properly'})
</code>```

end.html: Here I have used the form to submit the score along with name . I hidden the username so that user cannot change the name.

```<code><form method="POST">
        {% csrf_token %}

        <div>
            <p style="display:none;">
                <label for="id_username">Username:</label>
                <input type="text" name="username" value={{user.username}} placeholder="{{user.username}}" maxlength="50" required="" id="id_username">
            </p>

            <p>
                <label for="id_score">Score:</label>
                <input type="number" name="score" placeholder ='' value='I want the score value here from javascsript' required="" id="id_score">
            </p>
        </div>
        <button type="submit">Submit</button>

    </form>
</code>```

I wrote the ajax post request but i tried  of showing score in the same index.html. It is displaying but i want that score value in the end.html. Is it possible to show the score of index.html(score storing in the #result) into the end.html (where the score need to store )

```<code>function scoresubmit(){
          $.ajax({
            url: '/',
            method : 'POST',
            // data: {score: $('#score').val(), "csrfmiddlewaretoken" : "{{csrf_token}}"},
            success: function() {
              $('#name').html(score);
            }
             });
            }
</code>```

index.html:   (from here)

```<code>resultCont.innerHTML = 'Your Score:- ' + score + '/80' ;
</code>```

end.html:(to Here)

```<code> <input type="number" name="score" placeholder ='' value='I want the score value here from javascsript' required="" id="id_score">
</code>```

urls.py:

```<code>path('home', views.home,name = "home"),
    path('main',views.main, name='main'),
    path('', views.score, name = "score"),
    path('profile/',views.profile, name = "profile"),
    path('category/',views.category, name = "category"),
</code>```

Only thing I want here is store the score along with the user name  in my DB (Django).

What is the wrong in my ajax code . How to pass the value from one to another html using ajax post request?

答:
Hey below is the code i tried.
I created a form in index.html. Took dummy input, marks and performed some operation on it and sent variable score to the end.html and also stored it in the db.
Since i was working with JS ajax, i used djano-rest framwork for the same.
Below is the code

models.py

```<code>from django.db import models
from django.contrib.auth.models import User

# Create your models here.
class Results(models.Model):
    user = models.ForeignKey(User, default=None, on_delete=models.CASCADE)
    score = models.IntegerField()
    marks = models.IntegerField()
</code>```

index.html

```<code>body>
    <form id="scoreform" method="POST">
        {% csrf_token %}
        <p class="marks">
            <label for="marks">Marks</label>
            <input type="number" name='marks' id="id_marks">
        </p>

        <input type="submit"  id="submit" value="Submit">
    </form>
</body>

<script src="{% static 'main.js' %}"></script>
</code>```

end.html

```<code><body>
    <form id="scoreform" method="POST">
        {% csrf_token %}
        <p class="username">
            <label for="username">Label</label>
            <input type="text" name="username" value={{score.user}}>
        </p>
        <p class="scores">
            <label for="score">Score</label>
            <input type="number" name='score' id="score-value" value={{score.score}}>
        </p>

    </form>
</body>
</code>```

views.py

```<code>from django.shortcuts import render, redirect
from .models import Results
from .forms import Score
from django.contrib.auth.decorators import login_required
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .serializers import ResultSerializer

# Create your views here.
@api_view(['GET','POST'])
@login_required(login_url='users:login')
def score(request):
    form = Score()
    print(1)
    if request.method == 'POST':
        serializer = ResultSerializer(data=request.data)
        print(serializer)
        if (serializer.is_valid()):
            print(3)
            serializer.save(user = request.user)
            return Response(request.user.pk)
    return render(request, 'index.html', {'form': form})
    #return redirect('score:end', pk=request.user.pk)

@login_required(login_url='users:login')
def end(request, pk):
    score = Results.objects.get(pk=pk)
    return render(request, 'end.html', {'score':score})
</code>```

This also has login feature, as i wanted to tag a user to the score.
I dunno who clear this would be for you. But i seriously hope this helps

Body:
I am creating the quiz application using JavaScript and Django. Actually entire logic was done in the JavaScript . For the quiz application ,I have a score variable that score variable value i am showing in the index.html as show below:

          resultCont.innerHTML = 'Your Score:- ' + score + '/80' ;

Here score is the JavaScript variable.

Another thing I need to store this score variable into my DB . So that I need to use the ajax to post the score variable to my views.py file where my function is running to submit the score along with username to the Django models.

models.py:

class Results(models.Model):
    username = models.CharField(max_length=50,default='')
    score = models.IntegerField()

    def __str__(self):
        return self.username

Here I have taken the username and score variable . And the username is the foreign key.

views.py

def score(request):
    if request.method == 'GET':
        return render(request, 'quiz/html/end.html',{'form':Score()})
    else:
        try:
            form = Score(data=request.POST)
            newscore = form.save(commit=False)
            newscore.owner = request.user
            newscore.save()
            return redirect('category')
        except ValueError:
            return render(request, 'quiz/html/end.html',{'form':Score(), 'error' :'please fill the form properly'})

end.html: Here I have used the form to submit the score along with name . I hidden the username so that user cannot change the name.

<form method="POST">
        {% csrf_token %}

                Username:
                <input type="text" name="username" value={{user.username}} placeholder="{{user.username}}" maxlength="50" required="" id="id_username">

                Score:
                <input type="number" name="score" placeholder ='' value='I want the score value here from javascsript' required="" id="id_score">

        <button type="submit">Submit</button>

    </form>

I wrote the ajax post request but i tried  of showing score in the same index.html. It is displaying but i want that score value in the end.html. Is it possible to show the score of index.html(score storing in the #result) into the end.html (where the score need to store )

function scoresubmit(){
          $.ajax({
            url: '/',
            method : 'POST',
            // data: {score: $('#score').val(), "csrfmiddlewaretoken" : "{{csrf_token}}"},
            success: function() {
              $('#name').html(score);
            }
             });
            }

index.html:   (from here)

resultCont.innerHTML = 'Your Score:- ' + score + '/80' ;

end.html:(to Here)

 <input type="number" name="score" placeholder ='' value='I want the score value here from javascsript' required="" id="id_score">

urls.py:

path('home', views.home,name = "home"),
    path('main',views.main, name='main'),
    path('', views.score, name = "score"),
    path('profile/',views.profile, name = "profile"),
    path('category/',views.category, name = "category"),

Only thing I want here is store the score along with the user name  in my DB (Django).

What is the wrong in my ajax code . How to pass the value from one to another html using ajax post request?

Body:
Hey below is the code i tried.
I created a form in index.html. Took dummy input, marks and performed some operation on it and sent variable score to the end.html and also stored it in the db.
Since i was working with JS ajax, i used djano-rest framwork for the same.
Below is the code

models.py

from django.db import models
from django.contrib.auth.models import User

# Create your models here.
class Results(models.Model):
    user = models.ForeignKey(User, default=None, on_delete=models.CASCADE)
    score = models.IntegerField()
    marks = models.IntegerField()

index.html

body>
    <form id="scoreform" method="POST">
        {% csrf_token %}
        <p class="marks">
            <label for="marks">Marks</label>
            <input type="number" name='marks' id="id_marks">
        </p>

        <input type="submit"  id="submit" value="Submit">
    </form>
</body>

<script src="{% static 'main.js' %}"></script>

end.html

<body>
    <form id="scoreform" method="POST">
        {% csrf_token %}
        <p class="username">
            <label for="username">Label</label>
            <input type="text" name="username" value={{score.user}}>
        </p>
        <p class="scores">
            <label for="score">Score</label>
            <input type="number" name='score' id="score-value" value={{score.score}}>
        </p>

    </form>
</body>

views.py

from django.shortcuts import render, redirect
from .models import Results
from .forms import Score
from django.contrib.auth.decorators import login_required
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .serializers import ResultSerializer

# Create your views here.
@api_view(['GET','POST'])
@login_required(login_url='users:login')
def score(request):
    form = Score()
    print(1)
    if request.method == 'POST':
        serializer = ResultSerializer(data=request.data)
        print(serializer)
        if (serializer.is_valid()):
            print(3)
            serializer.save(user = request.user)
            return Response(request.user.pk)
    return render(request, 'index.html', {'form': form})
    #return redirect('score:end', pk=request.user.pk)

@login_required(login_url='users:login')
def end(request, pk):
    score = Results.objects.get(pk=pk)
    return render(request, 'end.html', {'score':score})

This also has login feature, as i wanted to tag a user to the score.
I dunno who clear this would be for you. But i seriously hope this helps


问:
Access to fetch at 'https://randomuser.me/api/?results=4' from origin 'http://localhost:3000' has been blocked by CORS policy:
I keep getting this in my console and i don't understand, please can somebody help me and explain.
Access to fetch at 'https://randomuser.me/api/?results=4' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.</p>

答:
In your api domain https://randomuser.me, add localhost to your list of allowed origin.

The reason you're getting this error is because https://randomuser.me expects request from origin https://randomuser.me and not from some other sources like from your localhost. If this is not satisfied it will be returned as a warning/error by your browser.


问:
Azure Cosmos DB - how to retrieve json attributes from a document similar like retrieving column names from SQL table
```<code>{
  "Volcano Name": "Agua de Pau",
  "Country": "Portugal",
  "Region": "Azores",
  "Location": {
    "type": "Point",
    "coordinates": [
      -25.47,
      37.77
    ]
  },
  "Elevation": 947,
  "Type": "Stratovolcano",
  "Status": "Historical",
  "Last Known Eruption": "Last known eruption from 1500-1699, inclusive",
  "id": "d44c94b6-81f8-4b27-4970-f79b149529d3",
  "_rid": "Sl8fALN4sw4BAAAAAAAAAA==",
  "_ts": 1448049512,
  "_self": "dbs/Sl8fAA==/colls/Sl8fALN4sw4=/docs/Sl8fALN4sw4BAAAAAAAAAA==/",
  "_etag": "\"0000443f-0000-0000-0000-564f7b680000\"",
  "_attachments": "attachments/"
}
</code>```

In MS SQL, we have like below to read column names from a table.

select column_name, data_type, character_maximum_length
    from INFORMATION_SCHEMA.COLUMNS
    where table_name = 'table_name' .

I am expecting the same for document db. is it possible
from the above sample document which has the Type "Stratovolcano" to retrieve the json names "Volcano Name", "Country", "Region", "Location"... etc

答:
An Azure Cosmos SQL container is a schema-agnostic container of items. The items in a container can have arbitrary schemas unlike rows in a table. So, Cosmos DB will not be able to do what you are asking for. </p>

<p>In your case it looks like all your items will have the same schema. So, you could do a " select * from c where c.id = "someid" " and infer the schema from the retuned item. </p>

Body:
{
  "Volcano Name": "Agua de Pau",
  "Country": "Portugal",
  "Region": "Azores",
  "Location": {
    "type": "Point",
    "coordinates": [
      -25.47,
      37.77
    ]
  },
  "Elevation": 947,
  "Type": "Stratovolcano",
  "Status": "Historical",
  "Last Known Eruption": "Last known eruption from 1500-1699, inclusive",
  "id": "d44c94b6-81f8-4b27-4970-f79b149529d3",
  "_rid": "Sl8fALN4sw4BAAAAAAAAAA==",
  "_ts": 1448049512,
  "_self": "dbs/Sl8fAA==/colls/Sl8fALN4sw4=/docs/Sl8fALN4sw4BAAAAAAAAAA==/",
  "_etag": "\"0000443f-0000-0000-0000-564f7b680000\"",
  "_attachments": "attachments/"
}

In MS SQL, we have like below to read column names from a table.

select column_name, data_type, character_maximum_length
    from INFORMATION_SCHEMA.COLUMNS
    where table_name = 'table_name' .

I am expecting the same for document db. is it possible
from the above sample document which has the Type "Stratovolcano" to retrieve the json names "Volcano Name", "Country", "Region", "Location"... etc

Body:
An Azure Cosmos SQL container is a schema-agnostic container of items. The items in a container can have arbitrary schemas unlike rows in a table. So, Cosmos DB will not be able to do what you are asking for.

In your case it looks like all your items will have the same schema. So, you could do a " select * from c where c.id = "someid" " and infer the schema from the retuned item.


问:
Initialize a constant variable in PS_CONFIGURATION
In fact my question is facing a misunderstanding concerning the functioning of prestashop, in particular due to the poorly explained documentation. In fact, the final idea would be to create an accordion visible in the front end, with all the necessary parameters via a form in the back office.

I consulted the getting started documentation, with success, and my question is about the variable of the table PS_CONFIGURATION. To use the example in the doc, when is the variable MY_MODULENAME initialized? I would like to put a variable by input of the form, but when I enter them in the display form method by indicating in the name the name of each variable, I have an error returning undefined. I was told that the variables initialized during installation, but after regularly uninstalling / reinstalling my module, nothing changes, so I put all the variables in the install() or getContent() method.

So my question is: In which part of the main class initialized all the necessary variables (I already know that we must use !Configuration::updateValue()), to later use them in the form and transcribe them in the tpl file with smarty ?

答:
I'm not sure if I understand well your question, but maybe this will help you.

in getContent() function you generate the content displayed at the Back Office. This is where you build the form to display and get the options.

When the form is submitted something like this should work to save the variables

```<code>if (Tools::isSubmit($this->name)) {
    // process the submitted data
}
</code>```

The install() function is mainly used to register the hooks and to create the databases, as contrary of uninstall() which should remove that data for a clean uninstallation.

On the Front End you depend on the hooks, until the hook is called any variable that you define will not be present in the template, so probably if you see an undefined notice then you are trying to access the variable but is still not assigned.

If you are going to build a module for your site or for a particular client and you don't want to depend on hooks you can assign the variables in the header hook and then you should be able to use then in any part of the tpls.

If you want to build a commercial module, then you must depend on hooks.

I hope that helps!

Body:
I'm not sure if I understand well your question, but maybe this will help you.

in getContent() function you generate the content displayed at the Back Office. This is where you build the form to display and get the options.

When the form is submitted something like this should work to save the variables

if (Tools::isSubmit($this->name)) {
    // process the submitted data
}

The install() function is mainly used to register the hooks and to create the databases, as contrary of uninstall() which should remove that data for a clean uninstallation.

On the Front End you depend on the hooks, until the hook is called any variable that you define will not be present in the template, so probably if you see an undefined notice then you are trying to access the variable but is still not assigned.

If you are going to build a module for your site or for a particular client and you don't want to depend on hooks you can assign the variables in the header hook and then you should be able to use then in any part of the tpls.

If you want to build a commercial module, then you must depend on hooks.

I hope that helps!


问:
Visual studio code tracks one git repo only
I am working with VS Code IDE and cloned two repos.
i.e.

```<code>git clone url://repo1
cd new
git clone url://repo2 new2
</code>```

However,VS code is only tracking one repo for changes. it grays out new2 folder(it is part of repo1 gitignore). also if I make any changes it does not reflect in left panel of VS code source control.

Is it possible in Visual studio code to work with two repositories and tracking/pulling/pushing changes of both repos?

Disclaimer : I have not worked much on git or VS code earlier.

答:
I am able to solve this issue by adding a dummy .submodules file at root folder, and adding it to .gitignore

contain of .submoudles file:

```<code>[submodule "your_module_name"]
    path = paht_of_submodule/
    url = dummy_string_to_satisfy_vscode
</code>```

More details here :
https://github.com/microsoft/vscode/issues/37947 and
https://git-scm.com/docs/gitmodules

Body:
I am working with VS Code IDE and cloned two repos.
i.e.

git clone url://repo1
cd new
git clone url://repo2 new2

However,VS code is only tracking one repo for changes. it grays out new2 folder(it is part of repo1 gitignore). also if I make any changes it does not reflect in left panel of VS code source control.

Is it possible in Visual studio code to work with two repositories and tracking/pulling/pushing changes of both repos?

Disclaimer : I have not worked much on git or VS code earlier.

Body:
I am able to solve this issue by adding a dummy .submodules file at root folder, and adding it to .gitignore

contain of .submoudles file:

[submodule "your_module_name"]
    path = paht_of_submodule/
    url = dummy_string_to_satisfy_vscode

More details here :
https://github.com/microsoft/vscode/issues/37947 and
https://git-scm.com/docs/gitmodules


问:
how to SQL inject this?
```<code>mysql_select_db($database_db, $db);
query_user = "SELECT * FROM customers WHERE email = '$login'";
user = mysql_query($query_user, $db) or die(mysql_error());
row_user = mysql_fetch_assoc($user);
totalRows_user = mysql_num_rows($user);
</code>```

<p>i need some help i know this might be injectable i need to bring up all the customer details within    the database. please help. </p>

答:
This would work:

```<code>foo' or 1 = 1 --
</code>```

Or, since you are running MySQL:

```<code>foo' or 1 --
</code>```

When concatenated in your query string, this produces:

```<code>SELECT *
FROM customers
WHERE email = 'foo' or 1 = 1 -- '
</code>```

Regardless of the result of the first condition, the second condition evaluates as true, so the query returns all rows in the table.

Title: how to SQL inject this?

Body:
mysql_select_db($database_db, $db);
query_user = "SELECT * FROM customers WHERE email = '$login'";
user = mysql_query($query_user, $db) or die(mysql_error());
row_user = mysql_fetch_assoc($user);
totalRows_user = mysql_num_rows($user);

i need some help i know this might be injectable i need to bring up all the customer details within    the database. please help.

Body:
This would work:

foo' or 1 = 1 --

Or, since you are running MySQL:

foo' or 1 --

When concatenated in your query string, this produces:

SELECT *
FROM customers
WHERE email = 'foo' or 1 = 1 -- '

Regardless of the result of the first condition, the second condition evaluates as true, so the query returns all rows in the table.


问:
Is it possible for async method to ever return null in C#?
Digging through some old code, I have noticed a call to an asyncmethod and then a check for the task being returned for null.

```<code>async Task<Something> DoSomeStuffAsync()
{
    //...
    return null; //not the actual return, but I guess it doesn't matter
}

var result = DoSomeStuffAsync(); //without await
if(result == null)
{
    //does this part makes any sense
}
</code>```

From my understanding of the async keyword, this scenario will never be possible because the result of an async method will always be wrapped in a Task but just to check, am I missing something?

Is there any case when an async method will return null in C#?

答:
It's not possible for a method marked async to return null.

However, for the caller, a method is not async or not, it just returns an awaitable (a Task... or other awaitable types, that's out of the scope of the question), so it's indeed possible that it returns null.

I.e., the caller can't distinguish between:

```<code>async Task Foo()
//...
</code>```

and:

```<code>Task Foo()
//...
</code>```

And the latter method can perfectly return null

So a null check is perfectly valid for the caller

Body:
Digging through some old code, I have noticed a call to an asyncmethod and then a check for the task being returned for null.

async Task<Something> DoSomeStuffAsync()
{
    //...
    return null; //not the actual return, but I guess it doesn't matter
}

var result = DoSomeStuffAsync(); //without await
if(result == null)
{
    //does this part makes any sense
}

From my understanding of the async keyword, this scenario will never be possible because the result of an async method will always be wrapped in a Task but just to check, am I missing something?

Is there any case when an async method will return null in C#?

Body:
It's not possible for a method marked async to return null.

However, for the caller, a method is not async or not, it just returns an awaitable (a Task... or other awaitable types, that's out of the scope of the question), so it's indeed possible that it returns null.

I.e., the caller can't distinguish between:

async Task Foo()
//...

and:

Task Foo()
//...

And the latter method can perfectly return null

So a null check is perfectly valid for the caller


问:
Declare an array with pointer in C
Why is this syntax illegal in C?

```<code>int *a = {1,2,3};
</code>```

Aren't arrays and pointers the same thing? Why would this work and not the above?

```<code>int a[] = {1,2,3};
int *b = a;
</code>```

答:
Why is this syntax illegal in C?

In int a[] = {1,2,3};, the {1,2,3} is a syntax for providing initial values of the things being initialized. A list of values in braces is a general notation for listing initial values. It is not a notation for representing an array.

The declaration says a is an array, but that is just in its int a[] part. The {1,2,3} does not indicate an array—it just provides a list of values, and it could be used for non-array objects, such as providing values for the members of a structure.

In int *a = {1,2,3};, the int *a part defines a to be a pointer. A pointer just has one value in it—the address of something (or null). So it does not make sense to initialize it with multiple values. To initialize a pointer, you need to provide an address for it to point to.

There is a notation in C for representing an array of given values. It is called a compound literal, and can be used for types in general, not just arrays. Its syntax is “(type) { initial values }”. So we can create an array with (int []) {1, 2, 3}. A pointer could be defined and initialized to point to this array with int *a = (int []) {1, 2, 3};. However, this should be done with care. Such an array is temporary (has automatic storage duration that ends when execution of its associated block ends) when defined inside a function, so the pointer will become invalid when the function returns (or before, if it is in an inner block).

Title: Declare an array with pointer in C

Body:
Why is this syntax illegal in C?

int *a = {1,2,3};

Aren't arrays and pointers the same thing? Why would this work and not the above?

int a[] = {1,2,3};
int *b = a;


问:
sum of nested list in Python
I try to sum a list of nested elements

e.g, numbers=[1,3,5,6,[7,8]] should produce sum=30

I wrote the following code :

```<code>def nested_sum(L):
    sum=0
    for i in range(len(L)):
       if (len(L[i])>1):
          sum=sum+nested_sum(L[i])
       else:
          sum=sum+L[i]
    return sum
</code>```

The above code gives following error:

object of type 'int' has no len()

I also tried len([L[i]]), still not working.

Anyone can help? It is Python 3.3

答:
L = [1, 2, 3, [4, 5, 6], 5, [7, 8, 9]]
total = 0 # assign any var
for a in L: # assign index and start to iterate using if else
    if (isinstance(a, list)): # since its a list you are basically repeating the prev step
        for b in a:
            total += b
    else:
        total += a
print(total)
```

Title: sum of nested list in Python

Body:
I try to sum a list of nested elements

e.g, numbers=[1,3,5,6,[7,8]] should produce sum=30

I wrote the following code :

def nested_sum(L):
    sum=0
    for i in range(len(L)):
       if (len(L[i])>1):
          sum=sum+nested_sum(L[i])
       else:
          sum=sum+L[i]
    return sum

The above code gives following error:

object of type 'int' has no len()

I also tried len([L[i]]), still not working.

Anyone can help? It is Python 3.3


问:
Add constraints to neo4j node based on node property value
I am adding constraints to a neo4j database using Cypher constraints and want to create a constraint which only applies to a subset of a node type.

I can create a constraint that a foo field must exist on Entity with

CREATE CONSTRAINT ON (e:Entity) ASSERT EXISTS (e.foo)

but instead, I want to constrain only nodes with a given field. e.g

CREATE CONSTRAINT ON (e:Entity {constrain_flag:true) ASSERT EXISTS (e.foo)

For example, I may have two nodes like

(e:Entity { foo: 'bar' , constrain_flag: true }) and

(e:Entity { constrain_flag: false })

I only want the constraint that e.foo must exist to apply to the Entity where constrain_flag = true, so both of these should be allowed. However,

(e:Entity { constrain_flag: false }) should throw an exception.

Is there a way to do this currently with cypher and neo4j?

Thanks in advance!

答:
Instead of adding a flag property, you can just add an additional label (say, ConstrainedEntity) to Entity nodes that should be constrained. Queries can continue to use just the Entity label.

For example:

```<code>CREATE CONSTRAINT ON (ce:ConstrainedEntity) ASSERT EXISTS (ce.foo)
</code>```

To create a "flagged" Entity:

```<code>CREATE (e:Entity:ConstrainedEntity {id: 111, foo: 'bar'})
</code>```

To "flag" an existing Entity:

```<code>MATCH (e:Entity)
WHERE e.id = 123
SET e:ConstrainedEntity
</code>```

Body:
Instead of adding a flag property, you can just add an additional label (say, ConstrainedEntity) to Entity nodes that should be constrained. Queries can continue to use just the Entity label.

For example:

CREATE CONSTRAINT ON (ce:ConstrainedEntity) ASSERT EXISTS (ce.foo)

To create a "flagged" Entity:

CREATE (e:Entity:ConstrainedEntity {id: 111, foo: 'bar'})

To "flag" an existing Entity:

MATCH (e:Entity)
WHERE e.id = 123
SET e:ConstrainedEntity


问:
Android Studio - How to perform doubleClick in Kotlin?
A boring thing when some more advanced technologies impose their standards is to have to do with the "double click" to perform an action. But what I'm looking for is an easy way to implement it without having to rewrite the code a thousand times.

I would like to implement double click in my project using Kotlin.
Could someone help me?
Thanks in Advance

just to know: I would like a way to understand how to do double click or to prevent  that user do a doubleclick

答:
I implemented this library using Kotlin, you can just define the doubleClick property and override single and double click methods, and finally add it to setOnClickListener of your button

```<code>val doubleClick = DoubleClick(object : DoubleClickListener {
    override fun onSingleClickEvent(view: View?) {
        // DO STUFF SINGLE CLICK
    }

    override fun onDoubleClickEvent(view: View?) {
       // DO STUFF DOUBLE CLICK
    }
})

button.setOnClickListener(doubleClick)
</code>```

https://gitlab.com/developerdeveloperdeveloper/androidutilslibrary

Body:
I implemented this library using Kotlin, you can just define the doubleClick property and override single and double click methods, and finally add it to setOnClickListener of your button

val doubleClick = DoubleClick(object : DoubleClickListener {
    override fun onSingleClickEvent(view: View?) {
        // DO STUFF SINGLE CLICK
    }

    override fun onDoubleClickEvent(view: View?) {
       // DO STUFF DOUBLE CLICK
    }
})

button.setOnClickListener(doubleClick)

https://gitlab.com/developerdeveloperdeveloper/androidutilslibrary


问:
How to compare today's date and date stored in a string (without time)?
With python, How can I check if a date stored in a string has already passed?
My current code:

```<code>from datetime import date, datetime
date1 = date.today()

data2_str = '2018-06-25'
data2_obj = datetime.strptime(data2_str, '%Y-%m-%d')

print(date1<=data2_obj)

</code>```

The code above gives me the following error:

```<code>TypeError: can't compare datetime.datetime to datetime.date
</code>```

Note that I would not want to work with any time - just the date (this case the treated in 32287708)

答:
Use the .date() method to get the date component like this:

from datetime import date, datetime
date1 = date.today()

date2_str = '2018-06-25'
date2 = datetime.strptime(date2_str, '%Y-%m-%d').date()
print(date1<=date2)
```

<p>Output:</p>

```False
```

Body:
With python, How can I check if a date stored in a string has already passed?
My current code:

from datetime import date, datetime
date1 = date.today()

data2_str = '2018-06-25'
data2_obj = datetime.strptime(data2_str, '%Y-%m-%d')

print(date1<=data2_obj)

The code above gives me the following error:

TypeError: can't compare datetime.datetime to datetime.date

Note that I would not want to work with any time - just the date (this case the treated in 32287708)

Body:
Use the .date() method to get the date component like this:

from datetime import date, datetime
date1 = date.today()

date2_str = '2018-06-25'
date2 = datetime.strptime(date2_str, '%Y-%m-%d').date()
print(date1<=date2)

Output:

False


问:
how to handle alert boxes in KARATE UI testing
I have stared using Karate, as suggested by one of my client for our UI automation. it was some how going in good direction but as of now I am struggling to handle alert box on browser. I tried few things like switchFarme or input('body', Key.ENTER) but no success.
Can any one help me.</p>

答:
See if dialog() helps: https://github.com/intuit/karate/tree/master/karate-core#dialog

Else follow this process: https://github.com/intuit/karate/tree/develop/examples/ui-test


问:
How to check whether a Button is clicked by using JavaScript
Is there a simple way to do something along these lines:

JavaScript:

```<code>if(document.getElementById('button').clicked == true)
{
   alert("button was clicked");
}
</code>```

HTML:

```<code><input id="button" type="submit" name="button" value="enter"/>
</code>```

答:
All the answers here discuss about onclick method, however you can also use addEventListener().

Syntax of addEventListener()

```<code>document.getElementById('button').addEventListener("click",{function defination});
</code>```

The function defination above is known as anonymous function.

If you don't want to use anonymous functions you can also use function refrence.

```<code>function functionName(){
//function defination
}

document.getElementById('button').addEventListener("click",functionName);
</code>```

You can check the detail differences between onclick() and addEventListener() in this answer here.

Body:
Is there a simple way to do something along these lines:

JavaScript:

if(document.getElementById('button').clicked == true)
{
   alert("button was clicked");
}

HTML:

<input id="button" type="submit" name="button" value="enter"/>

Body:
All the answers here discuss about onclick method, however you can also use addEventListener().

Syntax of addEventListener()

document.getElementById('button').addEventListener("click",{function defination});

The function defination above is known as anonymous function.

If you don't want to use anonymous functions you can also use function refrence.

function functionName(){
//function defination
}

document.getElementById('button').addEventListener("click",functionName);

You can check the detail differences between onclick() and addEventListener() in this answer here.


问:
how do I play sound in line with the iphone system's sound settings
I have mimicked the iphone keyboard tap sound. My problem now is that the 'Tock' sound is louder than the normal keyboard sound, and it still sounds even when keyboard clicks is disabled in the sounds setting on the phone.</p>

答: I don't believe there is any access to the preferences set in the iPhone settings.app</p>


问:
Preset jest-puppeteer is invalid
in a working jest + puppeteer project,
i'm moving to jest-circus in order to use the jest-circus retry feature.
As documented, i installed jest-circus and i set as runner but running test as usual i obtain

```<code> Validation Error:

  Preset jest-puppeteer is invalid:

  The "id" argument must be of type string. Received type object
  TypeError [ERR_INVALID_ARG_TYPE]: The "id" argument must be of type string. Received type object
    at validateString (internal/validators.js:112:11)
    at Module.require (internal/modules/cjs/loader.js:842:3)
    at require (internal/modules/cjs/helpers.js:74:18)
    at setupPreset (C:\src\qa-e2e-update-stack\node_modules\jest-config\build\normalize.js:348:14)
    at normalize (C:\src\qa-e2e-update-stack\node_modules\jest-config\build\normalize.js:703:15)
    at readConfig (C:\src\qa-e2e-update-stack\node_modules\jest-config\build\index.js:220:68)
    at async readConfigs (C:\src\qa-e2e-update-stack\node_modules\jest-config\build\index.js:401:26)
    at async runCLI (C:\src\qa-e2e-update-stack\node_modules\@jest\core\build\cli\index.js:203:59)
    at async Object.run (C:\src\qa-e2e-update-stack\node_modules\jest\node_modules\jest-cli\build\cli\index.js:216:37)

  Configuration Documentation:
  https://jestjs.io/docs/configuration.html
</code>```

this is my jest.config.js file

```<code>const fs = require('fs')
reportFolder = "reports"
if (!fs.existsSync(reportFolder)){
    fs.mkdirSync(reportFolder)
}

module.exports = {
    preset: "jest-puppeteer",
    testRunner: "jest-circus/runner",
    setupFilesAfterEnv: [  // NOT setupFiles
        "./configurazioni/custom-configuration.js",
        "./configurazioni/shared-require.js",
        "jest-allure/dist/setup"
    ],
    "reporters": [
        "default",
        ["./node_modules/jest-html-reporter", {
            "pageTitle": "Test Report",
            "includeFailureMsg": true,
            "includeConsoleLog": true,
            "outputPath":"reports/"+new Date().getDate() + "-" +
                (new Date().getMonth() + 1) + "-"
                + new Date().getFullYear()+ "-"
                + new Date().getHours().toString() + "-"
                + (new Date().getMinutes() + 1 ).toString() + "-"
                + (new Date().getSeconds() + 1 ).toString()
                +"-run.html"
        }],
        ["jest-junit", { outputName: "reports/junitreport.xml" }]
    ],
    moduleNameMapper: {
        '^\\$lib\/(.*)': `<rootDir>/lib/$1`,
    },
};
</code>```

i don't found any page talking about my issue, jest-circus and jest-preset cannot coexists?

答: I would suggest to check whether your node packages are properly installed. I encountered the very same issue when my node_modules folder got deleted. </p>

Title: Preset jest-puppeteer is invalid

Body:
in a working jest + puppeteer project,
i'm moving to jest-circus in order to use the jest-circus retry feature.
As documented, i installed jest-circus and i set as runner but running test as usual i obtain

 Validation Error:

  Preset jest-puppeteer is invalid:

  The "id" argument must be of type string. Received type object
  TypeError [ERR_INVALID_ARG_TYPE]: The "id" argument must be of type string. Received type object
    at validateString (internal/validators.js:112:11)
    at Module.require (internal/modules/cjs/loader.js:842:3)
    at require (internal/modules/cjs/helpers.js:74:18)
    at setupPreset (C:\src\qa-e2e-update-stack\node_modules\jest-config\build\normalize.js:348:14)
    at normalize (C:\src\qa-e2e-update-stack\node_modules\jest-config\build\normalize.js:703:15)
    at readConfig (C:\src\qa-e2e-update-stack\node_modules\jest-config\build\index.js:220:68)
    at async readConfigs (C:\src\qa-e2e-update-stack\node_modules\jest-config\build\index.js:401:26)
    at async runCLI (C:\src\qa-e2e-update-stack\node_modules\@jest\core\build\cli\index.js:203:59)
    at async Object.run (C:\src\qa-e2e-update-stack\node_modules\jest\node_modules\jest-cli\build\cli\index.js:216:37)

  Configuration Documentation:
  https://jestjs.io/docs/configuration.html

this is my jest.config.js file

const fs = require('fs')
reportFolder = "reports"
if (!fs.existsSync(reportFolder)){
    fs.mkdirSync(reportFolder)
}

module.exports = {
    preset: "jest-puppeteer",
    testRunner: "jest-circus/runner",
    setupFilesAfterEnv: [  // NOT setupFiles
        "./configurazioni/custom-configuration.js",
        "./configurazioni/shared-require.js",
        "jest-allure/dist/setup"
    ],
    "reporters": [
        "default",
        ["./node_modules/jest-html-reporter", {
            "pageTitle": "Test Report",
            "includeFailureMsg": true,
            "includeConsoleLog": true,
            "outputPath":"reports/"+new Date().getDate() + "-" +
                (new Date().getMonth() + 1) + "-"
                + new Date().getFullYear()+ "-"
                + new Date().getHours().toString() + "-"
                + (new Date().getMinutes() + 1 ).toString() + "-"
                + (new Date().getSeconds() + 1 ).toString()
                +"-run.html"
        }],
        ["jest-junit", { outputName: "reports/junitreport.xml" }]
    ],
    moduleNameMapper: {
        '^\\$lib\/(.*)': `<rootDir>/lib/$1`,
    },
};

i don't found any page talking about my issue, jest-circus and jest-preset cannot coexists?


问:
How to write a RWD css for all devices?
I have designed 3 Different devices, hoping each device can perform normally whether screen is vertical or horizontal, left menu can choose zoom or shrink.  but now I’m stuck, I found that set up for above
2K HD is a disaster, without showing all selections.  How to fix this to allow all
menu to follow for all devices.  I hope that menu’s font and spacing can be automatically adjust by percentage according to various solution.

http://www.ecotw.com.tw/vicky/hl-doc/

display in my device

/* display in laptop */
.hide-phone{display:none}
@media only screen and (max-width:1366px) {
.hide-phone { display: block; } }

/* display in tablet */
.show-tablet{display:none}
@media only screen and (min-width:1024px) {
.show-tablet { display: block; } }

/* display in mobile phone */
.show-phone{display:none}
@media only screen and (min-width:980px) {
.show-phone { display: block; } }

.tablet {display: none;}
@media(max-width:1024px){
    .mobile {
        display: none;
    }
    .tablet {
        display: block;
    }
    .desktop {
        display: none;
    }
}

.mobile {display: none;}
@media(max-width:980px){
    .mobile {
        display: block;
    }
    .tablet {
        display: none;
    }
    .desktop {
        display: none;
    }
}

/*===== topmenu/laptop =====*/
.topmenu {
    margin: 0 auto;
}

.topmenu li a{
 font-size:18px;
 color:#eee;
    padding: 15px;
}

.topmenu li a {
    padding: 15px; }
    @media (min-width: 1400px) {
      .topmenu li a {
        padding: 40px; } }

.topmenu li a:hover {
 font-size:18px;
 color: #fff;
 font-weight:bold;
}

/*===== topmenu/tablet =====*/
.topmenu-tablet {
    margin: 0 auto;
}

.topmenu-tablet li a{
 font-size:12px;
 color:#eee;
    padding: 10px;
}

.topmenu-tablet li a:hover {
 font-size:12px;
 color: #fff;
 font-weight:bold;
}

.topmenu-tablet li a {
    padding: 12px; }
    @media (min-width: 1366px) {
      .topmenu-tablet li a {
        padding: 40px; } }

/*===== topmenu/mobile phone =====*/
.topmenu-mobile{
 margin: 0 auto;}

.topmenu-mobile li a{
 font-size:18px;
 color:#eee;
    padding-right: 6px;
    padding-left: 6px;
}

.topmenu-mobile li a:hover {
 font-size:18px;
 color: #fff;
 font-weight:bold;
}```

答:
```<code>@media screen and (min-width: 1401px) and (max-width: 1599px) {
.topmenu li a, .topmenu li a:hover {
    font-size: 110%;
    padding: 15px;
  }
}
@media screen and (min-width: 1600px) and (max-width: 1919px) {
.topmenu li a, .topmenu li a:hover {
    font-size: 120%;
    padding: 20px;
  }
}
@media screen and (min-width: 1920px)and (max-width: 2387px) {
.topmenu li a, .topmenu li a:hover {
    font-size: 125%;
    padding: 30px;
  }
}

@media screen and (min-width: 2388px) {
.topmenu li a, .topmenu li a:hover {
    font-size: 130%;
    padding: 35px;
  }
}
</code>```

Title: How to write a RWD css for all devices?


问:
My app stops when I open it with 4.2 "api 16"?
When I open my app with samsung s3 its not opening.  It works with other versions.

This is the error:

My app works well with higher versions and my database is back4app.

My minsdk is 15.

答:
Try adding this to your manifest </p>

```<code><provider android:authorities="com.facebook.app.FacebookContentProvider{app id here}"
            android:name="com.facebook.FacebookContentProvider"
            android:exported="false"/>
</code>```

Body:
Try adding this to your manifest

<provider android:authorities="com.facebook.app.FacebookContentProvider{app id here}"
            android:name="com.facebook.FacebookContentProvider"
            android:exported="false"/>


问:
Access VBA to open/activate a database table
I have an open MS Access database with 20 tables showing in the left and two tabs open showing the contents of two tables. I am trying to write vba code to 1) select/activate one of the tabs that is already open, and 2) to open a new tab for one of the tables on the left that is not yet open.

I've looked at many examples, but they all talk about Forms, not the tab control/tabs that I want to work with in the main Access table display. Here's my code so far - I can get the name of the table, but I can't figure out how to open and activate a tab for the table in the Access display.

```<code>Sub ActivateCommandsTable()
 ' activate or open a tab for the Commands table
 Dim tbl As AccessObject, db As Object
 Set db = Application.CurrentData

 ' Search for open AccessObject objects in AllTables collection.
 For Each tbl In db.AllTables

 If tbl.IsLoaded = True Then
    ' Print name of the table
    Debug.Print tbl.name
    If tbl.name = "Commands" Then

        ' I need some code here to activate/open the table tab

        Exit Sub
    End If
 End If

 Next tbl
End Sub
</code>```

答:
Just use DoCmd.OpenTable.

DoCmd.OpenTable tbl.Name

Body:
I have an open MS Access database with 20 tables showing in the left and two tabs open showing the contents of two tables. I am trying to write vba code to 1) select/activate one of the tabs that is already open, and 2) to open a new tab for one of the tables on the left that is not yet open.

I've looked at many examples, but they all talk about Forms, not the tab control/tabs that I want to work with in the main Access table display. Here's my code so far - I can get the name of the table, but I can't figure out how to open and activate a tab for the table in the Access display.

Sub ActivateCommandsTable()
 ' activate or open a tab for the Commands table
 Dim tbl As AccessObject, db As Object
 Set db = Application.CurrentData

 ' Search for open AccessObject objects in AllTables collection.
 For Each tbl In db.AllTables

 If tbl.IsLoaded = True Then
    ' Print name of the table
    Debug.Print tbl.name
    If tbl.name = "Commands" Then

        ' I need some code here to activate/open the table tab

        Exit Sub
    End If
 End If

 Next tbl
End Sub


问:
Cannot perform prop function onClick when usnig stateless functions
I can't seem to get my modal button to run the function I have passed into it.

Am I missing something?

Dashboard.js

```<code>const Dashboard = () => {

    let show = false;

    const showModal = () => {
        console.log('showing modal');
    };

    const hideModal = () => {
        console.log('closing modal');
    };

    return (
        <div>
            <h1>This is the dashboard</h1>
            <button type="button" onClick={showModal}>Open</button>
            <Modal handleClose={hideModal} show={show}/>
        </div>
    )
};

export default Dashboard;
</code>```

Modal.js

```<code>const Modal = (handleClose, show, children) => {
    const showHideClass = show ? 'show-modal' : 'hide-modal';

    return (
        <div className={showHideClass}>
            <h1>This is my modal!</h1>
            <p>{children}</p>
            <button onClick={handleClose}>Close</button>
        </div>
    );
};

export default Modal;
</code>```

I had the warning: Expected 'onClick' listener to be a function, instead got a value of 'object' type., so I changed the onClick in modal.js to () => handleClose which dismissed the warning, however nothing happened when I clicked the button...

答:
The Solution

The issue you're having is you're not destructuring the props object that's passed in.

```<code>const Modal = (handleClose, show, children) => {
</code>```

should instead put curly braces around the arguments

```<code>const Modal = ({handleClose, show, children}) => {
</code>```

Brief Explanation

The props passed to a functional component are a single object with keys that correspond to the name of the object passed in. The object's shape would be:

```<code>{
   handleClose: [function],
   show: true,
   children: ...
}
</code>```

To get the props, you can either have a single argument (idiomatically named props), and then access values from that object:

```<code>const Hello = (props) => {
   console.log(props.message);
}
</code>```

Or you can use a destructuring assignment (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) to extract the props in the function arguments:

```<code>const Hello = ({message}) => {
   console.log(message);
}
</code>```

Body:
I can't seem to get my modal button to run the function I have passed into it.

Am I missing something?

Dashboard.js

const Dashboard = () => {

    let show = false;

    const showModal = () => {
        console.log('showing modal');
    };

    const hideModal = () => {
        console.log('closing modal');
    };

    return (

This is the dashboard

            <button type="button" onClick={showModal}>Open</button>
            <Modal handleClose={hideModal} show={show}/>

    )
};

export default Dashboard;

Modal.js

const Modal = (handleClose, show, children) => {
    const showHideClass = show ? 'show-modal' : 'hide-modal';

    return (

This is my modal!

{children}

            <button onClick={handleClose}>Close</button>

    );
};

export default Modal;

I had the warning: Expected 'onClick' listener to be a function, instead got a value of 'object' type., so I changed the onClick in modal.js to () => handleClose which dismissed the warning, however nothing happened when I clicked the button...

Body:
The Solution

The issue you're having is you're not destructuring the props object that's passed in.

const Modal = (handleClose, show, children) => {

should instead put curly braces around the arguments

const Modal = ({handleClose, show, children}) => {

Brief Explanation

The props passed to a functional component are a single object with keys that correspond to the name of the object passed in. The object's shape would be:

{
   handleClose: [function],
   show: true,
   children: ...
}

To get the props, you can either have a single argument (idiomatically named props), and then access values from that object:

const Hello = (props) => {
   console.log(props.message);
}

Or you can use a destructuring assignment (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) to extract the props in the function arguments:

const Hello = ({message}) => {
   console.log(message);
}


问:
How to test within the same module?
In this project I have a modular setup. There is a parent with two modules in it.

Here's a snippet from the parent-pom.xml:

```<code><modules>
    <module>moduleA</module>
    <module>moduleB</module>
</modules>
</code>```

Both modules have a module-info.java. Here is the module-info.java for moduleB:

```<code>module moduleB {
    requires spring.web;
    requires static lombok;
    requires java.validation;
    requires swagger.annotations;
    requires slf4j.api;
    exports com.example.service
}
</code>```

Within moduleB there is the main folder and the test folder, like any regular java project. Within the test-folder there is a JUnit5 test, which is trying to test a service within the same package, but in the src-folder.

While trying to attempt this, I get the following error-message:

```<code>module moduleB does not "opens com.example.service" to unnamed module @67205a84
</code>```

As I understand, all of the dependencies which are not part of the module will be packaged in an 'unnamed' module. In this case module @67205a84. Things I expect to be in this module are stuff like Mockito, which I only use for testing. Please correct me if I'm wrong about this assumption.

When I open up my moduleB (by adding the word 'open' before the moduledecleration), the test runs smoothly. But obviously this is not what I want.

So my question really is: can I open up to the unnamed module so that my tests can run, but my module stays closed for anything other than the test?

Here's a simplified overview of the directory structure.

```<code>- parent
  |
  -> - pom.xml
     - moduleA
     - moduleB
       |
       -> - pom.xml
          - src
            |
            -> - main
                 |
                 -> - java
                      |
                      -> - module.info
                         - com.example.service
                           |
                           -> - ModuleBService.java
               - test
                 |
                 -> - java
                      |
                      -> - com.example
                           |
                           -> - Application.java
                         - com.example.service
                           |
                           -> - ModuleBServiceTest.java
</code>```

As it turns out, the location of the Application.class is relevant. The module I am trying to test does not have a class annotated with @SpringbootApplication, because it's just a library. To test it's functionality, I have to start a SpringbootApplication in test. When the Application.java is in the same package as the ModuleBServiceTest.java, all is well. When I move it out in another package the error-message from above occurs. Why is that?

答:
What you can do is to configure the surefire plugin to open the module to the unnamed modules in the POM of your moduleB

<build>
  <plugins>
    <plugin>
      <artifactId>maven-surefire-plugin</artifactId>
      <configuration>
        <argLine>

          --add-opens moduleB/com.example.service=ALL-UNNAMED

          --add-exports moduleB/com.example.service.test.util=moduleC

          --illegal-access=deny
        </argLine>
      </configuration>
    </plugin>
  </plugins>
</build>
```

I've also added a sample where you can explicitly export some test utility classes to a further module in case it wants to access these

As it turns out, the location of the Application.class is relevant. The module I am trying to test does not have a class annotated with @SpringbootApplication, because it's just a library. To test it's functionality, I have to start a SpringbootApplication in test. When the Application.java is in the same package as the ModuleBServiceTest.java, all is well. When I move it out in another package the error-message from above occurs. Why is that?

AFAIK Spring Boot will scan its package and any sub-packages for components, services and the like and will add these automatically to its configuration. If the application is not directly in an ancestor path it might not be able to find your test class, though the information given is a bit limited to be honest.

Title: How to test within the same module?

Body:
In this project I have a modular setup. There is a parent with two modules in it.

Here's a snippet from the parent-pom.xml:

<modules>
    <module>moduleA</module>
    <module>moduleB</module>
</modules>

Both modules have a module-info.java. Here is the module-info.java for moduleB:

module moduleB {
    requires spring.web;
    requires static lombok;
    requires java.validation;
    requires swagger.annotations;
    requires slf4j.api;
    exports com.example.service
}

Within moduleB there is the main folder and the test folder, like any regular java project. Within the test-folder there is a JUnit5 test, which is trying to test a service within the same package, but in the src-folder.

While trying to attempt this, I get the following error-message:

module moduleB does not "opens com.example.service" to unnamed module @67205a84

As I understand, all of the dependencies which are not part of the module will be packaged in an 'unnamed' module. In this case module @67205a84. Things I expect to be in this module are stuff like Mockito, which I only use for testing. Please correct me if I'm wrong about this assumption.

When I open up my moduleB (by adding the word 'open' before the moduledecleration), the test runs smoothly. But obviously this is not what I want.

So my question really is: can I open up to the unnamed module so that my tests can run, but my module stays closed for anything other than the test?

Here's a simplified overview of the directory structure.

- parent
  |
  -> - pom.xml
     - moduleA
     - moduleB
       |
       -> - pom.xml
          - src
            |
            -> - main
                 |
                 -> - java
                      |
                      -> - module.info
                         - com.example.service
                           |
                           -> - ModuleBService.java
               - test
                 |
                 -> - java
                      |
                      -> - com.example
                           |
                           -> - Application.java
                         - com.example.service
                           |
                           -> - ModuleBServiceTest.java

As it turns out, the location of the Application.class is relevant. The module I am trying to test does not have a class annotated with @SpringbootApplication, because it's just a library. To test it's functionality, I have to start a SpringbootApplication in test. When the Application.java is in the same package as the ModuleBServiceTest.java, all is well. When I move it out in another package the error-message from above occurs. Why is that?

Body:
What you can do is to configure the surefire plugin to open the module to the unnamed modules in the POM of your moduleB

<build>
  <plugins>
    <plugin>
      <artifactId>maven-surefire-plugin</artifactId>
      <configuration>
        <argLine>
          <!-- Allow access to the tests during test time -->
          --add-opens moduleB/com.example.service=ALL-UNNAMED
          <!-- Add export to test-util classes to moduleC if it wants to reuse these -->
          --add-exports moduleB/com.example.service.test.util=moduleC
          <!-- Prevent any illegal access to modules -->
          --illegal-access=deny
        </argLine>
      </configuration>
    </plugin>
  </plugins>
</build>

I've also added a sample where you can explicitly export some test utility classes to a further module in case it wants to access these

As it turns out, the location of the Application.class is relevant. The module I am trying to test does not have a class annotated with @SpringbootApplication, because it's just a library. To test it's functionality, I have to start a SpringbootApplication in test. When the Application.java is in the same package as the ModuleBServiceTest.java, all is well. When I move it out in another package the error-message from above occurs. Why is that?

AFAIK Spring Boot will scan its package and any sub-packages for components, services and the like and will add these automatically to its configuration. If the application is not directly in an ancestor path it might not be able to find your test class, though the information given is a bit limited to be honest.


问:
Move data from one set of columns to another for a subset of rows
I have a dataframe...

```<code>df <- tibble(
  id = 1:10,
  family = c("a","a","b","b","c", "d", "e", "f", "g", "h"),
  col1_a = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
  col1_b = c(1, 2, 3, 4, NA, NA, NA, NA, NA, NA),
  col2_a = c(11, 12, 13, 14, 15, 16, 17, 18, 19, 20),
  col2_b = c(11, 12, 13, 14, NA, NA, NA, NA, NA, NA),
  )
</code>```

Families will only contain 2 members at most (so they're either individuals or pairs).

For individuals (families with only one row, i.e. id = 5:10), I want to randomly move 50% of the data from columns ending in 'a' to columns ending in 'b'.

By the end, the data should look like the following (depending on which 50% of rows are used)...

```<code>df <- tibble(
  id = 1:10,
  family = c("a","a","b","b","c", "d", "e", "f", "g", "h"),
  col1_a = c(1, 2, 3, 4, 5, NA, 7, NA, 9, NA),
  col1_b = c(1, 2, 3, 4, NA, 6, NA, 8, NA, 10),
  col2_a = c(11, 12, 13, 14, NA, NA, 17, 18, NA, 20),
  col2_b = c(11, 12, 13, 14, 15, 16, NA, NA, 19, NA),
  )
</code>```

I would like to be able to do this with a combination of group_by and mutate since I am mostly using Tidyverse.

Update: I forgot to mention that values in columns ending 'a' should be replaced with NA if they are moved across to 'b'.

答:
I would do this in two primary steps, first create the fam_count column to determine which families only have 1 person. Then, create two rand columns, to determine whether or not we use the values in the b columns.

```<code>library(tidyverse)
set.seed(1)

df %>% group_by(family) %>%
  mutate(fam_count = n()) %>%
  ungroup() %>%
  mutate(
    rand1 = sample(c(NA, 1), nrow(.), replace = TRUE),
    rand2 = sample(c(NA, 1), nrow(.), replace = TRUE),
    col1_b = ifelse(fam_count == 1, rand1 * col1_a, col1_b),
    col2_b = ifelse(fam_count == 1, rand2 * col2_a, col2_b)
  ) %>%
  mutate(
    col1_a = ifelse(fam_count == 1 & !is.na(col1_b), NA, col1_a),
    col2_a = ifelse(fam_count == 1 & !is.na(col2_b), NA, col2_a)
  ) %>%
  select(-rand1, -rand2, - fam_count)

# A tibble: 10 x 6
      id family col1_a col1_b col2_a col2_b
   <int> <chr>   <int>  <dbl>  <int>  <dbl>
 1     1 a           1      1     11     11
 2     2 a           2      2     12     12
 3     3 b           3      3     13     13
 4     4 b           4      4     14     14
 5     5 c           5     NA     NA     15
 6     6 d           6     NA     NA     16
 7     7 e          NA      7     17     NA
 8     8 f           8     NA     NA     18
 9     9 g          NA      9     19     NA
10    10 h          10     NA     20     NA
</code>```

Body:
I have a dataframe...

df <- tibble(
  id = 1:10,
  family = c("a","a","b","b","c", "d", "e", "f", "g", "h"),
  col1_a = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
  col1_b = c(1, 2, 3, 4, NA, NA, NA, NA, NA, NA),
  col2_a = c(11, 12, 13, 14, 15, 16, 17, 18, 19, 20),
  col2_b = c(11, 12, 13, 14, NA, NA, NA, NA, NA, NA),
  )

Families will only contain 2 members at most (so they're either individuals or pairs).

For individuals (families with only one row, i.e. id = 5:10), I want to randomly move 50% of the data from columns ending in 'a' to columns ending in 'b'.

By the end, the data should look like the following (depending on which 50% of rows are used)...

df <- tibble(
  id = 1:10,
  family = c("a","a","b","b","c", "d", "e", "f", "g", "h"),
  col1_a = c(1, 2, 3, 4, 5, NA, 7, NA, 9, NA),
  col1_b = c(1, 2, 3, 4, NA, 6, NA, 8, NA, 10),
  col2_a = c(11, 12, 13, 14, NA, NA, 17, 18, NA, 20),
  col2_b = c(11, 12, 13, 14, 15, 16, NA, NA, 19, NA),
  )

I would like to be able to do this with a combination of group_by and mutate since I am mostly using Tidyverse.

Update: I forgot to mention that values in columns ending 'a' should be replaced with NA if they are moved across to 'b'.

Body:
I would do this in two primary steps, first create the fam_count column to determine which families only have 1 person. Then, create two rand columns, to determine whether or not we use the values in the b columns.

library(tidyverse)
set.seed(1)

df %>% group_by(family) %>%
  mutate(fam_count = n()) %>%
  ungroup() %>%
  mutate(
    rand1 = sample(c(NA, 1), nrow(.), replace = TRUE),
    rand2 = sample(c(NA, 1), nrow(.), replace = TRUE),
    col1_b = ifelse(fam_count == 1, rand1 * col1_a, col1_b),
    col2_b = ifelse(fam_count == 1, rand2 * col2_a, col2_b)
  ) %>%
  mutate(
    col1_a = ifelse(fam_count == 1 & !is.na(col1_b), NA, col1_a),
    col2_a = ifelse(fam_count == 1 & !is.na(col2_b), NA, col2_a)
  ) %>%
  select(-rand1, -rand2, - fam_count)

# A tibble: 10 x 6
      id family col1_a col1_b col2_a col2_b
   <int> <chr>   <int>  <dbl>  <int>  <dbl>
 1     1 a           1      1     11     11
 2     2 a           2      2     12     12
 3     3 b           3      3     13     13
 4     4 b           4      4     14     14
 5     5 c           5     NA     NA     15
 6     6 d           6     NA     NA     16
 7     7 e          NA      7     17     NA
 8     8 f           8     NA     NA     18
 9     9 g          NA      9     19     NA
10    10 h          10     NA     20     NA