问:
May I destroy a mutexattr object before the mutex that was initialized with this mutexattr is used?
Consider the following code:

```<code>pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_setrobust(&attr, PTHREAD_MUTEX_ROBUST);

pthread_mutex_t mut;
pthread_mutex_init(&mut, &attr);

pthread_mutexattr_destroy(&attr);

pthread_mutex_lock(&mut);
</code>```

Is this code valid?

If the mutex is allowed to contain references to the attribute object it was initialized with, then I suppose I may not call pthread_mutexattr_destroy(&attr) before using the mutex.

答:
Like the manual say:

After a mutex attributes object has been used to initialize one or more mutexes, any function affecting the attributes object (including destruction) shall not affect any previously initialized mutexes.

So your code is valid (but don't forget to check the potential error of these functions).

Body:
Consider the following code:

pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_setrobust(&attr, PTHREAD_MUTEX_ROBUST);

pthread_mutex_t mut;
pthread_mutex_init(&mut, &attr);

pthread_mutexattr_destroy(&attr);

pthread_mutex_lock(&mut);

Is this code valid?

If the mutex is allowed to contain references to the attribute object it was initialized with, then I suppose I may not call pthread_mutexattr_destroy(&attr) before using the mutex.


来源: stackexchange

问:
how can refresh list when click button in item listview
i have recyclerview and button on the all item of list. when i click the button in my adapter item deleted and i want refresh recycler and show new data.</p>

```<code>@Override
  public void onBindViewHolder(final LietnerViewHolder holder, final int position) {
    lietner = lietners.get(position);
    holder.txt_en.setText(lietner.getText_en());
    holder.txt_pe.setText(lietner.getText_pe());
    holder.time.setText(lietner.getTime());
    holder.data.setText(HelperCalendar.g2j(lietner.getTime_create()));
    holder.next_level.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
      G.databaseOpenHelper.goToNextLevel(lietners.get(position).getId());

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

答:
i do this and it work for me!</p>

```<code>@Override
  public void onBindViewHolder(final LietnerViewHolder holder, final int position) {
    lietner = lietners.get(position);
    holder.txt_en.setText(lietner.getText_en());
    holder.txt_pe.setText(lietner.getText_pe());
    holder.time.setText(lietner.getTime());
    holder.data.setText(HelperCalendar.g2j(lietner.getTime_create()));
    holder.next_level.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        G.databaseOpenHelper.goToNextLevel(lietners.get(position).getId());
        lietners.remove(position);
        notifyDataSetChanged();
      }
    });
  }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i have recyclerview and button on the all item of list. when i click the button in my adapter item deleted and i want refresh recycler and show new data.

@Override
  public void onBindViewHolder(final LietnerViewHolder holder, final int position) {
    lietner = lietners.get(position);
    holder.txt_en.setText(lietner.getText_en());
    holder.txt_pe.setText(lietner.getText_pe());
    holder.time.setText(lietner.getTime());
    holder.data.setText(HelperCalendar.g2j(lietner.getTime_create()));
    holder.next_level.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
      G.databaseOpenHelper.goToNextLevel(lietners.get(position).getId());

      }
    });
  }

Body:
i do this and it work for me!

@Override
  public void onBindViewHolder(final LietnerViewHolder holder, final int position) {
    lietner = lietners.get(position);
    holder.txt_en.setText(lietner.getText_en());
    holder.txt_pe.setText(lietner.getText_pe());
    holder.time.setText(lietner.getTime());
    holder.data.setText(HelperCalendar.g2j(lietner.getTime_create()));
    holder.next_level.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        G.databaseOpenHelper.goToNextLevel(lietners.get(position).getId());
        lietners.remove(position);
        notifyDataSetChanged();
      }
    });
  }


问:
how can i split a string if there is a period and then a space?
Right now I am using .split(/(?<=[.])/) which splits keeps the period.

```<code>string = "Going home. See you soon."
</code>```

=> ["Going home.", "See you soon."]

But what I need is to split on and keep ". "

答:
Using look-behind assertion, you can match space () following . ((?<=\.)):

```<code>string = "Going home. See you soon."
string.split(/(?<=\.) /)
=> ["Going home.", "See you soon."]
</code>```

Body:
Right now I am using .split(/(?<=[.])/) which splits keeps the period.

string = "Going home. See you soon."

=> ["Going home.", "See you soon."]

But what I need is to split on and keep ". "

Body:
Using look-behind assertion, you can match space () following . ((?<=\.)):

string = "Going home. See you soon."
string.split(/(?<=\.) /)
=> ["Going home.", "See you soon."]


问:
Can't detect null value from JSON_EXTRACT
I have a database that has an array of data stored in a JSON column. I need to find all values that have a null value at a particular position in the JSON array. While pulling out the data with JSON_EXTRACT seemed trivial, none of my comparisons to null have worked, all of them claiming the value is null.

Here is the example code that should work as far as I can tell:

```<code>SELECT JSON_EXTRACT(`COLUMNS_HEADERS`, '$[1]') , (JSON_EXTRACT(`COLUMNS_HEADERS`, '$[1]') is null)
FROM ate.readings_columns_new;
</code>```

The first few rows of my results table look like this:

```<code>null                    |   0
"INTERNALTEMPERATURE"   |   0
"INPUT_VOLTAGE"         |   0
null                    |   0
null                    |   0
"AH1"                   |   0
</code>```

I have tried every comparison I can think of, and they all result in a 0:

```<code>(JSON_EXTRACT(`COLUMNS_HEADERS`, '$[1]') is null)
(JSON_EXTRACT(`COLUMNS_HEADERS`, '$[1]') <=> null)
ISNULL(JSON_EXTRACT(`COLUMNS_HEADERS`, '$[1]'))
(JSON_EXTRACT(`COLUMNS_HEADERS`, '$[1]') <=> 'null')
</code>```

Is there some key to comparing null values pulled from a JSON_EXTRACT?

答:
A bit of a belated answer but I just hit this problem and couldn't find anything reasonably documented.  The solution I ended ended up using was the json_type function as 'abl' pointed out above.

The trick was to compare with the string 'NULL' not null or NULL.

As a test throw the following into a mysql prompt and play around with the values

(if using phpMyAdmin don't forget to check 'show this query here again' and  'retain query box' - the universe is frustrating enough without losing edits..)

```<code>set @a='{"a":3,"b":null}';

select if(json_type(json_extract(@a,'$.b')) = 'NULL',1,0);
</code>```

I ended up with the following.

```<code>mysql> set @a='{"a":3,"b":null}';
Query OK, 0 rows affected (0.00 sec)

mysql> select if(json_type(json_extract(@a,'$.b')) = 'NULL',1,0);
+----------------------------------------------------+
| if(json_type(json_extract(@a,'$.b')) = 'NULL',1,0) |
+----------------------------------------------------+
|                                                  1 |
+----------------------------------------------------+
1 row in set (0.00 sec)

mysql> set @a='{"a":3,"b":1}';
Query OK, 0 rows affected (0.00 sec)

mysql> select if(json_type(json_extract(@a,'$.b')) = 'NULL',1,0);
+----------------------------------------------------+
| if(json_type(json_extract(@a,'$.b')) = 'NULL',1,0) |
+----------------------------------------------------+
|                                                  0 |
+----------------------------------------------------+
1 row in set (0.00 sec)
</code>```

As the bare bones of a stored procedure - which is what I needed it for - using the 'if' statements rather than the if() function.

```<code>drop procedure if exists test;
delimiter $$

create procedure test(in x json)
begin

if json_type(json_extract(x,'$.b')) = 'NULL' then
  select 1;
else
  select 0;
end if;

end$$

delimiter;

mysql> call test('{"a":3,"b":1}');
+---+
| 0 |
+---+
| 0 |
+---+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

mysql> call test('{"a":3,"b":null}');
+---+
| 1 |
+---+
| 1 |
+---+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)
</code>```

Body:
I have a database that has an array of data stored in a JSON column. I need to find all values that have a null value at a particular position in the JSON array. While pulling out the data with JSON_EXTRACT seemed trivial, none of my comparisons to null have worked, all of them claiming the value is null.

Here is the example code that should work as far as I can tell:

SELECT JSON_EXTRACT(`COLUMNS_HEADERS`, '$[1]') , (JSON_EXTRACT(`COLUMNS_HEADERS`, '$[1]') is null)
FROM ate.readings_columns_new;

The first few rows of my results table look like this:

null                    |   0
"INTERNALTEMPERATURE"   |   0
"INPUT_VOLTAGE"         |   0
null                    |   0
null                    |   0
"AH1"                   |   0

I have tried every comparison I can think of, and they all result in a 0:

(JSON_EXTRACT(`COLUMNS_HEADERS`, '$[1]') is null)
(JSON_EXTRACT(`COLUMNS_HEADERS`, '$[1]') <=> null)
ISNULL(JSON_EXTRACT(`COLUMNS_HEADERS`, '$[1]'))
(JSON_EXTRACT(`COLUMNS_HEADERS`, '$[1]') <=> 'null')

Is there some key to comparing null values pulled from a JSON_EXTRACT?

Body:
A bit of a belated answer but I just hit this problem and couldn't find anything reasonably documented.  The solution I ended ended up using was the json_type function as 'abl' pointed out above.

The trick was to compare with the string 'NULL' not null or NULL.

As a test throw the following into a mysql prompt and play around with the values

(if using phpMyAdmin don't forget to check 'show this query here again' and  'retain query box' - the universe is frustrating enough without losing edits..)

set @a='{"a":3,"b":null}';

select if(json_type(json_extract(@a,'$.b')) = 'NULL',1,0);

I ended up with the following.

mysql> set @a='{"a":3,"b":null}';
Query OK, 0 rows affected (0.00 sec)

mysql> select if(json_type(json_extract(@a,'$.b')) = 'NULL',1,0);
+----------------------------------------------------+
| if(json_type(json_extract(@a,'$.b')) = 'NULL',1,0) |
+----------------------------------------------------+
|                                                  1 |
+----------------------------------------------------+
1 row in set (0.00 sec)

mysql> set @a='{"a":3,"b":1}';
Query OK, 0 rows affected (0.00 sec)

mysql> select if(json_type(json_extract(@a,'$.b')) = 'NULL',1,0);
+----------------------------------------------------+
| if(json_type(json_extract(@a,'$.b')) = 'NULL',1,0) |
+----------------------------------------------------+
|                                                  0 |
+----------------------------------------------------+
1 row in set (0.00 sec)

As the bare bones of a stored procedure - which is what I needed it for - using the 'if' statements rather than the if() function.

drop procedure if exists test;
delimiter $$

create procedure test(in x json)
begin

if json_type(json_extract(x,'$.b')) = 'NULL' then
  select 1;
else
  select 0;
end if;

end$$

delimiter;

mysql> call test('{"a":3,"b":1}');
+---+
| 0 |
+---+
| 0 |
+---+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

mysql> call test('{"a":3,"b":null}');
+---+
| 1 |
+---+
| 1 |
+---+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)


问:
Meteor.logout() and Meteor.call() too slow
I have a web app. I am living a problem about time of Meteor.logout() and Meteor.call(). When i meteor.logout(), it takes time between about 30-40 sec. Same for Meteor.call() as well. About 200-250 clients use this system on the same time.

if a client see about 100-200 items his on app screen this delay time is so much. but 10-20 items, it's a little well. we get data every 5-10 sec as different times each others on these items. I mean, live screen.

I don't get this problem when i work this system on diffrent port with same code and same database by the way just use only me.

I can't figure it. What can be reason it. I need your ideas and help.

答:
You can use this.unblock() in every method and publications.
By default, Meteor process requests one by one, it will queue all the requests coming, if one is processing.

This may be due to the reason that some of the functions doing some bigger functionalities will be requiring more time and all other request to the server have to wait till it ends.

You need to simply place this.unblock() at the starting of every method and publications and it will not block your requests.
Thanks


问:
JavaScript - Search object property by key and add its value to array
Let's say I have an object like this:

```<code>var object =  {
  "Defender": {
    "player-1868": {
      "birthdate": "1 July 1996",
      "club_country": "IQ",
      "club_id": 171,
      "club_name": "Erbil",
      "forename": "Burhan Jumaah",
      "id": 1868,
      "league_id": 12,
      "league_name": "Iraqi Premier League",
      "name": "Burhan Jumaah",
      "nationality": "iq",
      "nationality_full": "Iraq",
      "position": "Defender",
      "surname": "Razzaq",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    }
  },
  "Goalkeeper": {
    "player-3076": {
      "birthdate": "15 December 1985",
      "club_country": "QA",
      "club_id": 1,
      "club_name": "Lekhwiya",
      "comments": [
        {
          "comment": "xxx",
          "name": "guy tester",
          "photoURL": "http://pbs.twimg.com/profile_images/855450315704979460/RGiq07D7_normal.jpg",
          "time": 1496529030321,
          "user": "y884F42mLCVdld5V5cMeRpl11gJ2"
        }
      ],
      "forename": "Qasem Abdulhamed",
      "id": 3076,
      "league_id": 1,
      "league_name": "Qatar Stars League",
      "name": "Qasem Burhan",
      "nationality": "qa",
      "nationality_full": "Qatar",
      "position": "Goalkeeper",
      "surname": "Burhan",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    },
    "player-3532": {
      "birthdate": "2 April 1992",
      "club_country": "SA",
      "club_id": 18,
      "club_name": "Al Ittihad",
      "forename": "Fawaz",
      "id": 3532,
      "league_id": 2,
      "league_name": "Saudi Professional League",
      "name": "Fawaz Al Qarni",
      "nationality": "sa",
      "nationality_full": "Saudi Arabia",
      "position": "Goalkeeper",
      "surname": "Al Qarni",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    }
  }
};
</code>```

How would I, using lodash, traverse through this object and add every time the property id appears inside an object key of player-xxxxxx, add that value to an array. Essentially, getting all of the player IDs in a single array?

答:
Iterate through the object keys check to see if the string starts with "player-" and then push into an empty array the last four characters.

var object = {
  "Defender": {
    "player-1868": {
      "birthdate": "1 July 1996",
      "club_country": "IQ",
      "club_id": 171,
      "club_name": "Erbil",
      "forename": "Burhan Jumaah",
      "id": 1868,
      "league_id": 12,
      "league_name": "Iraqi Premier League",
      "name": "Burhan Jumaah",
      "nationality": "iq",
      "nationality_full": "Iraq",
      "position": "Defender",
      "surname": "Razzaq",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    }
  },
  "Goalkeeper": {
    "player-3076": {
      "birthdate": "15 December 1985",
      "club_country": "QA",
      "club_id": 1,
      "club_name": "Lekhwiya",
      "comments": [{
        "comment": "xxx",
        "name": "guy tester",
        "photoURL": "http://pbs.twimg.com/profile_images/855450315704979460/RGiq07D7_normal.jpg",
        "time": 1496529030321,
        "user": "y884F42mLCVdld5V5cMeRpl11gJ2"
      }],
      "forename": "Qasem Abdulhamed",
      "id": 3076,
      "league_id": 1,
      "league_name": "Qatar Stars League",
      "name": "Qasem Burhan",
      "nationality": "qa",
      "nationality_full": "Qatar",
      "position": "Goalkeeper",
      "surname": "Burhan",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    },
    "player-3532": {
      "birthdate": "2 April 1992",
      "club_country": "SA",
      "club_id": 18,
      "club_name": "Al Ittihad",
      "forename": "Fawaz",
      "id": 3532,
      "league_id": 2,
      "league_name": "Saudi Professional League",
      "name": "Fawaz Al Qarni",
      "nationality": "sa",
      "nationality_full": "Saudi Arabia",
      "position": "Goalkeeper",
      "surname": "Al Qarni",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    }
  }
};

function getPlayers(object) {
  let items = [];
  for (let i in object) {
    let key = Object.keys(object[i]);
    key.forEach(i => i.startsWith('player') ? items.push(i.substring(i.length -4)) : '');
  }
  return items;
}
console.log(getPlayers(object));```

Body:
Let's say I have an object like this:

var object =  {
  "Defender": {
    "player-1868": {
      "birthdate": "1 July 1996",
      "club_country": "IQ",
      "club_id": 171,
      "club_name": "Erbil",
      "forename": "Burhan Jumaah",
      "id": 1868,
      "league_id": 12,
      "league_name": "Iraqi Premier League",
      "name": "Burhan Jumaah",
      "nationality": "iq",
      "nationality_full": "Iraq",
      "position": "Defender",
      "surname": "Razzaq",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    }
  },
  "Goalkeeper": {
    "player-3076": {
      "birthdate": "15 December 1985",
      "club_country": "QA",
      "club_id": 1,
      "club_name": "Lekhwiya",
      "comments": [
        {
          "comment": "xxx",
          "name": "guy tester",
          "photoURL": "http://pbs.twimg.com/profile_images/855450315704979460/RGiq07D7_normal.jpg",
          "time": 1496529030321,
          "user": "y884F42mLCVdld5V5cMeRpl11gJ2"
        }
      ],
      "forename": "Qasem Abdulhamed",
      "id": 3076,
      "league_id": 1,
      "league_name": "Qatar Stars League",
      "name": "Qasem Burhan",
      "nationality": "qa",
      "nationality_full": "Qatar",
      "position": "Goalkeeper",
      "surname": "Burhan",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    },
    "player-3532": {
      "birthdate": "2 April 1992",
      "club_country": "SA",
      "club_id": 18,
      "club_name": "Al Ittihad",
      "forename": "Fawaz",
      "id": 3532,
      "league_id": 2,
      "league_name": "Saudi Professional League",
      "name": "Fawaz Al Qarni",
      "nationality": "sa",
      "nationality_full": "Saudi Arabia",
      "position": "Goalkeeper",
      "surname": "Al Qarni",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    }
  }
};

How would I, using lodash, traverse through this object and add every time the property id appears inside an object key of player-xxxxxx, add that value to an array. Essentially, getting all of the player IDs in a single array?


问:
String literal Vs Unicode literal Vs unicode type object - Memory representation
Python 2.x doc says,

Unicode string is a sequence of code points

Unicode strings are expressed as instances of the unicode type

```<code>>>> ThisisNotUnicodeString = 'a정정' # What is the memory representation?
>>> ThisisNotUnicodeString
'a\xec\xa0\x95\xec\xa0\x95\xf0\x9f\x92\x9b'
>>> type(ThisisNotUnicodeString)
<type 'str'>
>>> a = u'a정정' # Which encoding technique used to represent in memory? utf-8?
>>> a
u'a\uc815\uc815\U0001f49b'
>>> type(a)
<type 'unicode'>
>>> b = unicode('a정정', 'utf-8')
>>> b
u'a\uc815\uc815\U0001f49b'
>>> c = unicode('a정정', 'utf-16')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/encodings/utf_16.py", line 16, in decode
    return codecs.utf_16_decode(input, errors, True)
UnicodeDecodeError: 'utf16' codec can't decode byte 0x9b in position 10: truncated data
>>>
</code>```

Question:

1) ThisisNotUnicodeString is string literal. Despite ThisisNotUnicodeString is not a unicode literal, Which encoding technique used to represent ThisisNotUnicodeString in memory? Because there should be some encoding technique to represent 정 or  character in memory.

2) Which encoding technique used to represent unicode literal a in memory? utf-8?  If yes, How to know the number of bytes occupied?

3) Why c is not represented in memory, using utf-16 technique?

答:
Which encoding technique used to represent in memory? utf-8?

You can try the following:

```<code>ThisisNotUnicodeString.decode('utf-8')
</code>```

If you get a result, it's UTF-8, otherwise it's not.

If you want to get the UTF-16 representation of the string, you should first decode it, and then encode with UTF-16 scheme:

```<code>ThisisNotUnicodeString.decode('utf-8').encode('utf-16')
</code>```

So basically, you can decode and encode the given string from/to UTF-8/UTF-16, because all characters can be represented in both schemes.

```<code>ThisisNotUnicodeString.decode('utf-8').encode('utf-16').decode('utf-16').encode('utf-8')
</code>```

Body:
Python 2.x doc says,

Unicode string is a sequence of code points

Unicode strings are expressed as instances of the unicode type

>>> ThisisNotUnicodeString = 'a정정' # What is the memory representation?
>>> ThisisNotUnicodeString
'a\xec\xa0\x95\xec\xa0\x95\xf0\x9f\x92\x9b'
>>> type(ThisisNotUnicodeString)
<type 'str'>
>>> a = u'a정정' # Which encoding technique used to represent in memory? utf-8?
>>> a
u'a\uc815\uc815\U0001f49b'
>>> type(a)
<type 'unicode'>
>>> b = unicode('a정정', 'utf-8')
>>> b
u'a\uc815\uc815\U0001f49b'
>>> c = unicode('a정정', 'utf-16')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/encodings/utf_16.py", line 16, in decode
    return codecs.utf_16_decode(input, errors, True)
UnicodeDecodeError: 'utf16' codec can't decode byte 0x9b in position 10: truncated data
>>>

Question:

1) ThisisNotUnicodeString is string literal. Despite ThisisNotUnicodeString is not a unicode literal, Which encoding technique used to represent ThisisNotUnicodeString in memory? Because there should be some encoding technique to represent 정 or  character in memory.

2) Which encoding technique used to represent unicode literal a in memory? utf-8?  If yes, How to know the number of bytes occupied?

3) Why c is not represented in memory, using utf-16 technique?

Body:
Which encoding technique used to represent in memory? utf-8?

You can try the following:

ThisisNotUnicodeString.decode('utf-8')

If you get a result, it's UTF-8, otherwise it's not.

If you want to get the UTF-16 representation of the string, you should first decode it, and then encode with UTF-16 scheme:

ThisisNotUnicodeString.decode('utf-8').encode('utf-16')

So basically, you can decode and encode the given string from/to UTF-8/UTF-16, because all characters can be represented in both schemes.

ThisisNotUnicodeString.decode('utf-8').encode('utf-16').decode('utf-16').encode('utf-8')


问:
How to compute user defined variables with a mysql database table?
I am building a website that will need to process some data that is in a database table with a form that the user fills out. There is kind of a lot of data but a simple example would be something like this:

In this I am multiplying the answer to each form question with its corresponding column.

Is this something that can be done or do I need to set it up in a different way?

答:
This question is too broad to answer, however, focusing on only your first table, a normalised version of same might look like this: </p>

```<code> hour fruit  quantity
    1 apple     3
    1 orange    2
    1 melon     3
    2 apple     2
    2 orange    2
    2 melon     2
    3 apple     1
    3 orange    3
    3 melon     2
</code>```

Body:
This question is too broad to answer, however, focusing on only your first table, a normalised version of same might look like this:

 hour fruit  quantity
    1 apple     3
    1 orange    2
    1 melon     3
    2 apple     2
    2 orange    2
    2 melon     2
    3 apple     1
    3 orange    3
    3 melon     2


问:
Change drawer gap between header group and first item menu
I need change the space between header group and first item menu, here's an example:

I have seen a lot of examples and posts but only be can change the space for all items, and I just need to change only for header group.

Any idea?

答:
There are 4 types of items in the RecyclerView that NavigationView creates:

```
<code>
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case VIEW_TYPE_NORMAL:
                return new NormalViewHolder(mLayoutInflater, parent, mOnClickListener);
            case VIEW_TYPE_SUBHEADER:
                return new SubheaderViewHolder(mLayoutInflater, parent);
            case VIEW_TYPE_SEPARATOR:
                return new SeparatorViewHolder(mLayoutInflater, parent);
            case VIEW_TYPE_HEADER:
                return new HeaderViewHolder(mHeaderLayout);
        }
        return null;
    }
</code>
```

The one you are interested in is SubheaderViewHolder. R.layout.design_navigation_item_subheader is the layout, that would be inflated for that ViewHolder.

```<code><TextView xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="?attr/listPreferredItemHeightSmall"
          android:gravity="center_vertical|start"
          android:maxLines="1"
          android:paddingLeft="?attr/listPreferredItemPaddingLeft"
          android:paddingRight="?attr/listPreferredItemPaddingRight"
          android:textAppearance="@style/TextAppearance.AppCompat.Body2"
          android:textColor="?android:textColorSecondary"/>
</code>```

As you can see, the height is taken from the theme's listPreferredItemHeightSmall attribute. But you cannot achieve your requirement just by changing the value of listPreferredItemHeightSmall, because NormalViewHolder's item is also dependent on that value, thus changing it would affect all other items too.

The sneaky and non-reliable way of achieving that would be to acquire this RecyclerView on runtime with getIdentifier() API. The id of the custom RecyclerView is design_navigation_view. Once acquired, you can manually get the actual View from RecyclerView (knowing which child of RecyclerView is the one you need). Then you can manually change the height of that View. But that is not reliable, because:

It won't be easy to handle that for many such items, because you cannot know how many of them are actually displayed (well, you can, but is it worth it?)

You have to listen for scroll events and detect when any new SubheaderViewHolder is getting displayed - then apply your custom height.

I cannot find enough seams to affect the height of that item. Your best option would be to provide your custom layout as the content of NavigationView.

Body:
There are 4 types of items in the RecyclerView that NavigationView creates:

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case VIEW_TYPE_NORMAL:
                return new NormalViewHolder(mLayoutInflater, parent, mOnClickListener);
            case VIEW_TYPE_SUBHEADER:
                return new SubheaderViewHolder(mLayoutInflater, parent);
            case VIEW_TYPE_SEPARATOR:
                return new SeparatorViewHolder(mLayoutInflater, parent);
            case VIEW_TYPE_HEADER:
                return new HeaderViewHolder(mHeaderLayout);
        }
        return null;
    }

The one you are interested in is SubheaderViewHolder. R.layout.design_navigation_item_subheader is the layout, that would be inflated for that ViewHolder.

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="?attr/listPreferredItemHeightSmall"
          android:gravity="center_vertical|start"
          android:maxLines="1"
          android:paddingLeft="?attr/listPreferredItemPaddingLeft"
          android:paddingRight="?attr/listPreferredItemPaddingRight"
          android:textAppearance="@style/TextAppearance.AppCompat.Body2"
          android:textColor="?android:textColorSecondary"/>

As you can see, the height is taken from the theme's listPreferredItemHeightSmall attribute. But you cannot achieve your requirement just by changing the value of listPreferredItemHeightSmall, because NormalViewHolder's item is also dependent on that value, thus changing it would affect all other items too.

The sneaky and non-reliable way of achieving that would be to acquire this RecyclerView on runtime with getIdentifier() API. The id of the custom RecyclerView is design_navigation_view. Once acquired, you can manually get the actual View from RecyclerView (knowing which child of RecyclerView is the one you need). Then you can manually change the height of that View. But that is not reliable, because:

It won't be easy to handle that for many such items, because you cannot know how many of them are actually displayed (well, you can, but is it worth it?)

You have to listen for scroll events and detect when any new SubheaderViewHolder is getting displayed - then apply your custom height.

I cannot find enough seams to affect the height of that item. Your best option would be to provide your custom layout as the content of NavigationView.


问:
Compile error with writing return function
I want to create a function where I use one parameter so the function returns another value. In this case I want to insert "links" in a function and then the function should give me back "Left" (Im need a of 'translations' so therefore I use case of if statements.

I have the following function

```<code>Public Function newParameter(aParameter) As Integer
 Select Case aParameter
  Case Is = "Links"
   aParameter = "ppAlignLeft"
 End Select
End Function

Sub finalFunction()
 Dim newParameter As String
 newParameter = newParameter(Links)
 MsgBox (newParameter)
End Sub
</code>```

This however gives me a compile error that a matrix is required. Any thoughts on how I can get this working?

答:
You're passing the argument ByRef and change it's value. You dont need a function for this. Functions retun values.

Since you are using a Function though, why dont you have the Function return the value you want?

```<code>Public Function newParameter(ByVal aParameter As String) As String
 Select Case aParameter
  Case "Links":
   newParameter = "ppAlignLeft"
 Case "A":
   newParameter = "You passed A"
 Case Else:
   newParameter = "No match"
 End Select
End Function

Sub finalFunction()
 Dim newParameter1 As String
 newParameter1 = newParameter("Links") 'This reads 'ppAlignLeft'
 MsgBox newParameter1
End Sub
</code>```

Body:
I want to create a function where I use one parameter so the function returns another value. In this case I want to insert "links" in a function and then the function should give me back "Left" (Im need a of 'translations' so therefore I use case of if statements.

I have the following function

Public Function newParameter(aParameter) As Integer
 Select Case aParameter
  Case Is = "Links"
   aParameter = "ppAlignLeft"
 End Select
End Function

Sub finalFunction()
 Dim newParameter As String
 newParameter = newParameter(Links)
 MsgBox (newParameter)
End Sub

This however gives me a compile error that a matrix is required. Any thoughts on how I can get this working?

Body:
You're passing the argument ByRef and change it's value. You dont need a function for this. Functions retun values.

Since you are using a Function though, why dont you have the Function return the value you want?

Public Function newParameter(ByVal aParameter As String) As String
 Select Case aParameter
  Case "Links":
   newParameter = "ppAlignLeft"
 Case "A":
   newParameter = "You passed A"
 Case Else:
   newParameter = "No match"
 End Select
End Function

Sub finalFunction()
 Dim newParameter1 As String
 newParameter1 = newParameter("Links") 'This reads 'ppAlignLeft'
 MsgBox newParameter1
End Sub


问:
replace text in code module
Im trying to use the replaceline function to update code in Access VBA module. it keeps coming up with a compile error. Ive checked that the VBA Extension are selected and compared it to other examples that I have looked up.

this is the first time that Ive used this type of function, so I haven't fully got my head around them.

code below

Sub ReplaceCodeModuleText(strModule As String, strFindWhat As String, strReplaceWith As String)
'FUNCTION:
'           Search the code module for specific text
'           Replace with new text

Dim VBProj As VBProject
Dim VBComp As VBComponent
Dim CodeMod As CodeModule

Dim SL As Long ' start line
Dim EL As Long ' end line
Dim SC As Long ' start column
Dim EC As Long ' end column
Dim strCodeLine As String
Dim vDummy As Variant

Dim Found As Boolean

    Set VBProj = Application.VBE.ActiveVBProject
    Set VBComp = VBProj.VBComponents(strModule)
    Set CodeMod = VBComp.CodeModule '    '.CodeModule

    With CodeMod
        SL = 1:        EL = .CountOfLines
        SC = 1:        EC = 255

        Found = .Find(Target:=strFindWhat, StartLine:=SL, StartColumn:=SC, _
            EndLine:=EL, EndColumn:=EC, _
            wholeword:=True, MatchCase:=False, patternsearch:=False)

        If Found Then
            strCodeLine = CodeMod.Lines(SL, 1)
            strCodeLine = Replace(strCodeLine, strFindWhat, strReplaceWith, Compare:=vbTextCompare) 'not case sensitive = vbTextCompare
            .ReplaceLine(SL, strCodeLine)

            Debug.Print "Successfully Replaced: " & strFindWhat & " in VBA Module: " & strModule & " with : " & strReplaceWith
        Else
            Debug.Print "Did not find: " & strFindWhat;

        End If
    End With
End Sub
```

答:
```<code>        .ReplaceLine(SL, strCodeLine)
</code>```

must be either

```<code>        Call .ReplaceLine(SL, strCodeLine)
</code>```

or

```<code>        .ReplaceLine SL, strCodeLine
</code>```

Title: replace text in code module

Body:
        .ReplaceLine(SL, strCodeLine)

must be either

        Call .ReplaceLine(SL, strCodeLine)

or

        .ReplaceLine SL, strCodeLine


问:
How to store volley response into HashMap?

i have created HashMap and JsonArrayRequest object as follows. Response is successfully retrieved but HashMap object url_maps size is zero.I want to use for loop in url_maps.

```<code>    HashMap<String,String> url_maps = new HashMap<String, String>();

    // Creating volley request obj for Banner
    JsonArrayRequest bannerReq = new JsonArrayRequest(bannerUrl,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    Log.d(msg, response.toString());
                    // Parsing json
                    for (int i = 0; i < response.length(); i++) {
                        try {
                            JSONObject obj = response.getJSONObject(i);
                            url_maps.put("static key", "static value );
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    // notifying list adapter about data changes
                    // so that it renders the list view with updated data
                    //adapter.notifyDataSetChanged();
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(msg, "Error: " + error.getMessage());
        }
    });
    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(bannerReq);
</code>```

答:
maybe you can change:

```<code>url_maps.put("static key", "static value );
</code>```

to:

```<code>url_maps.put(obj.getString("static key"),obj.getString("static value"));
</code>```

Body:
i have created HashMap and JsonArrayRequest object as follows. Response is successfully retrieved but HashMap object url_maps size is zero.I want to use for loop in url_maps.

    HashMap<String,String> url_maps = new HashMap<String, String>();

    // Creating volley request obj for Banner
    JsonArrayRequest bannerReq = new JsonArrayRequest(bannerUrl,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    Log.d(msg, response.toString());
                    // Parsing json
                    for (int i = 0; i < response.length(); i++) {
                        try {
                            JSONObject obj = response.getJSONObject(i);
                            url_maps.put("static key", "static value );
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    // notifying list adapter about data changes
                    // so that it renders the list view with updated data
                    //adapter.notifyDataSetChanged();
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(msg, "Error: " + error.getMessage());
        }
    });
    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(bannerReq);

Body:
maybe you can change:

url_maps.put("static key", "static value );

to:

url_maps.put(obj.getString("static key"),obj.getString("static value"));


问:
How to test an angular service function nested promises?
Heres what my service kind of looks like

```<code>TestService.initializeDefaults = function() {
        var qPromise = $q.defer();
        $q.all({localResource : localResource.fetch(),
                item : itemResource.fetch()}).then(function(directories){

            //stuff happens with directories
            $q.all({
                thing1 : anotherThingFetch.fetch(),
                thing2: someThingFetch.fetch(),
                thing3: thingFetch.fetch()
            }).then(function(funData) {
                //stuff happens with the data

                preventiveServicesService.fetch().then(function() {

                    //stuff happens
                });

            });
        }.bind(this));
        return qPromise;
    };
</code>```

And Im attempting to use karma to test that all the functions within this initializeDefaults method have run. Meaning that essentially all the fetch's happened. Heres what I have that works in the test so far:

```<code>it("should initialize defaults (Scenario 1)", function() {

            service.initializeDefaults();

            rootScope.$apply();

            expect(localResourceMock.fetch).toHaveBeenCalledWith();
            expect(itemResourceMock.fetch).toHaveBeenCalledWith();
</code>```

答:
Well there are 2 ways you can go about this.

1) Use $httpBackend: use something like $httpBackend.expectGET('url1').respond(200, {}) and so on for all the $http calss you're making. Then call $httpBackend.flush() and it should execute all nested promises as well.
Downside: This will execute all logic in the methods being invoked.

2) Use Jasmine spies: Do something like:

```<code>let deferred = $q.defer();
deferred.resolve(/*data you expect the promise to return*/);
spyOn(localResourceMock, 'fetch').and.returnValue(deferred.promise);
spyOn(itemResource, 'fetch').and.returnValue(deferred.promise);

spyOn(anotherThingFetch, 'fetch').and.returnValue(deferred.promise);
/*And so on for all methods being invoked*/

// Invoke the method
service.initializeDefaults();

// Trigger digest cycle
rootScope.$digest();

/*Expect all the spies to have been called*/
expect(anotherThingFetch.fetch).toHaveBeenCalledWith(); // will now pass
</code>```

Either of those will work. Your call.
Cheers.

Body:
Heres what my service kind of looks like

TestService.initializeDefaults = function() {
        var qPromise = $q.defer();
        $q.all({localResource : localResource.fetch(),
                item : itemResource.fetch()}).then(function(directories){

            //stuff happens with directories
            $q.all({
                thing1 : anotherThingFetch.fetch(),
                thing2: someThingFetch.fetch(),
                thing3: thingFetch.fetch()
            }).then(function(funData) {
                //stuff happens with the data

                preventiveServicesService.fetch().then(function() {

                    //stuff happens
                });

            });
        }.bind(this));
        return qPromise;
    };

And Im attempting to use karma to test that all the functions within this initializeDefaults method have run. Meaning that essentially all the fetch's happened. Heres what I have that works in the test so far:

it("should initialize defaults (Scenario 1)", function() {

            service.initializeDefaults();

            rootScope.$apply();

            expect(localResourceMock.fetch).toHaveBeenCalledWith();
            expect(itemResourceMock.fetch).toHaveBeenCalledWith();

Body:
Well there are 2 ways you can go about this.

1) Use $httpBackend: use something like $httpBackend.expectGET('url1').respond(200, {}) and so on for all the $http calss you're making. Then call $httpBackend.flush() and it should execute all nested promises as well.
Downside: This will execute all logic in the methods being invoked.

2) Use Jasmine spies: Do something like:

let deferred = $q.defer();
deferred.resolve(/*data you expect the promise to return*/);
spyOn(localResourceMock, 'fetch').and.returnValue(deferred.promise);
spyOn(itemResource, 'fetch').and.returnValue(deferred.promise);

spyOn(anotherThingFetch, 'fetch').and.returnValue(deferred.promise);
/*And so on for all methods being invoked*/

// Invoke the method
service.initializeDefaults();

// Trigger digest cycle
rootScope.$digest();

/*Expect all the spies to have been called*/
expect(anotherThingFetch.fetch).toHaveBeenCalledWith(); // will now pass

Either of those will work. Your call.
Cheers.


问:
Is it possible to run ios apps developed using react-native in linux to real iphone
I am having a react-native app. I would like to generate an iOS app from my linux/windows machine. Is it possbile? Some friends has suggested me about BuddyBuild. is there any alternative solutions for me?? I have the following physical devices

Laptop running windows & linux (running node.js,python,java,npm,and lot more)

iPhone 5S

Internet Connection

答:
Try Expo. It's built on top of React Native and it makes developing a lot easier because you can see what you code instantly on a real phone. You can send links to people or even use a QR code to share your projects as you work on them.

Expo


问:
Delete rows containing @ symbol in mySQL
Hi I would like to know if there is any way of deleting any row containing the @ symbol in a text string.

I already tried :

```<code>DELETE FROM FilteredJobs WHERE Description LIKE '%[@]%'
</code>```

but this returns 0 rows (I know there are 4)

I need to get this done within mySQL since there will be other mySQL functions to follow this task.

答:
Try this:

```<code>DELETE FROM FilteredJobs WHERE Description LIKE '%@%'
</code>```

It appears you were trying to use a regex character class containing the at symbol.  This won't work with LIKE, but it should work with REGEXP, e.g.

```<code>DELETE FROM FilteredJobs WHERE Description REGEXP '[@]'
</code>```

Here is a demo showing that your approach would work using REGEXP:

Rextester

Body:
Hi I would like to know if there is any way of deleting any row containing the @ symbol in a text string.

I already tried :

DELETE FROM FilteredJobs WHERE Description LIKE '%[@]%'

but this returns 0 rows (I know there are 4)

I need to get this done within mySQL since there will be other mySQL functions to follow this task.

Body:
Try this:

DELETE FROM FilteredJobs WHERE Description LIKE '%@%'

It appears you were trying to use a regex character class containing the at symbol.  This won't work with LIKE, but it should work with REGEXP, e.g.

DELETE FROM FilteredJobs WHERE Description REGEXP '[@]'

Here is a demo showing that your approach would work using REGEXP:

Rextester


问:
I want the hyperlink to be in a different place
I am looking to put the hyperlink in a different place. How can I move the google.com link to another place on the page?</p>

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<title>Randy's first html web page !</title>
<style type="text/css">
body
{background-image:url('Koala.gif');}
h1
{
text-align:center;
font-size:500%;
}
h2
{
text-align:center;
font-size:250%;
}
p
{
text-align:center;
font-size:200%;
color:#00fff0;
}
div
{
background-color:#efffff;
}
a
{
text-align:center;
}
th
{
background-color:green;
}
tr
{
background-color:green;
}
table
{
width: 200px;
margin-left: auto;
margin-right: auto;
}
</style>
</head>
<h1> Hello Professor</h1>
<h2> By: Randy White</h2>
<P> It's getting better as the term goes on.</P>
<P>Week 2</P>
<P><img src="Hydrangeas.jpg" width="150" height="100" alt="Hydrangeas.jpg"></P>
<table border="1">
<tr>
<th>Month</th>
<th>Day</th>
<th>Year</th>
 </tr>
<tr>
<td>December</td>
<td>13</td>
<td>2010</td>
 </tr>
 </table>
 <a href="http://www.google.com">Visit Google!</a>
</body>
</html>
</code>```

答:
In your CSS, add this:

```<code>#google-link {
    text-align: center;
}
</code>```

This aligns text inside in the center.

In your HTML, change the Google link to this:

```<code><div id="google-link"><a href="http://www.google.com">Visit Google!</a></div>
</code>```

The div is tagged with the google-link id, which gets it the above style.  The style actually affects the contents of the div, aligning them to the center.  The div itself is the width of the page.

ContentLicense: CC BY-SA 2.5

Body:
I am looking to put the hyperlink in a different place. How can I move the google.com link to another place on the page?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">

<title>Randy's first html web page !</title>

 Hello Professor

 By: Randy White

 It's getting better as the term goes on.

Week 2

Month
Day
Year

December
13
2010

 Visit Google!

Body:
In your CSS, add this:

#google-link {
    text-align: center;
}

This aligns text inside in the center.

In your HTML, change the Google link to this:

<div id="google-link"><a href="http://www.google.com">Visit Google!</a></div>

The div is tagged with the google-link id, which gets it the above style.  The style actually affects the contents of the div, aligning them to the center.  The div itself is the width of the page.


问:
How can I extract a short part of characters from the string with Regular Expression in Python?
Here is my code:

```<code>s = '''I wish I may, I wish I might
Have a dish of fish tonight.'''

import re
m = re.search('w.*m', s)
print(m.group())
</code>```

and I got the result:

```<code>wish I may, I wish I m
</code>```

If I want to get the result only the first half wish I m, how can I revise my code?

Thanks a lot!

答:
In regular expressions, . means a single character and .* means any number of characters (0 or more).

When you used w.*m, by default, python will look for the longest sub-string that starts with w and ends with m.
This is called GREEDY MATCH.

To find a smaller sub-string in a string that starts with w and ends with m, you have to search NON GREEDILY.

For this, instead of using w.*m, use w.*?m .
Because of the ? operator, python matches the first sub-string that is given by the regular expression.

Technically, ? Causes the resulting RE to match 0 or 1 repetitions of the preceding RE. example : ab? will match either a or ab.
So, Here, w.*?m will match minimum number of characters after w(included) that ends with m(included).

```<code>>>> s = '''I wish I may, I wish I might
... Have a dish of fish tonight.'''
>>>
>>> import re
>>> m = re.search('w.*m', s)    #GREEDY SEARCH
>>> print(m.group())
wish I may, I wish I m
>>> m = re.search('w.*?m', s)   #NON GREEDY SEARCH
>>> print(m.group())
wish I m
</code>```

Read more about REGULAR EXPRESSIONS here

Body:
Here is my code:

s = '''I wish I may, I wish I might
Have a dish of fish tonight.'''

import re
m = re.search('w.*m', s)
print(m.group())

and I got the result:

wish I may, I wish I m

If I want to get the result only the first half wish I m, how can I revise my code?

Thanks a lot!

Body:
In regular expressions, . means a single character and .* means any number of characters (0 or more).

When you used w.*m, by default, python will look for the longest sub-string that starts with w and ends with m.
This is called GREEDY MATCH.

To find a smaller sub-string in a string that starts with w and ends with m, you have to search NON GREEDILY.

For this, instead of using w.*m, use w.*?m .
Because of the ? operator, python matches the first sub-string that is given by the regular expression.

Technically, ? Causes the resulting RE to match 0 or 1 repetitions of the preceding RE. example : ab? will match either a or ab.
So, Here, w.*?m will match minimum number of characters after w(included) that ends with m(included).

>>> s = '''I wish I may, I wish I might
... Have a dish of fish tonight.'''
>>>
>>> import re
>>> m = re.search('w.*m', s)    #GREEDY SEARCH
>>> print(m.group())
wish I may, I wish I m
>>> m = re.search('w.*?m', s)   #NON GREEDY SEARCH
>>> print(m.group())
wish I m

Read more about REGULAR EXPRESSIONS here


问:
Get network statistics of Wi-Fi interface used by specific ssid in windows
What is the best way to  get previous Network Statistics in Windows used by Wi-Fi interface when it is connected to specific SSID? Using any programming language.

答: Windows does not store data usage details per SSID.</p>


问:
How to target div#specificDiv in jquery?
I want to ask that how can i target a specific division in Jquery code. In the code below we are targeting "everything", Even if we change this to "div", it will target all the divisions in the file.But my question is that how can we target a specific division, As i want to target at the div with class "particles particles2"

$(document).ready(function() {

  $(document).on('click', function() {
    $('body').jGravity({
      target: 'eveything',
      ignoreClass: 'ignoreMe',
      weight: 25,
      depth: 5,
      drag: true
    });
    // Misc code for demo purposes
    $(this).removeClass('#fountains');

  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="template-page"> </div>
<div class="particles particles2 ignoreMe jGravity" id="fountains"></div></code>```

答:
For targeting specific Div with class define selectors as div.class, like this:

$(document).ready(function() {

    $(document).on('click', function() {
        $('body').jGravity({
            target: 'div.particles',
            ignoreClass: 'ignoreMe',
            weight: 25,
            depth: 5,
            drag: true
        });
        // Misc code for demo purposes
        $(this).removeClass('#fountains');

    });
});```


问:
How to vertical align elements cross-browser?
I am doing vertical alignment using vertical-align: middle property its working in Chrome but not in IE.

答:
If you want to place a one line text, for example a header title in your box, than use line-height

For example with a 200px width and 40px height box:

```<code>.the_box{
width: 200px;
height: 40px;
line-height: 40px;
}
</code>```

It's easy, elegant, and cross-browser. If you have longer text than 200px, this method will not work.

Body:
If you want to place a one line text, for example a header title in your box, than use line-height

For example with a 200px width and 40px height box:

.the_box{
width: 200px;
height: 40px;
line-height: 40px;
}

It's easy, elegant, and cross-browser. If you have longer text than 200px, this method will not work.


答:
Well, this is something that I could think of, might not be the PERFECT answer but can definitely be tried:

```<code>UPDATE FilteredJobs SET Description = REPLACE(Description, '@', 'TO_BE_DELETED');
</code>```

And then you can fire a normal DELETE query:

```<code>DELETE FROM FilteredJobs WHERE Description LIKE '%TO_BE_DELETED%';
</code>```

Title: Delete rows containing @ symbol in mySQL

Body:
Well, this is something that I could think of, might not be the PERFECT answer but can definitely be tried:

UPDATE FilteredJobs SET Description = REPLACE(Description, '@', 'TO_BE_DELETED');

And then you can fire a normal DELETE query:

DELETE FROM FilteredJobs WHERE Description LIKE '%TO_BE_DELETED%';


问:
Features and Events in FileChooserWidget GTK#
I'm using GTK#(Newbie) on Xamarin Studio Community version 6.3, on Windows.
Recently, I was trying to build a Total Commander application. During the construction, I used the File Chooser Widget and found some issue that I can't solve:

1- When I click on a folder in Places box, a few buttons will appear: \ <icon button with a pen and a paper> enter image description here. When I click on the Icon Button, a Location Entry will show up. However, I don't know how to use that entry like opening a folder, folder path will show up on Location entry or enter folder path, folder will open on the widget. My temporary solution is create a entry:

```<code>FileChooserWidget fcw1 = new global::Gtk.FileChooserWidget(((global::Gtk.FileChooserAction)(0)));
Entry e1 = new Entry();

e1.Text = fcw1.CurrentFolder;
</code>```

I hope to find the way to capture that Location Entry and use it.

2- On the workplace I have a problem in open a file by using Double-Click Event. My code:

```<code>[GLib.ConnectBefore]
protected void OnFcw1ButtonPressEvent(object o, ButtonPressEventArgs args)
        {
            if (((Gdk.EventButton)args.Event).Type == Gdk.EventType.TwoButtonPress)
                 {
                     entry1.Text = fcw1.Filename;
                     if (File.Exists(fcw1.Filename))
                         Process.Start(fcw1.Filename);
                 }
        }
</code>```

3- The same problem of find The use of the Search and Recently Used that Could not start the search process
 The program was not able to create a connection to the indexer daemon.  Please make sure it is running.

Please help me find the solution and teach me how to find the name of all these widgets. Thank you very much!

答:
To answer #1 there's a Action property on the FileChooser widget which will allow you to set it up for what you want it to do (Open, Create, Select Folder etc). The Location field contains the filename (that you select if browsing, or can type in if creating a new file).

On #2, default behaviour for double-clicks on FCW is to drill-through on folders and select for files. Because you've got a Glib.ConnectBefore attribute your event handler will run before the default handler. Maybe whatever problem you have in #2 is related to the handlers?

On #3 sounds like an issue on your dev machine. The FCW will allow you to search the file system so long as it can connect to the daemon so it looks like that's not running. I've not had an issue with that in Windows, Mac OSX, Ubuntu or RHEL on other machines.

Body:
I'm using GTK#(Newbie) on Xamarin Studio Community version 6.3, on Windows.
Recently, I was trying to build a Total Commander application. During the construction, I used the File Chooser Widget and found some issue that I can't solve:

1- When I click on a folder in Places box, a few buttons will appear: \ <icon button with a pen and a paper> enter image description here. When I click on the Icon Button, a Location Entry will show up. However, I don't know how to use that entry like opening a folder, folder path will show up on Location entry or enter folder path, folder will open on the widget. My temporary solution is create a entry:

FileChooserWidget fcw1 = new global::Gtk.FileChooserWidget(((global::Gtk.FileChooserAction)(0)));
Entry e1 = new Entry();

e1.Text = fcw1.CurrentFolder;

I hope to find the way to capture that Location Entry and use it.

2- On the workplace I have a problem in open a file by using Double-Click Event. My code:

[GLib.ConnectBefore]
protected void OnFcw1ButtonPressEvent(object o, ButtonPressEventArgs args)
        {
            if (((Gdk.EventButton)args.Event).Type == Gdk.EventType.TwoButtonPress)
                 {
                     entry1.Text = fcw1.Filename;
                     if (File.Exists(fcw1.Filename))
                         Process.Start(fcw1.Filename);
                 }
        }

3- The same problem of find The use of the Search and Recently Used that Could not start the search process
 The program was not able to create a connection to the indexer daemon.  Please make sure it is running.

Please help me find the solution and teach me how to find the name of all these widgets. Thank you very much!


问:
Display name over clicked/hovered node? (D3.js version 4)
Currently I have names of my nodes display. I think I would like to only  have the name of a node display if the user clicks on the node or hovers over it (will decide after testing what I like).

To display text I have this currently:

```<code>var nodes_text = svg.selectAll(".nodetext")
        .data(nodes)
        .enter()
        .append("text")
        .attr("class", "nodetext slds-text-heading--label")
        .attr("text-anchor", "middle")
        .attr("dx", -20)
        .attr("dy", 20)
        .text(function(d) {
            return  d.name;
        });
</code>```

My initial thought was to delete the last statement in the above code and move it to a "onclick" event...

```<code>svg.select("circle").on("click", function(d) {
svg.select(".nodetext").text(function(d) {
            return  d.name;
        });

});
</code>```

However this only works if I click my central node for some reason. Was wondering if there is a more obvious way. My node data is stored in an array called "nodes."

EDIT: Here is JFiddle of some test data that shows basic problem. Clicking purple node works but others do not
https://jsfiddle.net/mg8b46aj/1/

答:
You have several issues in code

You are binding same data for node-circles and node-text elements, so it makes sense if you group them inside one g element

You are trying to handle click event on only one element

svg.select("circle").on("click",handler)

this selects  and handles events only last one element , you have to use selectAll - svg.selectAll("circle").on("click",handler)

Same thing inside handler function

svg.select(".nodetext").text(function(d) { return  d.name; });

you are also selecting last element here

Instead of setting text attribute on click, it's better if you set them before and just display & hide it on hover & click

As Gerardo mentioned, you have to filter nodes based on circle click,
but what if two nodes have same name?  I have also generated id for nodes and have filtered them using that id

See the updated fiddle

Body:
Currently I have names of my nodes display. I think I would like to only  have the name of a node display if the user clicks on the node or hovers over it (will decide after testing what I like).

To display text I have this currently:

var nodes_text = svg.selectAll(".nodetext")
        .data(nodes)
        .enter()
        .append("text")
        .attr("class", "nodetext slds-text-heading--label")
        .attr("text-anchor", "middle")
        .attr("dx", -20)
        .attr("dy", 20)
        .text(function(d) {
            return  d.name;
        });

My initial thought was to delete the last statement in the above code and move it to a "onclick" event...

svg.select("circle").on("click", function(d) {
svg.select(".nodetext").text(function(d) {
            return  d.name;
        });

});

However this only works if I click my central node for some reason. Was wondering if there is a more obvious way. My node data is stored in an array called "nodes."

EDIT: Here is JFiddle of some test data that shows basic problem. Clicking purple node works but others do not
https://jsfiddle.net/mg8b46aj/1/


问:
Shortest Reach Graph on HackerRank
I have submitted a solution for this (https://www.hackerrank.com/challenges/ctci-bfs-shortest-reach) problem on HackerRank. It fails for certain test cases. I have not been able to figure out what is incorrect in my solution.

Problem Statement

Consider an undirected graph consisting of  n nodes where each node is labeled from 1 to n and the edge between any two nodes is always of length 6. We define node s  to be the starting position for a BFS.

Given q queries in the form of a graph and some starting node, s , perform each query by calculating the shortest distance from starting node  s to all the other nodes in the graph. Then print a single line of  space-separated integers listing node s 's shortest distance to each of the  other nodes (ordered sequentially by node number); if s is disconnected from a node, print  as the distance to that node.

Input Format

The first line contains an integer, q , denoting the number of queries. The subsequent lines describe each query in the following format:

The first line contains two space-separated integers describing the respective values of n (the number of nodes) and m (the number of edges) in the graph.
Each line i of the m subsequent lines contains two space-separated integers, u and v, describing an edge connecting node u to node v.
The last line contains a single integer, s, denoting the index of the starting node.

Output Format

For each of the q queries, print a single line of n-1 space-separated integers denoting the shortest distances to each of the  other nodes from starting position s. These distances should be listed sequentially by node number (i.e., 1,2...n), but should not include node s. If some node is unreachable from s, print  -1 as the distance to that node.

Example

Sample Input:

```<code>    2
    4 2
    1 2
    1 3
    1
    3 1
    2 3
    2
</code>```

Sample Output:

```<code>6 6 -1
-1 6
</code>```

My solution:

```<code>import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static class Graph {
        //key = node. value = list of neighbors.
       Map<Integer, List<Integer>> nodes;

        public Graph(int size) {
            nodes = new HashMap<Integer, List<Integer>>();
            for(int i = 0; i<size; i++){
                nodes.put(i, new ArrayList<Integer>());
            }
        }

        public void addEdge(int first, int second) {
            if(first != second){
               if(!(nodes.get(first).contains(second))){
                    nodes.get(first).add(second);
                }
                if(!(nodes.get(second).contains(first))){
                    nodes.get(second).add(first);
                }
            }
        }

        public int[] shortestReach(int startId) { // 0 indexed
            int[] distances = new int[nodes.keySet().size()];
            Arrays.fill(distances, -1);
            distances[startId] = 0;
            visitNeighbors(startId, distances);
            return distances;
        }

        private void visitNeighbors(int startId, int[] distances){
            List<Integer> nodesToVisit = new ArrayList<Integer>();
            for(int i:nodes.get(startId)){
                if(distances[i] == -1){
                    distances[i] = distances[startId] + 6;
                    nodesToVisit.add(i);
                }
                //dont recurse right here, otherwise it will become depth-first and we will not get shortest path.
            }
            for(int i:nodesToVisit){
                visitNeighbors(i, distances);
            }
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int queries = scanner.nextInt();

        for (int t = 0; t < queries; t++) {

            // Create a graph of size n where each edge weight is 6:
            Graph graph = new Graph(scanner.nextInt());
            int m = scanner.nextInt();

            // read and set edges
            for (int i = 0; i < m; i++) {
                int u = scanner.nextInt() - 1;
                int v = scanner.nextInt() - 1;

                // add each edge to the graph
                graph.addEdge(u, v);
            }

            // Find shortest reach from node s
            int startId = scanner.nextInt() - 1;
            int[] distances = graph.shortestReach(startId);

            for (int i = 0; i < distances.length; i++) {
                if (i != startId) {
                    System.out.print(distances[i]);
                    System.out.print(" ");
                }
            }
            System.out.println();
        }

        scanner.close();
    }
}
</code>```

When I submit the above code, HackerRank reports that certain TestCases did not pass. I am not sure what I am doing wrong. Please help. Thank you.

答:
This is a pretty straight forward bfs problem.

Your visit method is not correct, considering it's pointing to visitNeighbors.

Make it a bfs function. currently, it's a recursive method making it a stack instead of a queue.

```<code>    private void visitNeighbors(int startId, int[] distances){
        List<Integer> nodesToVisit = new ArrayList<Integer>();

        nodesToVisit.add(startId);
        distances[startId] = 0;
        while (!nodesToVisit.isEmpty()) {
            int current = nodesToVisit.get(0);
            nodesToVisit.remove(0);
            for (int i : nodes.get(current)) {
                if (distances[i] == -1) {
                    distances[i] = distances[current] + 6;
                    nodesToVisit.add(i);
                }
                //dont recurse right here, otherwise it will become depth-first and we will not get shortest path.
            }
        }
    }
</code>```

Here is the edited accepted code.

Title: Shortest Reach Graph on HackerRank

Body:
I have submitted a solution for this (https://www.hackerrank.com/challenges/ctci-bfs-shortest-reach) problem on HackerRank. It fails for certain test cases. I have not been able to figure out what is incorrect in my solution.

Problem Statement

Consider an undirected graph consisting of  n nodes where each node is labeled from 1 to n and the edge between any two nodes is always of length 6. We define node s  to be the starting position for a BFS.

Given q queries in the form of a graph and some starting node, s , perform each query by calculating the shortest distance from starting node  s to all the other nodes in the graph. Then print a single line of  space-separated integers listing node s 's shortest distance to each of the  other nodes (ordered sequentially by node number); if s is disconnected from a node, print  as the distance to that node.

Input Format

The first line contains an integer, q , denoting the number of queries. The subsequent lines describe each query in the following format:

The first line contains two space-separated integers describing the respective values of n (the number of nodes) and m (the number of edges) in the graph.
Each line i of the m subsequent lines contains two space-separated integers, u and v, describing an edge connecting node u to node v.
The last line contains a single integer, s, denoting the index of the starting node.

Output Format

For each of the q queries, print a single line of n-1 space-separated integers denoting the shortest distances to each of the  other nodes from starting position s. These distances should be listed sequentially by node number (i.e., 1,2...n), but should not include node s. If some node is unreachable from s, print  -1 as the distance to that node.

Example

Sample Input:

    2
    4 2
    1 2
    1 3
    1
    3 1
    2 3
    2

Sample Output:

6 6 -1
-1 6

My solution:

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static class Graph {
        //key = node. value = list of neighbors.
       Map<Integer, List<Integer>> nodes;

        public Graph(int size) {
            nodes = new HashMap<Integer, List<Integer>>();
            for(int i = 0; i<size; i++){
                nodes.put(i, new ArrayList<Integer>());
            }
        }

        public void addEdge(int first, int second) {
            if(first != second){
               if(!(nodes.get(first).contains(second))){
                    nodes.get(first).add(second);
                }
                if(!(nodes.get(second).contains(first))){
                    nodes.get(second).add(first);
                }
            }
        }

        public int[] shortestReach(int startId) { // 0 indexed
            int[] distances = new int[nodes.keySet().size()];
            Arrays.fill(distances, -1);
            distances[startId] = 0;
            visitNeighbors(startId, distances);
            return distances;
        }

        private void visitNeighbors(int startId, int[] distances){
            List<Integer> nodesToVisit = new ArrayList<Integer>();
            for(int i:nodes.get(startId)){
                if(distances[i] == -1){
                    distances[i] = distances[startId] + 6;
                    nodesToVisit.add(i);
                }
                //dont recurse right here, otherwise it will become depth-first and we will not get shortest path.
            }
            for(int i:nodesToVisit){
                visitNeighbors(i, distances);
            }
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int queries = scanner.nextInt();

        for (int t = 0; t < queries; t++) {

            // Create a graph of size n where each edge weight is 6:
            Graph graph = new Graph(scanner.nextInt());
            int m = scanner.nextInt();

            // read and set edges
            for (int i = 0; i < m; i++) {
                int u = scanner.nextInt() - 1;
                int v = scanner.nextInt() - 1;

                // add each edge to the graph
                graph.addEdge(u, v);
            }

            // Find shortest reach from node s
            int startId = scanner.nextInt() - 1;
            int[] distances = graph.shortestReach(startId);

            for (int i = 0; i < distances.length; i++) {
                if (i != startId) {
                    System.out.print(distances[i]);
                    System.out.print(" ");
                }
            }
            System.out.println();
        }

        scanner.close();
    }
}

When I submit the above code, HackerRank reports that certain TestCases did not pass. I am not sure what I am doing wrong. Please help. Thank you.

Body:
This is a pretty straight forward bfs problem.

Your visit method is not correct, considering it's pointing to visitNeighbors.

Make it a bfs function. currently, it's a recursive method making it a stack instead of a queue.

    private void visitNeighbors(int startId, int[] distances){
        List<Integer> nodesToVisit = new ArrayList<Integer>();

        nodesToVisit.add(startId);
        distances[startId] = 0;
        while (!nodesToVisit.isEmpty()) {
            int current = nodesToVisit.get(0);
            nodesToVisit.remove(0);
            for (int i : nodes.get(current)) {
                if (distances[i] == -1) {
                    distances[i] = distances[current] + 6;
                    nodesToVisit.add(i);
                }
                //dont recurse right here, otherwise it will become depth-first and we will not get shortest path.
            }
        }
    }

Here is the edited accepted code.


问:
PHP if statement when reading a file from Pastebin somehow doesn't work
So I wrote some PHP code that reads a file from Pastebin and loops through it. My Pastebin file looks like this:

```<code>=WRTSAM=
=Dutch=
=English=
+ Hond
- Dog
+ Eend
- Duck
+ Schaap
- Sheep
+ Kat
- Cat
</code>```

And here is my PHP code:

```<code><?php
$pb_key = $_GET['list'];

$listfile = file('https://pastebin.com/raw/' . $pb_key);

foreach ($listfile as $line_num => $line) {
    if ($line_num == 0) {
        echo $line;

        if ($line == "=WRTSAM=") {
            echo "It works!";
        }
    }
}
?>
</code>```

The weird thing is that is does work for the lines starting with a minus. Could it have something to do with Unicode/ASCII?

Sorry for the (probably) stupid question, but I just can't figure it out. I've been trying random stuff for like an hour.

答:
By default, file() includes the newlines in each string, but the string you're comparing with doesn't have a newline. If you don't want this, use the FILE_IGNORE_NEW_LINE option:

```<code>$listfile = file('https://pastebin.com/raw/' . $pb_key, FILE_IGNORE_NEW_LINES);
</code>```

Body:
So I wrote some PHP code that reads a file from Pastebin and loops through it. My Pastebin file looks like this:

=WRTSAM=
=Dutch=
=English=
+ Hond
- Dog
+ Eend
- Duck
+ Schaap
- Sheep
+ Kat
- Cat

And here is my PHP code:

<?php
$pb_key = $_GET['list'];

$listfile = file('https://pastebin.com/raw/' . $pb_key);

foreach ($listfile as $line_num => $line) {
    if ($line_num == 0) {
        echo $line;

        if ($line == "=WRTSAM=") {
            echo "It works!";
        }
    }
}
?>

The weird thing is that is does work for the lines starting with a minus. Could it have something to do with Unicode/ASCII?

Sorry for the (probably) stupid question, but I just can't figure it out. I've been trying random stuff for like an hour.

Body:
By default, file() includes the newlines in each string, but the string you're comparing with doesn't have a newline. If you don't want this, use the FILE_IGNORE_NEW_LINE option:

$listfile = file('https://pastebin.com/raw/' . $pb_key, FILE_IGNORE_NEW_LINES);


问:
this list comprehension is showing error don't know how to fix
I am trying to populate a list with boolean values I have a list for comparision, if the condition satisfies then True if not then False must be added to the list
I have tried something like

```<code>t_or_f = [True for car in car_types if car in new_car else False]
</code>```

and

```<code>t_or_f = [True for car in car_types if car in new_car True else False]
</code>```

I know that i can achieve it like this

```<code>for car in car_types:
    t_or_f.append(car in new_car)
</code>```

where new_car and car_types are lists ,
but i need to know how i can minimise my code in this  situation using list comprehension

答:
how about this:

```<code>t_or_f = [car in new_car for car in car_types]
</code>```

car in new_car will return True or False anyway so no need to make it more complicated

Body:
I am trying to populate a list with boolean values I have a list for comparision, if the condition satisfies then True if not then False must be added to the list
I have tried something like

t_or_f = [True for car in car_types if car in new_car else False]

and

t_or_f = [True for car in car_types if car in new_car True else False]

I know that i can achieve it like this

for car in car_types:
    t_or_f.append(car in new_car)

where new_car and car_types are lists ,
but i need to know how i can minimise my code in this  situation using list comprehension

Body:
how about this:

t_or_f = [car in new_car for car in car_types]

car in new_car will return True or False anyway so no need to make it more complicated


问:
What is the point of encrypting web.config if user can just decrypt it?
Oi, some vendor is telling my bosses that not encrypting the web.config is big security hole. This sounds like bunk to me. I mean, if someone compromises the server aren't we screwed anyways?</p>

答:
The encryption does not mean that you are protected. The private key needed for decryption is stored on the server, so if your server is compromised your web.config can be decrypted.

We only encrypt the connection string section of the web.config. It helps prevent other prying eyes from easily accessing our connection strings especially in the development environment (which is often much less secure than your production environments).

The encryption is just a small piece to the layered security.  It is by no means an end-all solution for protecting your sensitive information.

ContentLicense: CC BY-SA 4.0


问:
Preventing hexadecimal strings in YAML from loading as float/int in Python
I'm trying to make some changes in a YAML file using python.
I have a file with the structure:

```<code>name:
  mode: value
</code>```

The value is a number of hex digits.
I do:

```<code>import ruamel.yaml as yaml
f = open('C:\\file.yaml', 'r')
data = yaml.load(f, Loader=yaml.RoundTripLoader)
</code>```

then change several values and dump it back:

```<code>with open('C:\\file.yaml', 'w') as out_yaml:
     yaml.dump(in_data, out_yaml, Dumper=yaml.RoundTripDumper, explicit_start=True)
</code>```

And here I have a problem - some values were loaded as int or float and after dump I get values such as .inf or 9.4014e+40 e.g. from YAML:

```<code>name:
  mode1: 8578E877
  mode2: 94014E36
</code>```

How can I preserve the result values from this kind of conversion?

答:
You state "The value is a number of hexdigits" and "some values were loaded as int or float". And according to the YAML 1.2. Core Schema used for round-trip-loading (but also in the simpler JSON schema): those scalars are  int resp. float and not strings.

If you would try to dump a structure with various character combination as strings:

```<code>import sys
from ruamel import yaml

data = dict(
    name=dict(
        teny='decade',
        tbig='8578E877',
        mode='94014E36',
        ints='12345',
        Bool='True',
    )
)
yaml.round_trip_dump(data, sys.stdout)
</code>```

you would get:

```<code>name:
  teny: decade
  tbig: '8578E877'
  mode: '94014E36'
  ints: '12345'
  Bool: 'True'
</code>```

As you can see only decade makes it out as an unquoted scalar, and the reason for this is that the others can be misinterpreted if not quoted.

That is why, if you ever look at how the RoundTripLoader and RoundTripDumper (and their safe and unsafe counterparts) are constructed you can see that both are derived from the Resolver. Even when dumping a value, the patterns from the schema are matched against the regular expressions attached to the Resolver, to make sure it will not be loaded back as a special type. As the quoted True in the YAML output indicates this applies to other types than int and float as well.

The easy solution is to quote the combination of hex digits in your YAML input:

```<code>import sys
from ruamel import yaml

yaml_str = """\
name:
  tbig: '8578E877'
  mode: '94014E36'
"""

data = yaml.round_trip_load(yaml_str)
print(data['name']['tbig'], data['name']['mode'], end='\n----\n')
yaml.round_trip_dump(data, sys.stdout)
</code>```

will print:

```<code>8578E877 94014E36
----
name:
  tbig: '8578E877'
  mode: '94014E36'
</code>```

It is possible to prevent these scalar strings from loading as int resp. float. If you do so by changing the regular expressions attached to Resolver your program will load and dump those in a way no longer adhering to the core schema, so the quotes are not going to be attached on dump automatically when necessary.

If you have too many values in an existing YAML file to change by hand, and want to do a one off conversion, you'll need to use a Loader that has a resolver doesn't use those patterns. Fortunately the BaseLoader does so:

```<code>import sys
from ruamel import yaml

yaml_str = """\
name:
  tbig: 8578E877
  mode: 94014E36
  teny: DECADE
"""

data = yaml.load(yaml_str, yaml.loader.BaseLoader)
yaml.round_trip_dump(data, sys.stdout)
</code>```

gives:

```<code>name:
  tbig: '8578E877'
  mode: '94014E36'
  teny: DECADE
</code>```

adding quotes only where necessary. After that one-time load-dump you can use the normal round-trip or safe loader on that file.

The keys in the YAML output for the first example I gave were the same order as those given in the dict. That was so for Python 3.6, but not when run with 2.7. If you start from a Python data structure and want to control that output order use ruamel.yaml.comments.CommentedMap instead of a dict.

Body:
I'm trying to make some changes in a YAML file using python.
I have a file with the structure:

name:
  mode: value

The value is a number of hex digits.
I do:

import ruamel.yaml as yaml
f = open('C:\\file.yaml', 'r')
data = yaml.load(f, Loader=yaml.RoundTripLoader)

then change several values and dump it back:

with open('C:\\file.yaml', 'w') as out_yaml:
     yaml.dump(in_data, out_yaml, Dumper=yaml.RoundTripDumper, explicit_start=True)

And here I have a problem - some values were loaded as int or float and after dump I get values such as .inf or 9.4014e+40 e.g. from YAML:

name:
  mode1: 8578E877
  mode2: 94014E36

How can I preserve the result values from this kind of conversion?

Body:
You state "The value is a number of hexdigits" and "some values were loaded as int or float". And according to the YAML 1.2. Core Schema used for round-trip-loading (but also in the simpler JSON schema): those scalars are  int resp. float and not strings.

If you would try to dump a structure with various character combination as strings:

import sys
from ruamel import yaml

data = dict(
    name=dict(
        teny='decade',
        tbig='8578E877',
        mode='94014E36',
        ints='12345',
        Bool='True',
    )
)
yaml.round_trip_dump(data, sys.stdout)

you would get:

name:
  teny: decade
  tbig: '8578E877'
  mode: '94014E36'
  ints: '12345'
  Bool: 'True'

As you can see only decade makes it out as an unquoted scalar, and the reason for this is that the others can be misinterpreted if not quoted.

That is why, if you ever look at how the RoundTripLoader and RoundTripDumper (and their safe and unsafe counterparts) are constructed you can see that both are derived from the Resolver. Even when dumping a value, the patterns from the schema are matched against the regular expressions attached to the Resolver, to make sure it will not be loaded back as a special type. As the quoted True in the YAML output indicates this applies to other types than int and float as well.

The easy solution is to quote the combination of hex digits in your YAML input:

import sys
from ruamel import yaml

yaml_str = """\
name:
  tbig: '8578E877'
  mode: '94014E36'
"""

data = yaml.round_trip_load(yaml_str)
print(data['name']['tbig'], data['name']['mode'], end='\n----\n')
yaml.round_trip_dump(data, sys.stdout)

will print:

8578E877 94014E36
----
name:
  tbig: '8578E877'
  mode: '94014E36'

It is possible to prevent these scalar strings from loading as int resp. float. If you do so by changing the regular expressions attached to Resolver your program will load and dump those in a way no longer adhering to the core schema, so the quotes are not going to be attached on dump automatically when necessary.

If you have too many values in an existing YAML file to change by hand, and want to do a one off conversion, you'll need to use a Loader that has a resolver doesn't use those patterns. Fortunately the BaseLoader does so:

import sys
from ruamel import yaml

yaml_str = """\
name:
  tbig: 8578E877
  mode: 94014E36
  teny: DECADE
"""

data = yaml.load(yaml_str, yaml.loader.BaseLoader)
yaml.round_trip_dump(data, sys.stdout)

gives:

name:
  tbig: '8578E877'
  mode: '94014E36'
  teny: DECADE

adding quotes only where necessary. After that one-time load-dump you can use the normal round-trip or safe loader on that file.

The keys in the YAML output for the first example I gave were the same order as those given in the dict. That was so for Python 3.6, but not when run with 2.7. If you start from a Python data structure and want to control that output order use ruamel.yaml.comments.CommentedMap instead of a dict.


问:
How to fetch array data in json or get property of data in laravel
I'm trying to retrieve data from request, so I'm placing $data = $request->only('user_id', 'clientParticipants', 'event_type','contactParticipants', 'schedule', 'stellarParticipants', 'summaries', 'type', 'venue', 'with_client') the following is the format when I did dd($data) in Laravel:

```<code>array:10 [
  "user_id" => 1
  "clientParticipants" => array:2 [
    0 => array:2 [
      "label" => "Check 2 Contact - Test Company 5"
      "value" => 4
    ]
    1 => array:2 [
      "label" => "Ammy Contact - Test Company 6"
      "value" => 5
    ]
  ]
  "event_type" => 2
  "contactParticipants" => array:3 [
    0 => array:2 [
      "label" => "Check Contact - Test Company 3"
      "value" => 2
    ]
    1 => array:2 [
      "label" => "Check 1 Contact - Test Company 2"
      "value" => 3
    ]
    2 => array:2 [
      "label" => "Check 4 contact - Test Company 8"
      "value" => 6
    ]
  ]
  "schedule" => "2017-06-04 05:02:12"
  "stellarParticipants" => array:1 [
    0 => array:2 [
      "label" => "Analyst"
      "value" => 1
    ]
  ]
  "summaries" => array:2 [
    0 => array:5 [
     "client" => array:2 [
        "label" => "Test Company 4"
        "value" => 7
      ]
      "type" => "1"
      "mention" => array:2 [
        "label" => "Analyst"
        "value" => 1
      ]
      "action" => "Action Test 1"
      "comment" => "Comment Test 1"
    ]
    1 => array:5 [
      "client" => array:2 [
        "label" => "Test Company 5"
        "value" => 8
      ]
      "type" => "1"
      "mention" => array:2 [
        "label" => "Analyst"
        "value" => 1
      ]
      "action" => "Action Test 2"
      "comment" => "Comment Test 2"
    ]
  ]
  "type" => "Meeting"
  "venue" => "Mumbai"
  "with_client" => "0"
]
</code>```

I want to retrieve summaries so for this I'm trying to do following:

```<code>if($data['summaries'])
{
    $container = [];
    foreach($data['summaries'] as $summary)
    {
        $summary = json_encode($summary);
        $user_id = $summary->mention['value'];
        $container[] = new InteractionSummary([
            'company_id' => $summary->client,
            'nature' => $summary->type,
            'user_id' => $user_id,
            'action' => $summary->action,
            'feedback' => $summary->comment
        ]);
    }
    $interaction->meetingSummaries()->saveMany($container);
}
</code>```

I'm getting error while retrieving any data in summaries:

Trying to get property of non-object

Update
My InteractionSummary model is:

```<code>class InteractionSummary extends Model
{
    use SoftDeletes;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'company_id', 'interaction_id', 'nature', 'user_id', 'action', 'feedback'
    ];

    /**

     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [

    ];

    protected $dates = [
        'created_at',
        'updated_at',
        'deleted_at',
    ];
}
</code>```

Database schema:

```<code>public function up()
{
    Schema::create('interaction_summaries', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('company_id')->index();
        $table->integer('interaction_id')->index();
        $table->string('nature');
        $table->integer('user_id')->nullable();
        $table->string('action')->nullable();
        $table->string('feedback')->nullable();
        $table->softDeletes();
        $table->timestamps();
    });
}
</code>```

And Interaction have following relationship:

```<code>/**
 * @return \Illuminate\Database\Eloquent\Relations\HasMany
 */
public function meetingSummaries()
{
    return $this->hasMany('App\InteractionSummary');
}
</code>```

答:
The error is that json_encode() function always returns a string, and you are trying to access it as an object.

Moreover, the entire $data variable is already an array, so you do not need to implement any JSON-related actions with its elements.

Just work with it like a normal array:

```<code>foreach($data['summaries'] as $summary)
{
    $container[] = new InteractionSummary([
        'company_id' => $summary['client']['value'],
        'nature' => $summary['type'],
        'user_id' => $summary['mention']['value'],
        'action' => $summary['action'],
        'comment' => $summary['comment']
    ]);
}
</code>```

Body:
I'm trying to retrieve data from request, so I'm placing $data = $request->only('user_id', 'clientParticipants', 'event_type','contactParticipants', 'schedule', 'stellarParticipants', 'summaries', 'type', 'venue', 'with_client') the following is the format when I did dd($data) in Laravel:

array:10 [
  "user_id" => 1
  "clientParticipants" => array:2 [
    0 => array:2 [
      "label" => "Check 2 Contact - Test Company 5"
      "value" => 4
    ]
    1 => array:2 [
      "label" => "Ammy Contact - Test Company 6"
      "value" => 5
    ]
  ]
  "event_type" => 2
  "contactParticipants" => array:3 [
    0 => array:2 [
      "label" => "Check Contact - Test Company 3"
      "value" => 2
    ]
    1 => array:2 [
      "label" => "Check 1 Contact - Test Company 2"
      "value" => 3
    ]
    2 => array:2 [
      "label" => "Check 4 contact - Test Company 8"
      "value" => 6
    ]
  ]
  "schedule" => "2017-06-04 05:02:12"
  "stellarParticipants" => array:1 [
    0 => array:2 [
      "label" => "Analyst"
      "value" => 1
    ]
  ]
  "summaries" => array:2 [
    0 => array:5 [
     "client" => array:2 [
        "label" => "Test Company 4"
        "value" => 7
      ]
      "type" => "1"
      "mention" => array:2 [
        "label" => "Analyst"
        "value" => 1
      ]
      "action" => "Action Test 1"
      "comment" => "Comment Test 1"
    ]
    1 => array:5 [
      "client" => array:2 [
        "label" => "Test Company 5"
        "value" => 8
      ]
      "type" => "1"
      "mention" => array:2 [
        "label" => "Analyst"
        "value" => 1
      ]
      "action" => "Action Test 2"
      "comment" => "Comment Test 2"
    ]
  ]
  "type" => "Meeting"
  "venue" => "Mumbai"
  "with_client" => "0"
]

I want to retrieve summaries so for this I'm trying to do following:

if($data['summaries'])
{
    $container = [];
    foreach($data['summaries'] as $summary)
    {
        $summary = json_encode($summary);
        $user_id = $summary->mention['value'];
        $container[] = new InteractionSummary([
            'company_id' => $summary->client,
            'nature' => $summary->type,
            'user_id' => $user_id,
            'action' => $summary->action,
            'feedback' => $summary->comment
        ]);
    }
    $interaction->meetingSummaries()->saveMany($container);
}

I'm getting error while retrieving any data in summaries:

Trying to get property of non-object

Update
My InteractionSummary model is:

class InteractionSummary extends Model
{
    use SoftDeletes;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'company_id', 'interaction_id', 'nature', 'user_id', 'action', 'feedback'
    ];

    /**

     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [

    ];

    protected $dates = [
        'created_at',
        'updated_at',
        'deleted_at',
    ];
}

Database schema:

public function up()
{
    Schema::create('interaction_summaries', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('company_id')->index();
        $table->integer('interaction_id')->index();
        $table->string('nature');
        $table->integer('user_id')->nullable();
        $table->string('action')->nullable();
        $table->string('feedback')->nullable();
        $table->softDeletes();
        $table->timestamps();
    });
}

And Interaction have following relationship:

/**
 * @return \Illuminate\Database\Eloquent\Relations\HasMany
 */
public function meetingSummaries()
{
    return $this->hasMany('App\InteractionSummary');
}

Body:
The error is that json_encode() function always returns a string, and you are trying to access it as an object.

Moreover, the entire $data variable is already an array, so you do not need to implement any JSON-related actions with its elements.

Just work with it like a normal array:

foreach($data['summaries'] as $summary)
{
    $container[] = new InteractionSummary([
        'company_id' => $summary['client']['value'],
        'nature' => $summary['type'],
        'user_id' => $summary['mention']['value'],
        'action' => $summary['action'],
        'comment' => $summary['comment']
    ]);
}