问:
Convert consecutive Trues, to False python
Essentially, I want to convert consecutive duplicates of Trues, to False as the title suggests.

For example, say, i have an array of 0s and 1s

```<code>x = pd.Series([1,0,0,1,1])
</code>```

should become:

```<code>y = pd.Series([0,0,0,0,1])
# where the 1st element of x becomes 0 since its not a consecutive
# and the 4th element becomes 0 because its the first instance of the consecutive duplicate
# And everything else should remain the same.
</code>```

This can also apply to consecutives of more than two, Say i have a much longer array:
eg.

```<code>x = pd.Series([1,0,0,1,1,1,0,1,1,0,1,1,1,1,0,0,1,1,1,1,1])
</code>```

becomes;

```<code>y = pd.Series([0,0,0,0,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0,1])
</code>```

Posts that i have searched are mostly either deleting consecutive duplicates, and does not retain the original length. In this case, it should retain the original length.

It is something like the following code:

```<code>for i in range(len(x)):
    if x[i] == x[i+1]:
        x[i] = True
    else:
       x[i] = False
</code>```

but this gives me a never ending run. And does not accommodate consecutives of more than two.

答:
Pandas solution - create Series, then consecutive groups by shift and cumsum and filter last 1 values in duplicates by Series.duplicated:

```<code>s = pd.Series(x)
g = s.ne(s.shift()).cumsum()
s1 = (~g.duplicated(keep='last') & g.duplicated(keep=False) & s.eq(1)).astype(int)

print (s1.tolist())
[0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1]
</code>```

EDIT:

For multiple columns use function:

```<code>x = pd.Series([1,0,0,1,1,1,0,1,1,0,1,1,1,1,0,0,1,1,1,1,1])
df = pd.DataFrame({'a':x, 'b':x})

def f(s):
    g = s.ne(s.shift()).cumsum()
    return (~g.duplicated(keep='last') & g.duplicated(keep=False) & s.eq(1)).astype(int)

df = df.apply(f)
print (df)
    a  b
0   0  0
1   0  0
2   0  0
3   0  0
4   0  0
5   1  1
6   0  0
7   0  0
8   1  1
9   0  0
10  0  0
11  0  0
12  0  0
13  1  1
14  0  0
15  0  0
16  0  0
17  0  0
18  0  0
19  0  0
20  1  1
</code>```

Body:
Essentially, I want to convert consecutive duplicates of Trues, to False as the title suggests.

For example, say, i have an array of 0s and 1s

x = pd.Series([1,0,0,1,1])

should become:

y = pd.Series([0,0,0,0,1])
# where the 1st element of x becomes 0 since its not a consecutive
# and the 4th element becomes 0 because its the first instance of the consecutive duplicate
# And everything else should remain the same.

This can also apply to consecutives of more than two, Say i have a much longer array:
eg.

x = pd.Series([1,0,0,1,1,1,0,1,1,0,1,1,1,1,0,0,1,1,1,1,1])

becomes;

y = pd.Series([0,0,0,0,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0,1])

Posts that i have searched are mostly either deleting consecutive duplicates, and does not retain the original length. In this case, it should retain the original length.

It is something like the following code:

for i in range(len(x)):
    if x[i] == x[i+1]:
        x[i] = True
    else:
       x[i] = False

but this gives me a never ending run. And does not accommodate consecutives of more than two.

Body:
Pandas solution - create Series, then consecutive groups by shift and cumsum and filter last 1 values in duplicates by Series.duplicated:

s = pd.Series(x)
g = s.ne(s.shift()).cumsum()
s1 = (~g.duplicated(keep='last') & g.duplicated(keep=False) & s.eq(1)).astype(int)

print (s1.tolist())
[0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1]

EDIT:

For multiple columns use function:

x = pd.Series([1,0,0,1,1,1,0,1,1,0,1,1,1,1,0,0,1,1,1,1,1])
df = pd.DataFrame({'a':x, 'b':x})

def f(s):
    g = s.ne(s.shift()).cumsum()
    return (~g.duplicated(keep='last') & g.duplicated(keep=False) & s.eq(1)).astype(int)

df = df.apply(f)
print (df)
    a  b
0   0  0
1   0  0
2   0  0
3   0  0
4   0  0
5   1  1
6   0  0
7   0  0
8   1  1
9   0  0
10  0  0
11  0  0
12  0  0
13  1  1
14  0  0
15  0  0
16  0  0
17  0  0
18  0  0
19  0  0
20  1  1


来源: stackexchange

问:
how to build mingw qt project in vs2017
I have project used Qt mingw to build, but I want to use it in visual studio 2017, but it can't work and occurred an error.

Microsoft says vs2017 can use gcc, but I can't find c++ compiler in my vs2017.
https://blogs.msdn.microsoft.com/c/2017/03/27/%E5%9C%A8visual-studio%E4%B8%AD%E4%BD%BF%E7%94%A8%E4%BB%BB%E4%BD%95c%E7%BC%96%E8%AF%91%E5%99%A8

答:
Welcome @godlovemoon!

First: the given url is invalid.
Second: do you want to use the VisualStudio compiler tobuild the project, which was previously built with GCC. Or use the GCC inside VS as compiler?

ContentLicense: CC BY-SA 4.0

Title: how to build mingw qt project in vs2017


问:
There is data conversion error in my text_based music player program
In the function read_genre Which display the available genre in a list (that I defined 9 different genres inside $genre_name =[] outside of the function) and prompt the user to select a genre by using a case statement and then read in the genre number that user entered a number. The read_genre function is called from the read_album function and then printout in print_album function.

The problem is that after I run the program in the terminal when I prompt to select a genre and entered the number and I get an error  'no implicit conversion from nil to integer (typeError).

I tried by changing the conversion type to to_i(int) and still get the error.

```<code>module Genre
  POP, CLASSIC, JAZZ, ROCK, KPOP, METAL, PUNK, ROMANCE, LATIN = *1..9
end

$genre_names = ['Null','Pop', 'Classic', 'Jazz', 'Rock', 'KPop', 'Metal', 'Punk', 'Romance', 'Latin']

class Album
    attr_accessor :title, :artist, :genre

    def initialize (title, artist, genre)
        @title = title
        @artist = artist
        @genre = genre
    end
end

# Display the genre names in a
# numbered list and ask the user to select one
def read_genre()
    length = $genre_names.length
    index = 0
    print $genre_names
  while (index < length)
    select_genre = read_integer_in_range("Select Genre: ", 0,9)
        case select_genre
        when 1
        puts "#{index + 1} " + $genre_names[1]
        break
        when 2
        puts "#{index + 2 } " + $genre_names[2]
        break
        when 3
        puts "#{index + 3} " + $genre_names[3]
        break
        when 4
        puts "#{index + 4} " + $genre_names[4]
        break
        when 5
        puts "#{index + 5} " + $genre_names[5]
        break
        when 6
        puts "#{index + 6} " + $genre_names[6]
        break
        when 7
        puts "#{index + 7} " + $genre_names[7]
        break
        when 8
        puts "#{index + 8} " + $genre_names[8]
        break
        when 9
        puts "#{index + 9} " + $genre_names[9]
        break
         else
          puts 'Please Select again'
          break
        end

    end

end

def read_album
  album_title = read_string("Enter Title: ")
  album_artist = read_string("Enter Artist name: ")
  album_genre = read_genre()
  album = Album.new(album_title, album_artist, album_genre)
  album
end

def print_album album
    puts ' Album information is: '
    puts "Title is #{album.title}"
    puts "Artist is #{album.artist}"
    puts 'Genre is ' + album.genre.to_s
    puts $genre_names[album.genre]

end

def read_integer_in_range(prompt, min, max)
    value = read_integer(prompt)
    while (value < min or value > max)
        puts "Please enter a value between " + min.to_s + " and " + max.to_s + ": "
        value = read_integer(prompt);
    end
    value
end

def main
  puts "Welcome to the music player"
    album = read_album()
    print_album(album)
end

main

</code>```

When I entered the number for the specific genre index. for example, if I entered 2 it must display Classic because it is in index 2 in $genre_names variable.

答:
So I think your read_integer(prompt) function should be something like this ...

```<code>def read_integer(prompt)
  print(prompt)
  gets.strip().to_i
end
</code>```

gets.strip() -> this will return a string like for eg. "2"

"2".to_i -> this then converts from a String to an Integer

This should return an Integer and then you are off to the races.

Hope this helps.

Body:
In the function read_genre Which display the available genre in a list (that I defined 9 different genres inside $genre_name =[] outside of the function) and prompt the user to select a genre by using a case statement and then read in the genre number that user entered a number. The read_genre function is called from the read_album function and then printout in print_album function.

The problem is that after I run the program in the terminal when I prompt to select a genre and entered the number and I get an error  'no implicit conversion from nil to integer (typeError).

I tried by changing the conversion type to to_i(int) and still get the error.

module Genre
  POP, CLASSIC, JAZZ, ROCK, KPOP, METAL, PUNK, ROMANCE, LATIN = *1..9
end

$genre_names = ['Null','Pop', 'Classic', 'Jazz', 'Rock', 'KPop', 'Metal', 'Punk', 'Romance', 'Latin']

class Album
    attr_accessor :title, :artist, :genre

    def initialize (title, artist, genre)
        @title = title
        @artist = artist
        @genre = genre
    end
end

# Display the genre names in a
# numbered list and ask the user to select one
def read_genre()
    length = $genre_names.length
    index = 0
    print $genre_names
  while (index < length)
    select_genre = read_integer_in_range("Select Genre: ", 0,9)
        case select_genre
        when 1
        puts "#{index + 1} " + $genre_names[1]
        break
        when 2
        puts "#{index + 2 } " + $genre_names[2]
        break
        when 3
        puts "#{index + 3} " + $genre_names[3]
        break
        when 4
        puts "#{index + 4} " + $genre_names[4]
        break
        when 5
        puts "#{index + 5} " + $genre_names[5]
        break
        when 6
        puts "#{index + 6} " + $genre_names[6]
        break
        when 7
        puts "#{index + 7} " + $genre_names[7]
        break
        when 8
        puts "#{index + 8} " + $genre_names[8]
        break
        when 9
        puts "#{index + 9} " + $genre_names[9]
        break
         else
          puts 'Please Select again'
          break
        end

    end

end

def read_album
  album_title = read_string("Enter Title: ")
  album_artist = read_string("Enter Artist name: ")
  album_genre = read_genre()
  album = Album.new(album_title, album_artist, album_genre)
  album
end

def print_album album
    puts ' Album information is: '
    puts "Title is #{album.title}"
    puts "Artist is #{album.artist}"
    puts 'Genre is ' + album.genre.to_s
    puts $genre_names[album.genre]

end

def read_integer_in_range(prompt, min, max)
    value = read_integer(prompt)
    while (value < min or value > max)
        puts "Please enter a value between " + min.to_s + " and " + max.to_s + ": "
        value = read_integer(prompt);
    end
    value
end

def main
  puts "Welcome to the music player"
    album = read_album()
    print_album(album)
end

main

When I entered the number for the specific genre index. for example, if I entered 2 it must display Classic because it is in index 2 in $genre_names variable.

Body:
So I think your read_integer(prompt) function should be something like this ...

def read_integer(prompt)
  print(prompt)
  gets.strip().to_i
end

gets.strip() -> this will return a string like for eg. "2"

"2".to_i -> this then converts from a String to an Integer

This should return an Integer and then you are off to the races.

Hope this helps.


问:
Worksheet change event with multiple selections
I have a sheet that i keep a log of the changes that happen on it such as data entered into a cell or data deleted etc. This works great except for when multiple selections happen.

For example if i select B2 and D2 and F2 and deleted the contents of the cells the worksheet change event will only pick up the change for the first cell, B2. So i have no idea what happened to the other cells.

Is there a way i can get around this and either get it to log the worksheet change for the other cells or stop multiple selection deletes happening ?

Here is my code

```<code>Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As

Range)

Dim ws As Worksheet, iRow As Long, iCol As Long, Message As String, SheetId As String, iRowE As Long, iColE As Long, iRowB As Long, iColB As Long

Set ws = Sh
SheetId = Replace(ws.Name, " ", "")
SheetId = Left(SheetId, 2) & Right(SheetId, 2)

iRowB = Target.Row
iColB = Target.Column
iRowE = iRowB + Target.Rows.Count - 1
iColE = iColB + Target.Columns.Count - 1

Message = Format(Now(), "ddHHmmss") & Application.UserName & "-" & SheetId

For iRow = iRowB To iRowE
  For iCol = iColB To iColE
    Message = Message & "|" & Format(iRow, " 0") & Format(iCol, " 0") & "|" & CStr(ws.Cells(iRow, iCol).Text)
  Next iCol
Next iRow

If Not FileExists("L:\HC\" & ThisWorkbook.Name & Format(Now(), "YYYYMM") & ".Log") Then
  Call LogIt("L:\HC\" & ThisWorkbook.Name & Format(Now(), "YYYYMM") & ".Log", "ddHHmmssUSER-sheet|row col|value|row col|value")
End If

Call LogIt("L:\HC\" & ThisWorkbook.Name & Format(Now(), "YYYYMM") & ".Log", Message)

End Sub
</code>```

答:
Some guidelines:</p>

```<code>Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim cell As Range

    'Loop all selections
    For Each cell In Target

        With cell
            Debug.Print .Address
        End With

    Next cell

    'Exit sub when selection is more than one cell
    If Target.Count > 1 Then
        Exit Sub
    End If

End Sub
</code>```

Body:
I have a sheet that i keep a log of the changes that happen on it such as data entered into a cell or data deleted etc. This works great except for when multiple selections happen.

For example if i select B2 and D2 and F2 and deleted the contents of the cells the worksheet change event will only pick up the change for the first cell, B2. So i have no idea what happened to the other cells.

Is there a way i can get around this and either get it to log the worksheet change for the other cells or stop multiple selection deletes happening ?

Here is my code

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As

Range)

Dim ws As Worksheet, iRow As Long, iCol As Long, Message As String, SheetId As String, iRowE As Long, iColE As Long, iRowB As Long, iColB As Long

Set ws = Sh
SheetId = Replace(ws.Name, " ", "")
SheetId = Left(SheetId, 2) & Right(SheetId, 2)

iRowB = Target.Row
iColB = Target.Column
iRowE = iRowB + Target.Rows.Count - 1
iColE = iColB + Target.Columns.Count - 1

Message = Format(Now(), "ddHHmmss") & Application.UserName & "-" & SheetId

For iRow = iRowB To iRowE
  For iCol = iColB To iColE
    Message = Message & "|" & Format(iRow, " 0") & Format(iCol, " 0") & "|" & CStr(ws.Cells(iRow, iCol).Text)
  Next iCol
Next iRow

If Not FileExists("L:\HC\" & ThisWorkbook.Name & Format(Now(), "YYYYMM") & ".Log") Then
  Call LogIt("L:\HC\" & ThisWorkbook.Name & Format(Now(), "YYYYMM") & ".Log", "ddHHmmssUSER-sheet|row col|value|row col|value")
End If

Call LogIt("L:\HC\" & ThisWorkbook.Name & Format(Now(), "YYYYMM") & ".Log", Message)

End Sub

Body:
Some guidelines:

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim cell As Range

    'Loop all selections
    For Each cell In Target

        With cell
            Debug.Print .Address
        End With

    Next cell

    'Exit sub when selection is more than one cell
    If Target.Count > 1 Then
        Exit Sub
    End If

End Sub


问:
JS formatting date ymd to yyyy-mm-dd
I am getting my date from PHP in format ymd. I am using Moment.js to convert it to format I need, but it's not working properly.

So for example today's date is comes like 190528 but after conversion to YYYY-MM-DD it becomes 190528-1-1 instead of 2019-05-28.

Is it the first format of the date which causes the problem, or there is a way to overcome this and convert it the way I need?

答:
You can pass the format of current date as a second param of moment.

console.log(moment("190528", "YYMMDD").format("YYYY-MM-DD"));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script></code>```

Here the docs.

Title: JS formatting date ymd to yyyy-mm-dd

Body:
You can pass the format of current date as a second param of moment.

console.log(moment("190528", "YYMMDD").format("YYYY-MM-DD"));

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

Here the docs.


问:
WordPress get_the_post_thumbnail_url() not working when posting from front-end
Whenever I post from the dashboard, I can grab the featured image URL with get_the_post_thumbnail_url() and display it in a email with wp_mail(). However, when I try this from the front-end, I get a empty URL.

Ive tried numerous frontend plugins but none works when it comes to the featured image. The rest of the post's fields display fine in the emails.

Im using the following code:

```<code>// POST MAILMAN

// Add the hook action
add_action('transition_post_status', 'send_new_post', 10, 3);

// Listen for publishing of a new post
function send_new_post($new_status, $old_status, $post) {

if('publish' === $new_status && 'publish' !== $old_status && $post->post_type === 'post') {

$latestPost_ID = $post->ID;
$latestPost_ImgUrl = get_the_post_thumbnail_url($latestPost_ID, 'full');
$latestPost_Category = get_the_category($latestPost_ID);
$latestPost_Category_Name = esc_html( $latestPost_Category[0]->name );
$latestPost_Url = get_post_permalink($latestPost_ID);
$latestPost_Title = get_post_field( 'post_title', $latestPost_ID );
$latestPost_Excerpt = get_post_field( 'post_excerpt', $latestPost_ID );
$todaydate = date("l") . ", " . date("j") . " " . date("F") . " " . date("Y");
</code>```

to display the image in the email:

```<code><td class="fluid-img" style="font-size:0pt; line-height:0pt; text-align:left;"><img src="' . esc_url($latestPost_ImgUrl) . '" border="0" width="650" height="366" alt="" /></td>
</code>```

When done front-end vs backend:
https://imgur.com/a/TqP9L6a

Some plugins I tried:
https://wordpress.org/plugins/accesspress-anonymous-post/
https://wordpress.org/plugins/wp-user-frontend/

答:
I find getting the Featured Image via it's attachment record is more reliable, for either public-facing or admin requests. Try this:</p>

```<code>$attachment = wp_get_attachment_image_src(get_post_thumbnail_id($latestPost_ID), 'full', true);
$featuredImageUrl = $attachment[0];
</code>```

Body:
Whenever I post from the dashboard, I can grab the featured image URL with get_the_post_thumbnail_url() and display it in a email with wp_mail(). However, when I try this from the front-end, I get a empty URL.

Ive tried numerous frontend plugins but none works when it comes to the featured image. The rest of the post's fields display fine in the emails.

Im using the following code:

// POST MAILMAN

// Add the hook action
add_action('transition_post_status', 'send_new_post', 10, 3);

// Listen for publishing of a new post
function send_new_post($new_status, $old_status, $post) {

if('publish' === $new_status && 'publish' !== $old_status && $post->post_type === 'post') {

$latestPost_ID = $post->ID;
$latestPost_ImgUrl = get_the_post_thumbnail_url($latestPost_ID, 'full');
$latestPost_Category = get_the_category($latestPost_ID);
$latestPost_Category_Name = esc_html( $latestPost_Category[0]->name );
$latestPost_Url = get_post_permalink($latestPost_ID);
$latestPost_Title = get_post_field( 'post_title', $latestPost_ID );
$latestPost_Excerpt = get_post_field( 'post_excerpt', $latestPost_ID );
$todaydate = date("l") . ", " . date("j") . " " . date("F") . " " . date("Y");

to display the image in the email:

When done front-end vs backend:
https://imgur.com/a/TqP9L6a

Some plugins I tried:
https://wordpress.org/plugins/accesspress-anonymous-post/
https://wordpress.org/plugins/wp-user-frontend/

Body:
I find getting the Featured Image via it's attachment record is more reliable, for either public-facing or admin requests. Try this:

$attachment = wp_get_attachment_image_src(get_post_thumbnail_id($latestPost_ID), 'full', true);
$featuredImageUrl = $attachment[0];


问:
how to hide button create/edit in module employee to employee who belongs to group Employee/employee?
i develop a custom module  to restrict the right to create a new employee or to modify an existing one to the employees who belongs to group "Employee/Employee" but i notice even though my employee has the right "Employee/Manager" he became not able to create or edit employees. How can i fix that problem ? Any idea for help please ?
here is my code :

hr_employee_view.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<odoo>
<record id="view_hr_employee_form_remove_edit" model="ir.ui.view">
    <field name="name">view.hr.employee.form.remove.edit</field>
    <field name="model">hr.employee</field>
    <field name="inherit_id" ref="hr.view_employee_form"/>
    <field name="groups_id" eval="[(4,ref('base.group_user'))]"/>
    <field name="arch" type="xml">
        <xpath expr="//form" position="attributes">
            <attribute name="edit">false</attribute>
            <attribute name="create">false</attribute>

        </xpath>
    </field>
</record>

<record id="view_hr_employee_tree_remove_edit_create" model="ir.ui.view">
    <field name="name">view.hr.employee.tree.remove.edit.create</field>
    <field name="model">hr.employee</field>
    <field name="inherit_id" ref="hr.view_employee_tree"/>
    <field name="groups_id" eval="[(6, 0, [ref('base.group_user')])]"/>
    <field name="arch" type="xml">
        <xpath expr="//tree" position="attributes">
            <attribute name="edit">false</attribute>
            <attribute name="create">false</attribute>
        </xpath>
    </field>
</record>

<record id="view_hr_employee_kanban_remove_edit_create" model="ir.ui.view">
    <field name="name">view.hr.employee.kanban.remove.edit.create</field>
    <field name="model">hr.employee</field>
    <field name="inherit_id" ref="hr.hr_kanban_view_employees"/>
    <field name="groups_id" eval="[(6, 0, [ref('base.group_user')])]"/>
    <field name="arch" type="xml">
        <xpath expr="//kanban" position="attributes">
            <attribute name="edit">false</attribute>
            <attribute name="create">false</attribute>
        </xpath>
    </field>
</record>

</odoo>
</code>```

答:
Add this rule to your module, it will hide the button 'create' only for the hr_user group and not for hr_manager group, you should create new file security.xml, where you can past this rule

```<code>  <record id="rule_security_groups_hr_user" model="ir.rule">
        <field name="name">User can't edit or create employees.</field>
        <field name="model_id" ref="hr.model_hr_employee"/>
        <field name="groups" eval="[(4, ref('hr.group_hr_user'))]"/>
        <field name="perm_read" eval="1"/>
        <field name="perm_create" eval="0"/>
        <field name="perm_write" eval="0"/>
        <field name="perm_unlink" eval="0" />
        <field name="domain_force">[('user_id','=',user.id)]</field>
    </record>
</code>```

I hope this helps you. good luck

Body:
i develop a custom module  to restrict the right to create a new employee or to modify an existing one to the employees who belongs to group "Employee/Employee" but i notice even though my employee has the right "Employee/Manager" he became not able to create or edit employees. How can i fix that problem ? Any idea for help please ?
here is my code :

hr_employee_view.xml

<?xml version="1.0" encoding="utf-8"?>
<odoo>
<record id="view_hr_employee_form_remove_edit" model="ir.ui.view">
    <field name="name">view.hr.employee.form.remove.edit</field>
    <field name="model">hr.employee</field>
    <field name="inherit_id" ref="hr.view_employee_form"/>
    <field name="groups_id" eval="[(4,ref('base.group_user'))]"/>
    <field name="arch" type="xml">
        <xpath expr="//form" position="attributes">
            <attribute name="edit">false</attribute>
            <attribute name="create">false</attribute>

        </xpath>
    </field>
</record>

<record id="view_hr_employee_tree_remove_edit_create" model="ir.ui.view">
    <field name="name">view.hr.employee.tree.remove.edit.create</field>
    <field name="model">hr.employee</field>
    <field name="inherit_id" ref="hr.view_employee_tree"/>
    <field name="groups_id" eval="[(6, 0, [ref('base.group_user')])]"/>
    <field name="arch" type="xml">
        <xpath expr="//tree" position="attributes">
            <attribute name="edit">false</attribute>
            <attribute name="create">false</attribute>
        </xpath>
    </field>
</record>

<record id="view_hr_employee_kanban_remove_edit_create" model="ir.ui.view">
    <field name="name">view.hr.employee.kanban.remove.edit.create</field>
    <field name="model">hr.employee</field>
    <field name="inherit_id" ref="hr.hr_kanban_view_employees"/>
    <field name="groups_id" eval="[(6, 0, [ref('base.group_user')])]"/>
    <field name="arch" type="xml">
        <xpath expr="//kanban" position="attributes">
            <attribute name="edit">false</attribute>
            <attribute name="create">false</attribute>
        </xpath>
    </field>
</record>

</odoo>

Body:
Add this rule to your module, it will hide the button 'create' only for the hr_user group and not for hr_manager group, you should create new file security.xml, where you can past this rule

  <record id="rule_security_groups_hr_user" model="ir.rule">
        <field name="name">User can't edit or create employees.</field>
        <field name="model_id" ref="hr.model_hr_employee"/>
        <field name="groups" eval="[(4, ref('hr.group_hr_user'))]"/>
        <field name="perm_read" eval="1"/>
        <field name="perm_create" eval="0"/>
        <field name="perm_write" eval="0"/>
        <field name="perm_unlink" eval="0" />
        <field name="domain_force">[('user_id','=',user.id)]</field>
    </record>

I hope this helps you. good luck


问:
How to get N consecutive digits from a string?
I am trying to get 4 consecutive digits from a string wherever it is matched.

when I am trying re.sub('[^\d]+', ',', "abc 23 [1981] ghj [5656]") it returns ,23,1981,5656,.so when i do re.sub('[\d]{4}+', ',', "abc 23 [2021]") it returns an error "multiple repeat at position 7"

Since I am keeping {4}, shouldn't it match for 4 occurrences of [\d] and return ,1981,5656, ?

答:
What you want is a little tricky if you want to do it using regex only.

Instead you can use lambda to conditionally replace parts of string that is not four digits with a comma and retain the four digits as it is. Try using this Python code,

```<code>import re

s = "abc 23 [1981] ghj [5656]"
print(re.sub(r'\b(\d{4})\b|((?!\b\d{4}\b).)+', lambda x: x.group() if x.group(1) else ',', s))
</code>```

Prints following just like you wanted,

```<code>,1981,5656,
</code>```

What we are doing here is, capturing four digits using \b(\d{4})\b in group1 and capturing any other one or more characters that doesn't have four digits using this ((?!\b\d{4}\b).)+ regex and we do a conditional replace, where if first alternation is matched then group1 is not empty hence replace it with matched text and if group1 is empty meaning second regex matched, hence replace it using a comma instead.

Body:
What you want is a little tricky if you want to do it using regex only.

Instead you can use lambda to conditionally replace parts of string that is not four digits with a comma and retain the four digits as it is. Try using this Python code,

import re

s = "abc 23 [1981] ghj [5656]"
print(re.sub(r'\b(\d{4})\b|((?!\b\d{4}\b).)+', lambda x: x.group() if x.group(1) else ',', s))

Prints following just like you wanted,

,1981,5656,

What we are doing here is, capturing four digits using \b(\d{4})\b in group1 and capturing any other one or more characters that doesn't have four digits using this ((?!\b\d{4}\b).)+ regex and we do a conditional replace, where if first alternation is matched then group1 is not empty hence replace it with matched text and if group1 is empty meaning second regex matched, hence replace it using a comma instead.


答:
Parse Date first by passing format as 'YYMMDD'

```<code>moment("190528", "YYMMDD").format("YYYY-MM-DD");
</code>```

This will give proper output.

Title: JS formatting date ymd to yyyy-mm-dd

Body:
I am getting my date from PHP in format ymd. I am using Moment.js to convert it to format I need, but it's not working properly.

So for example today's date is comes like 190528 but after conversion to YYYY-MM-DD it becomes 190528-1-1 instead of 2019-05-28.

Is it the first format of the date which causes the problem, or there is a way to overcome this and convert it the way I need?

Body:
Parse Date first by passing format as 'YYMMDD'

moment("190528", "YYMMDD").format("YYYY-MM-DD");

This will give proper output.


问:
Guice injector in JUnit tests
Using Guice, is it a good practice to get a new injector in each JUnit test class, as each test class should be independant?</p>

答:
You should really avoid using Guice in unit tests as each test should be small enough that manual DI is manageable. By using Guice (or any DI) in unit tests you are hiding away a warning that your class is getting too big and taking on too many responsibilities.

For testing the bootstrapper code and integration tests then yes create a different injector for each test.

ContentLicense: CC BY-SA 3.0

Title: Guice injector in JUnit tests


问:
Secure access to Microsoft Azure Blob Storage
I have a frontend container, backend container and the azure blob storage. User using the front/backend are authenticated. Thus the backend validates the user credentials and users are allowed to access their media files stored in the azure blob storage.

I would like that users access their media files directly at the azure blob storage in order not to stress the backend to much by using it as a proxy. The media references for each user are stored in the backend.

How would you achieve this by using the azure blob storage and its access control (or is it a misuse of the azure blob storage)?

答:
You can implement security by generating a SAS token for your blob container/individual blob

With a SAS, you can grant clients access to resources in your storage account, without sharing your account keys


答:
You do not need to load moment for this.

You can break the string into parts of years, month and date. Format the year and return the joined string...

function formatDate(date) {
  var _d = date.match(/.{1,2}/g);
  _d[0] = "20" + _d[0];
  return _d.join("-");
}
var d = "190528";
console.log(formatDate(d));```

Title: JS formatting date ymd to yyyy-mm-dd


问:
How to remove CSS animation from element in vanilla JS
I've got a square grid of n x n smaller square div elements that I want to illuminate in a sequence with a CSS background color animation. I have a function to generate a random array for the sequence. The trouble I'm having is that once a certain square has been illuminated once, if it occurs again within the array it won't illuminate a second time. I believe it's because once the element has been assigned the CSS animation, the animation can't trigger again on that element, and I can't figure a way to make it work. It's for a Responsive Web Apps course I'm taking, and the assessment stipulates that we're only to use vanilla JS, and that all elements must be created in JS and appended to a blank  in our index.html.

Each flash according to the sequence is triggered through a setTimeout function that loops through all elements in the array increasing it's timer by 1s for each loop (the animation length is 1s also).

Defining containers and child divs:

```<code>function createGameContainer(n, width, height) {
    var container = document.createElement('div');

    //CSS styling
    container.style.margin = '50px auto'
    container.style.width = width;
    container.style.height = height;
    container.style.display = 'grid';

    // loop generates string to create necessary number of grid columns based on the width of the grid of squares
    var columns = '';
    for (i = 0; i < n; i++) {
        columns += ' calc(' + container.style.width + '/' + n.toString() + ')'
    }
    container.style.gridTemplateColumns = columns;

    container.style.gridRow = 'auto auto';

    // gap variable to reduce column and row gap for larger grid sizes
    // if n is ever set to less than 2, gap is hardcoded to 20 to avoid taking square root of 0 or a negative value
    var gap;
    if (n > 1) {
        gap = 20/Math.sqrt(n-1);
    } else {
        gap = 20;
    }

    container.style.gridColumnGap = gap.toString() + 'px';
    container.style.gridRowGap = gap.toString() + 'px';

    container.setAttribute('id', 'game-container');

    document.body.appendChild(container);
}

/*
function to create individual squares to be appended to parent game container
*/
function createSquare(id) {
    var square = document.createElement('div');

    //CSS styling
    square.style.backgroundColor = '#333';
    //square.style.padding = '20px';
    square.style.borderRadius = '5px';
    square.style.display = 'flex';
    square.style.alignItems = 'center';
    //set class and square id
    square.setAttribute('class', 'square');
    square.setAttribute('id', id);

    return square;
}
/*
function to create game container and and squares and append squares to parent container
parameter n denotes dimensions of game grid - n x n grid
*/

function createGameWindow(n, width, height) {
    window.dimension = n;
    createGameContainer(n, width, height);

    /*
    loop creates n**2 number of squares to fill game container and assigns an id to each square from 0 at the top left square to (n**2)-1 at the bottom right square
    */
    for (i = 0; i < n**2; i++) {
        var x = createSquare(i);
        document.getElementById('game-container').appendChild(x);
    }
}
</code>```

The CSS animation:

```<code>@keyframes flash {
    0% {
        background: #333;
    }

    50% {
        background: orange
    }

    100% {
        background: #333;
    }
}

.flashing {
    animation: flash 1s;
}

</code>```

The code to generate the array:

```<code>function generateSequence(sequenceLength) {
    var sequence = [];
    for (i = 0; i < sequenceLength; i++) {
        var random = Math.floor(Math.random() * (dimension**2));
        // the following loop ensures each element in the sequence is different than the previous element
        while (sequence[i-1] == random) {
            random = Math.floor(Math.random() * (dimension**2));
        }
        sequence[i] = random;
    };

    return sequence;
}
</code>```

Code to apply animation to square:

```<code>function flash(index, delay) {
    setTimeout( function() {
        flashingSquare = document.getElementById(index);
        flashingSquare.style.animation = 'flashOne 1s';
        flashingSquare.addEventListener('animationend', function() {
            flashingSquare.style.animation = '';
    }, delay);
}
</code>```

I've also tried removing and adding a class again to try and reset the animation:

```<code>function flash(index, delay) {
    setTimeout( function() {
        flashingSquare = document.getElementById(index);
        flashingSquare.classList.remove('flashing');
        flashingSquare.classList.add('flashing');
    }, delay);
}
</code>```

And the function to generate and display the sequence:

```<code>function displaySequence(sequenceLength) {
    var sequence = generateSequence(sequenceLength);

    i = 0;
    while (i < sequence.length) {
        index = sequence[i].toString();
        flash(index, i*1000);

        i++;
    }
}
</code>```

Despite many different attempts and a bunch of research I can't figure a way to get the animations to trigger multiple times on the same element.

答:
After some research, I figured out a work around. I rewrote the function so that the setTimeout was nested within a for loop, and the setTimeout nested within an immediately invoked function expression (which I still don't fully understand, but hey, if it works). The new function looks like this:

```<code>/*
function to display game sequence
length can be any integer greater than 1
speed is time between flashes in ms and can presently be set to 1000, 750, 500 and 250.
animation length for each speed is set by a corresponding speed class
in CSS main - .flashing1000 .flashing750 .flashing500 and .flashing250
*/
function displaySequence(length, speed) {
    var sequence = generateSequence(length);
    console.log(sequence);

    for (i = 0; i < sequence.length; i++) {
        console.log(sequence[i]);
        //       immediately invoked function expression
        (function(i) {
            setTimeout( function () {
                var sq = document.getElementById(sequence[i]);
                sq.classList.add('flashing' + speed.toString());
                sq.addEventListener('animationend', function() {
                    sq.classList.remove('flashing' + speed.toString());
                })
            }, (speed * i))
        })(i);
    }
}
</code>```

the CSS for each class:

```<code>@keyframes flash {
    0% {
        background: #333;
    }

    50% {
        background: orange
    }

    100% {
        background: #333;
    }
}

.flashing1000 {
    animation: flash 975ms;
}

.flashing750 {
    animation: flash 725ms;
}

.flashing500 {
    animation: flash 475ms;
}

.flashing250 {
    animation: flash 225ms;
}
</code>```

A few lazy work arounds, I know, but it works well enough.

Body:
I've got a square grid of n x n smaller square div elements that I want to illuminate in a sequence with a CSS background color animation. I have a function to generate a random array for the sequence. The trouble I'm having is that once a certain square has been illuminated once, if it occurs again within the array it won't illuminate a second time. I believe it's because once the element has been assigned the CSS animation, the animation can't trigger again on that element, and I can't figure a way to make it work. It's for a Responsive Web Apps course I'm taking, and the assessment stipulates that we're only to use vanilla JS, and that all elements must be created in JS and appended to a blank  in our index.html.

Each flash according to the sequence is triggered through a setTimeout function that loops through all elements in the array increasing it's timer by 1s for each loop (the animation length is 1s also).

Defining containers and child divs:

function createGameContainer(n, width, height) {
    var container = document.createElement('div');

    //CSS styling
    container.style.margin = '50px auto'
    container.style.width = width;
    container.style.height = height;
    container.style.display = 'grid';

    // loop generates string to create necessary number of grid columns based on the width of the grid of squares
    var columns = '';
    for (i = 0; i < n; i++) {
        columns += ' calc(' + container.style.width + '/' + n.toString() + ')'
    }
    container.style.gridTemplateColumns = columns;

    container.style.gridRow = 'auto auto';

    // gap variable to reduce column and row gap for larger grid sizes
    // if n is ever set to less than 2, gap is hardcoded to 20 to avoid taking square root of 0 or a negative value
    var gap;
    if (n > 1) {
        gap = 20/Math.sqrt(n-1);
    } else {
        gap = 20;
    }

    container.style.gridColumnGap = gap.toString() + 'px';
    container.style.gridRowGap = gap.toString() + 'px';

    container.setAttribute('id', 'game-container');

    document.body.appendChild(container);
}

/*
function to create individual squares to be appended to parent game container
*/
function createSquare(id) {
    var square = document.createElement('div');

    //CSS styling
    square.style.backgroundColor = '#333';
    //square.style.padding = '20px';
    square.style.borderRadius = '5px';
    square.style.display = 'flex';
    square.style.alignItems = 'center';
    //set class and square id
    square.setAttribute('class', 'square');
    square.setAttribute('id', id);

    return square;
}
/*
function to create game container and and squares and append squares to parent container
parameter n denotes dimensions of game grid - n x n grid
*/

function createGameWindow(n, width, height) {
    window.dimension = n;
    createGameContainer(n, width, height);

    /*
    loop creates n**2 number of squares to fill game container and assigns an id to each square from 0 at the top left square to (n**2)-1 at the bottom right square
    */
    for (i = 0; i < n**2; i++) {
        var x = createSquare(i);
        document.getElementById('game-container').appendChild(x);
    }
}

The CSS animation:

@keyframes flash {
    0% {
        background: #333;
    }

    50% {
        background: orange
    }

    100% {
        background: #333;
    }
}

.flashing {
    animation: flash 1s;
}

The code to generate the array:

function generateSequence(sequenceLength) {
    var sequence = [];
    for (i = 0; i < sequenceLength; i++) {
        var random = Math.floor(Math.random() * (dimension**2));
        // the following loop ensures each element in the sequence is different than the previous element
        while (sequence[i-1] == random) {
            random = Math.floor(Math.random() * (dimension**2));
        }
        sequence[i] = random;
    };

    return sequence;
}

Code to apply animation to square:

function flash(index, delay) {
    setTimeout( function() {
        flashingSquare = document.getElementById(index);
        flashingSquare.style.animation = 'flashOne 1s';
        flashingSquare.addEventListener('animationend', function() {
            flashingSquare.style.animation = '';
    }, delay);
}

I've also tried removing and adding a class again to try and reset the animation:

function flash(index, delay) {
    setTimeout( function() {
        flashingSquare = document.getElementById(index);
        flashingSquare.classList.remove('flashing');
        flashingSquare.classList.add('flashing');
    }, delay);
}

And the function to generate and display the sequence:

function displaySequence(sequenceLength) {
    var sequence = generateSequence(sequenceLength);

    i = 0;
    while (i < sequence.length) {
        index = sequence[i].toString();
        flash(index, i*1000);

        i++;
    }
}

Despite many different attempts and a bunch of research I can't figure a way to get the animations to trigger multiple times on the same element.

Body:
After some research, I figured out a work around. I rewrote the function so that the setTimeout was nested within a for loop, and the setTimeout nested within an immediately invoked function expression (which I still don't fully understand, but hey, if it works). The new function looks like this:

/*
function to display game sequence
length can be any integer greater than 1
speed is time between flashes in ms and can presently be set to 1000, 750, 500 and 250.
animation length for each speed is set by a corresponding speed class
in CSS main - .flashing1000 .flashing750 .flashing500 and .flashing250
*/
function displaySequence(length, speed) {
    var sequence = generateSequence(length);
    console.log(sequence);

    for (i = 0; i < sequence.length; i++) {
        console.log(sequence[i]);
        //       immediately invoked function expression
        (function(i) {
            setTimeout( function () {
                var sq = document.getElementById(sequence[i]);
                sq.classList.add('flashing' + speed.toString());
                sq.addEventListener('animationend', function() {
                    sq.classList.remove('flashing' + speed.toString());
                })
            }, (speed * i))
        })(i);
    }
}

the CSS for each class:

@keyframes flash {
    0% {
        background: #333;
    }

    50% {
        background: orange
    }

    100% {
        background: #333;
    }
}

.flashing1000 {
    animation: flash 975ms;
}

.flashing750 {
    animation: flash 725ms;
}

.flashing500 {
    animation: flash 475ms;
}

.flashing250 {
    animation: flash 225ms;
}

A few lazy work arounds, I know, but it works well enough.


问:
What are the ways to show static content on new page in GWT application?
I have a GWT application in which I want to show some static content in new tab.

```<code>private native void openResultWindow(String contents) /*-{
    var printWindow = window.open("", "PrintWin", "scrollbars=yes", false);
    printWindow.document.open("text/html","replace");
    if (printWindow && printWindow.top) {
        printWindow.document.write(contents);

    } else {
        alert("The print feature works by opening a popup window, but our popup window was blocked by your browser.  If you can disable the blocker temporarily, you'll be able to print here.  Sorry!");
    }
}-*/;

</code>```

Right now I am using the above code to show the static content as simple html page styled with CSS. The contents variable passed to the function contains the HTML string. But I need richer UI. Are there any other UI options which can be integrated with GWT?

Thanks.

答: If you want to render something really complex and want to integrate other UIs then what you should open the window with a URL instead of passing the content directly, the URL should point to a server where the static/dynamic content should be served, this could be any html page with what ever css and styles desired. or could be a servlet, or event another GWT application.</p>

Body:
I have a GWT application in which I want to show some static content in new tab.

private native void openResultWindow(String contents) /*-{
    var printWindow = window.open("", "PrintWin", "scrollbars=yes", false);
    printWindow.document.open("text/html","replace");
    if (printWindow && printWindow.top) {
        printWindow.document.write(contents);

    } else {
        alert("The print feature works by opening a popup window, but our popup window was blocked by your browser.  If you can disable the blocker temporarily, you'll be able to print here.  Sorry!");
    }
}-*/;

Right now I am using the above code to show the static content as simple html page styled with CSS. The contents variable passed to the function contains the HTML string. But I need richer UI. Are there any other UI options which can be integrated with GWT?

Thanks.


问:
Convert array of Strings to Array list
I have a String array with name and id, I need to convert that String array to List of objects.

This is my code:

```<code>private List<ObjectAttribute> getDtls(String newVal) {
    ObjectAttribute object = new ObjectAttribute();
    List<ObjectAttribute> objLst = new ArrayList<ObjectAttribute>();
    String[] newImageVal = [step0005.jpg, 172B6846-0073-4E5B-B10A-DDD928994EA6, step0003.jpg, FBC8D143-2CD7-47E6-B323-31A0928A9338]
    for (int i = 0; i <= newImageVal.length - 1; i++) {
        object.setImageName(newImageVal[i]);
        object.setImageId(newImageVal[++i]);
        objLst.add(object);
    }
    return objLst;
}
</code>```

but there is a problem that it always returns only the last value in objList. Can anyone correct this code.

答:
move

```<code>ObjectAttribute object = new ObjectAttribute();
</code>```

inside the for loop:

```<code>for (int i = 0; i <= newImageVal.length - 1; i++) {
    ObjectAttribute object = new ObjectAttribute();
    object.setImageName(newImageVal[i]);
    object.setImageId(newImageVal[++i]);
    objLst.add(object);
}
</code>```

Title: Convert array of Strings to Array list

Body:
I have a String array with name and id, I need to convert that String array to List of objects.

This is my code:

private List<ObjectAttribute> getDtls(String newVal) {
    ObjectAttribute object = new ObjectAttribute();
    List<ObjectAttribute> objLst = new ArrayList<ObjectAttribute>();
    String[] newImageVal = [step0005.jpg, 172B6846-0073-4E5B-B10A-DDD928994EA6, step0003.jpg, FBC8D143-2CD7-47E6-B323-31A0928A9338]
    for (int i = 0; i <= newImageVal.length - 1; i++) {
        object.setImageName(newImageVal[i]);
        object.setImageId(newImageVal[++i]);
        objLst.add(object);
    }
    return objLst;
}

but there is a problem that it always returns only the last value in objList. Can anyone correct this code.

Body:
move

ObjectAttribute object = new ObjectAttribute();

inside the for loop:

for (int i = 0; i <= newImageVal.length - 1; i++) {
    ObjectAttribute object = new ObjectAttribute();
    object.setImageName(newImageVal[i]);
    object.setImageId(newImageVal[++i]);
    objLst.add(object);
}


问:
How to fix this code? It writes to file the first argument, why not the second?
I am working on this code to automate "copy-paste" by reading from an access table and write to excel sheet.
Different values from access table, needs to be written in a particular cells on excel sheet.
My problem is that the code works by reading and writing the first value, but not the second++ values.

The first value is correctly written on E15 in Excel, but the second value which is supposed to be written on cell E16 is not written, Why?

```<code>Sub HentData()

Dim cn As Object, rs As Object
Dim intColIndex As Integer
Dim DBFullName As String
Dim TargetRange As Range
Dim Sum As Double

DBFullName = "C:\saga_effekt_Nidaros_2017_tiltak.mdb"

Application.ScreenUpdating = False

Set TargetRange = Sheets("1.3 Persontransportmodell").Range("A1")

Set cn = CreateObject("ADODB.Connection")

cn.Open "DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\saga_effekt_Nidaros_2017_tiltak.mdb;"

Set rs = CreateObject("ADODB.Recordset")

rs.Open "SELECT [VERDI] FROM [saga_trafikantnytte] WHERE [REISEMIDDE] = 'tog' AND [VARIABEL] = 'sum'", cn, , , adCmdText

For intColIndex = 0 To rs.Fields.Count - 1
    'TargetRange.Offset(1, intColIndex).Value = rs.Fields(intColIndex).Name
    Next

TargetRange.Offset(14, 4).CopyFromRecordset rs

 Application.ScreenUpdating = True

    On Error Resume Next
    rs.Close
    Set rs = Nothing
    cn.Close
    Set cn = Nothing
    On Error GoTo 0
    Exit Sub

rs.Open "SELECT [VERDI] FROM [saga_trafikantnytte] WHERE [REISEMIDDE] = 'tog' AND [VARIABEL] = 'referansetrafikk'", cn, , , adCmdText

For intColIndex = 0 To rs.Fields.Count - 1
    'TargetRange.Offset(1, intColIndex).Value = rs.Fields(intColIndex).Name
    Next

TargetRange.Offset(15, 4).CopyFromRecordset rs

 Application.ScreenUpdating = True

    On Error Resume Next
    rs.Close
    Set rs = Nothing
    cn.Close
    Set cn = Nothing
    On Error GoTo 0
    Exit Sub

End Sub
</code>```

I dont get any error messages, the code runs, but the output is not complete.

答:
Here is an edit to your original code that should work. There was no need to call the first Exit Sub. The second was also unnecessary since you did not have any error-handling code.

Also, you do not need to close the connection or discard rs until the end.

```<code>Sub HentData()

Dim cn As Object, rs As Object
Dim intColIndex As Integer
Dim DBFullName As String
Dim TargetRange As Range
Dim Sum As Double

DBFullName = "C:\saga_effekt_Nidaros_2017_tiltak.mdb"
Application.ScreenUpdating = False
Set TargetRange = Sheets("1.3 Persontransportmodell").Range("A1")

Set cn = CreateObject("ADODB.Connection")
cn.Open "DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\saga_effekt_Nidaros_2017_tiltak.mdb;"

Set rs = CreateObject("ADODB.Recordset")
rs.Open "SELECT [VERDI] FROM [saga_trafikantnytte] WHERE [REISEMIDDE] = 'tog' AND [VARIABEL] = 'sum'", cn, , , adCmdText

For intColIndex = 0 To rs.Fields.Count - 1
    'TargetRange.Offset(1, intColIndex).Value = rs.Fields(intColIndex).Name
Next
TargetRange.Offset(14, 4).CopyFromRecordset rs
Application.ScreenUpdating = True

On Error Resume Next
rs.Close
On Error GoTo 0

rs.Open "SELECT [VERDI] FROM [saga_trafikantnytte] WHERE [REISEMIDDE] = 'tog' AND [VARIABEL] = 'referansetrafikk'", cn, , , adCmdText

For intColIndex = 0 To rs.Fields.Count - 1
    'TargetRange.Offset(1, intColIndex).Value = rs.Fields(intColIndex).Name
Next
TargetRange.Offset(15, 4).CopyFromRecordset rs
Application.ScreenUpdating = True

On Error Resume Next
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
On Error GoTo 0

End Sub
</code>```

Body:
I am working on this code to automate "copy-paste" by reading from an access table and write to excel sheet.
Different values from access table, needs to be written in a particular cells on excel sheet.
My problem is that the code works by reading and writing the first value, but not the second++ values.

The first value is correctly written on E15 in Excel, but the second value which is supposed to be written on cell E16 is not written, Why?

Sub HentData()

Dim cn As Object, rs As Object
Dim intColIndex As Integer
Dim DBFullName As String
Dim TargetRange As Range
Dim Sum As Double

DBFullName = "C:\saga_effekt_Nidaros_2017_tiltak.mdb"

Application.ScreenUpdating = False

Set TargetRange = Sheets("1.3 Persontransportmodell").Range("A1")

Set cn = CreateObject("ADODB.Connection")

cn.Open "DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\saga_effekt_Nidaros_2017_tiltak.mdb;"

Set rs = CreateObject("ADODB.Recordset")

rs.Open "SELECT [VERDI] FROM [saga_trafikantnytte] WHERE [REISEMIDDE] = 'tog' AND [VARIABEL] = 'sum'", cn, , , adCmdText

For intColIndex = 0 To rs.Fields.Count - 1
    'TargetRange.Offset(1, intColIndex).Value = rs.Fields(intColIndex).Name
    Next

TargetRange.Offset(14, 4).CopyFromRecordset rs

 Application.ScreenUpdating = True

    On Error Resume Next
    rs.Close
    Set rs = Nothing
    cn.Close
    Set cn = Nothing
    On Error GoTo 0
    Exit Sub

rs.Open "SELECT [VERDI] FROM [saga_trafikantnytte] WHERE [REISEMIDDE] = 'tog' AND [VARIABEL] = 'referansetrafikk'", cn, , , adCmdText

For intColIndex = 0 To rs.Fields.Count - 1
    'TargetRange.Offset(1, intColIndex).Value = rs.Fields(intColIndex).Name
    Next

TargetRange.Offset(15, 4).CopyFromRecordset rs

 Application.ScreenUpdating = True

    On Error Resume Next
    rs.Close
    Set rs = Nothing
    cn.Close
    Set cn = Nothing
    On Error GoTo 0
    Exit Sub

End Sub

I dont get any error messages, the code runs, but the output is not complete.

Body:
Here is an edit to your original code that should work. There was no need to call the first Exit Sub. The second was also unnecessary since you did not have any error-handling code.

Also, you do not need to close the connection or discard rs until the end.

Sub HentData()

Dim cn As Object, rs As Object
Dim intColIndex As Integer
Dim DBFullName As String
Dim TargetRange As Range
Dim Sum As Double

DBFullName = "C:\saga_effekt_Nidaros_2017_tiltak.mdb"
Application.ScreenUpdating = False
Set TargetRange = Sheets("1.3 Persontransportmodell").Range("A1")

Set cn = CreateObject("ADODB.Connection")
cn.Open "DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\saga_effekt_Nidaros_2017_tiltak.mdb;"

Set rs = CreateObject("ADODB.Recordset")
rs.Open "SELECT [VERDI] FROM [saga_trafikantnytte] WHERE [REISEMIDDE] = 'tog' AND [VARIABEL] = 'sum'", cn, , , adCmdText

For intColIndex = 0 To rs.Fields.Count - 1
    'TargetRange.Offset(1, intColIndex).Value = rs.Fields(intColIndex).Name
Next
TargetRange.Offset(14, 4).CopyFromRecordset rs
Application.ScreenUpdating = True

On Error Resume Next
rs.Close
On Error GoTo 0

rs.Open "SELECT [VERDI] FROM [saga_trafikantnytte] WHERE [REISEMIDDE] = 'tog' AND [VARIABEL] = 'referansetrafikk'", cn, , , adCmdText

For intColIndex = 0 To rs.Fields.Count - 1
    'TargetRange.Offset(1, intColIndex).Value = rs.Fields(intColIndex).Name
Next
TargetRange.Offset(15, 4).CopyFromRecordset rs
Application.ScreenUpdating = True

On Error Resume Next
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
On Error GoTo 0

End Sub


答:
You need to tell moment what format your date string is in:

console.log(moment("190528", "YYMMDD"))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/moment@2.24.0/moment.js"></script></code>```

Title: JS formatting date ymd to yyyy-mm-dd

Body:
You need to tell moment what format your date string is in:

console.log(moment("190528", "YYMMDD"))

<script src="https://unpkg.com/moment@2.24.0/moment.js"></script>


问:
Google App Engine Datastore multiline entries not displayed as multiline in HTML
Using the Google App Store guestbook demo as an example, when entering a entry over multiple lines and storing it, when read back and displayed it appears on one single line.

How can we make it appear excactly as it was originally entered, over multiple lines?

The databasemodel is like this:

```<code>class Greeting(db.Model):
    author = db.UserProperty()
    content = db.StringProperty(multiline=True)
    date = db.DateTimeProperty(auto_now_add=True)
</code>```

And the submission form is like this:

```<code>self.response.out.write("""
          <form action="/sign" method="post">
            <div><textarea name="content" rows="3" cols="60"></textarea></div>
            <div><input type="submit" value="Sign Guestbook"></div>
          </form>
        </body>
      </html>""")
</code>```

答:
Html ignores EOL special characters like \r\n or \n.

Here are some options:

Replace the special characters with the proper html
 tag

Wrap the multiline text inside a ``` tag

In case you are using webapp templating, try with {{greeting.content|linebreaks}} as suggested by @wooble

Set white-space:pre in your CSS as suggested by @Nick   (example here)

Body:
Using the Google App Store guestbook demo as an example, when entering a entry over multiple lines and storing it, when read back and displayed it appears on one single line.

How can we make it appear excactly as it was originally entered, over multiple lines?

The databasemodel is like this:

class Greeting(db.Model):
    author = db.UserProperty()
    content = db.StringProperty(multiline=True)
    date = db.DateTimeProperty(auto_now_add=True)

And the submission form is like this:

self.response.out.write("""
          <form action="/sign" method="post">

<textarea name="content" rows="3" cols="60"></textarea>

<input type="submit" value="Sign Guestbook">

          </form>

      """)

Body:
Html ignores EOL special characters like \r\n or \n.

Here are some options:

Replace the special characters with the proper html <br> tag

Wrap the multiline text inside a <pre> tag

In case you are using webapp templating, try with {{greeting.content|linebreaks}} as suggested by @wooble

Set white-space:pre in your CSS as suggested by @Nick   (example here)


问:
instance variable in block when using define_method
I'm trying to do a DSL, in which the user can pass a block and expect an instance variable @arg to be defined. This is a full example with a unit test failing:

# Implementation
class Filter
  def initialize
    @arg = 'foo'
  end

  def self.filters &block
    define_method :filter do |els|
      els.select &block
    end
  end
end

# Usage
class Foo < Filter
  filters {|el| el == @arg}
end

# Expected behavior
describe 'filters created with the DSL' do
  subject { Foo.new }
  it 'can use @arg in the filters block' do
    els = %w[notthearg  either  foo  other]
    expect(subject.filter els).to be_eql(['foo'])
  end
end
```

Using pry or putting puts statements inside the block, I can see that @arg is nil. But Foo.new.instance_variable_get :@arg correctly outputs foo, so it must be related to some scoping rules.

What do I need to change in the implementation to make the test pass and the DSL to work?

答:
instance_exec to rescue!

```<code>class Filter
  def initialize
    @arg = 'foo'
  end

  def self.filters &block
    define_method :filter do |els|
      els.select { |e| self.instance_exec(e, &block) }
    end
  end
end

class Foo < Filter
  filters {|el| el == @arg }
end

Foo.new.filter(%w[notthearg  either  foo  other])
# => ["foo"]
</code>```

Caution: Make sure this is very well documented, since any shenanigans involving instance_exec or its cousins are breaking programmer expectations left and right - by design, you're destroying the concept of "scope". I'm pretty sure OP knows this, but it is worth putting down on the proverbial paper.

Also, consider using accessors rather than plain instance variables - accessors are checked, and variables are not. i.e. { |el| el == urg } will result in an error, but { |el| el == @urg } will silently fail (and filter for nil).

Body:
I'm trying to do a DSL, in which the user can pass a block and expect an instance variable @arg to be defined. This is a full example with a unit test failing:

# Implementation
class Filter
  def initialize
    @arg = 'foo'
  end

  def self.filters &block
    define_method :filter do |els|
      els.select &block
    end
  end
end

# Usage
class Foo < Filter
  filters {|el| el == @arg}
end

# Expected behavior
describe 'filters created with the DSL' do
  subject { Foo.new }
  it 'can use @arg in the filters block' do
    els = %w[notthearg  either  foo  other]
    expect(subject.filter els).to be_eql(['foo'])
  end
end

Using pry or putting puts statements inside the block, I can see that @arg is nil. But Foo.new.instance_variable_get :@arg correctly outputs foo, so it must be related to some scoping rules.

What do I need to change in the implementation to make the test pass and the DSL to work?

Body:
instance_exec to rescue!

class Filter
  def initialize
    @arg = 'foo'
  end

  def self.filters &block
    define_method :filter do |els|
      els.select { |e| self.instance_exec(e, &block) }
    end
  end
end

class Foo < Filter
  filters {|el| el == @arg }
end

Foo.new.filter(%w[notthearg  either  foo  other])
# => ["foo"]

Caution: Make sure this is very well documented, since any shenanigans involving instance_exec or its cousins are breaking programmer expectations left and right - by design, you're destroying the concept of "scope". I'm pretty sure OP knows this, but it is worth putting down on the proverbial paper.

Also, consider using accessors rather than plain instance variables - accessors are checked, and variables are not. i.e. { |el| el == urg } will result in an error, but { |el| el == @urg } will silently fail (and filter for nil).


问:
Allocating an array of strings
I'm trying to create an array to store multiple strings in. The maximum size of the string is 100.

This is what my struct looks like:

```<code>typedef struct
{
  int size;

  int capacity;

  char** elements;

} array_strings;
</code>```

I allocate space for an empty array in the following function:

```<code>array_strings *array_strings_new()
{
    array_strings *vec;

    vec = (array_strings *)malloc(sizeof(array_strings));
    if (vec == NULL)
        return NULL;

    vec->size = 0;
    vec->capacity = 0;
    vec->elements = NULL;

    return vec;
}
</code>```

And then I try to insert elements in the end of the vector with the following function:

```<code>int array_strings_insert(array_strings *vec, char *string, int pos)
{
    int i;

    if (vec == NULL || pos < -1 || pos > vec->size)
        return -1;

    /* increases capacity if needed */
    if (vec->size == vec->capacity)
    {
        if (vec->capacity == 0)
            vec->capacity = 1;
        else
            vec->capacity *= 2;

vec->elements = (char **)realloc(vec->elements, vec->capacity *sizeof(char *));
        for (int i = 0; i < vec->capacity; i++)
        {
            vec->elements[i] = realloc(vec->elements[i], 100*sizeof(char));
        }
        if (vec->elementos == NULL)
            return -1;
    }

    /* if pos=-1 inserts at the end of the array */
    if (pos == -1)
        pos = vec->size;

    /* Copy elements from pos to pos+1 until the end of the array */
    for (i = vec->size - 1; i >= pos; i--)
    {
        strcpy(vec->elements[i + 1], vec->elements[i]);
    }

    /* copy string */
    strcpy(vec->elements[pos], string);

    vec->size++;

    return pos;
}
</code>```

When I try to insert a a string I get "realloc(): invalid pointer
Aborted (core dumped)".

Can someone tell me what Im doing wrong?

Thank you,

I tried doing this:

```<code>vec->elements = (char **)realloc(vec->elements, vec->capacity *sizeof(char *));
        for (int i = 0; i < vec->capacity; i++)
        {
            vec->elements[i] = NULL;
            vec->elements[i] = realloc(vec->elements[i], 100*sizeof(char));
        }
        if (vec->elementos == NULL)
            return -1;
    }
</code>```

And I no longer get "realloc(): invalid pointer Aborted (core dumped)". However the first elements of the array are empty for some reason.

答:
The realloc code you wrote will destroy the strings stored previously. e.g. in case of data size increase from 2 to 4, the first 2 strings will be lost.

You can modify the realloc portion as follows.

```<code>int prevcapacity;
if (vec->size == vec->capacity)
{
    prevcapacity = vec->capacity;
    if (vec->capacity == 0)
        vec->capacity = 1;
    else
        vec->capacity *= 2;

    vec->elements = (char **)realloc(vec->elements, vec->capacity *sizeof(char *));
    for (int i = prevcapacity; i < vec->capacity; i++)
    {
        vec->elements[i] = malloc(vec->elements[i], 100*sizeof(char));
    }
}
</code>```

In this case, you can use malloc on the extra strings allocated. The previous strings will be preserved.

Title: Allocating an array of strings

Body:
I'm trying to create an array to store multiple strings in. The maximum size of the string is 100.

This is what my struct looks like:

typedef struct
{
  int size;

  int capacity;

  char** elements;

} array_strings;

I allocate space for an empty array in the following function:

array_strings *array_strings_new()
{
    array_strings *vec;

    vec = (array_strings *)malloc(sizeof(array_strings));
    if (vec == NULL)
        return NULL;

    vec->size = 0;
    vec->capacity = 0;
    vec->elements = NULL;

    return vec;
}

And then I try to insert elements in the end of the vector with the following function:

int array_strings_insert(array_strings *vec, char *string, int pos)
{
    int i;

    if (vec == NULL || pos < -1 || pos > vec->size)
        return -1;

    /* increases capacity if needed */
    if (vec->size == vec->capacity)
    {
        if (vec->capacity == 0)
            vec->capacity = 1;
        else
            vec->capacity *= 2;

vec->elements = (char **)realloc(vec->elements, vec->capacity *sizeof(char *));
        for (int i = 0; i < vec->capacity; i++)
        {
            vec->elements[i] = realloc(vec->elements[i], 100*sizeof(char));
        }
        if (vec->elementos == NULL)
            return -1;
    }

    /* if pos=-1 inserts at the end of the array */
    if (pos == -1)
        pos = vec->size;

    /* Copy elements from pos to pos+1 until the end of the array */
    for (i = vec->size - 1; i >= pos; i--)
    {
        strcpy(vec->elements[i + 1], vec->elements[i]);
    }

    /* copy string */
    strcpy(vec->elements[pos], string);

    vec->size++;

    return pos;
}

When I try to insert a a string I get "realloc(): invalid pointer
Aborted (core dumped)".

Can someone tell me what Im doing wrong?

Thank you,

I tried doing this:

vec->elements = (char **)realloc(vec->elements, vec->capacity *sizeof(char *));
        for (int i = 0; i < vec->capacity; i++)
        {
            vec->elements[i] = NULL;
            vec->elements[i] = realloc(vec->elements[i], 100*sizeof(char));
        }
        if (vec->elementos == NULL)
            return -1;
    }

And I no longer get "realloc(): invalid pointer Aborted (core dumped)". However the first elements of the array are empty for some reason.

Body:
The realloc code you wrote will destroy the strings stored previously. e.g. in case of data size increase from 2 to 4, the first 2 strings will be lost.

You can modify the realloc portion as follows.

int prevcapacity;
if (vec->size == vec->capacity)
{
    prevcapacity = vec->capacity;
    if (vec->capacity == 0)
        vec->capacity = 1;
    else
        vec->capacity *= 2;

    vec->elements = (char **)realloc(vec->elements, vec->capacity *sizeof(char *));
    for (int i = prevcapacity; i < vec->capacity; i++)
    {
        vec->elements[i] = malloc(vec->elements[i], 100*sizeof(char));
    }
}

In this case, you can use malloc on the extra strings allocated. The previous strings will be preserved.


问:
Passing argument in LEFT JOIN
I am currently trying to get data from 2 tables with a LEFT JOIN having an unknow value.

I tried using LEFT JOIN but it didn't work.

Here is my code example :

```<code>SELECT
    cc.shid,
    cc.user,
    ts.type,
    sum(cc.qty1) + sum(cc.qty2) as qty_tot,
    COUNT(cc.id) as nb
FROM
    content_c cc
LEFT JOIN
    (SELECT
        s.shid,
        s.type
    FROM
        tab_s s
    LIMIT 1
    ) as ts ON ts.shid = cc.shid
WHERE
    cc.time_i like '2019-01%'
GROUP BY
    cc.user,
    ts.type
</code>```

With that query it will never work : ts will contain the first occurence of tab_s regardless of cc.shid. I wonder if there is a way to make this :

```<code>LEFT JOIN
    (SELECT
        s.shid,
        s.type
    FROM
        tab_s s
    WHERE
        s.shid = cc.shid
    LIMIT 1
    ) as ts ON ts.shid = cc.shid
</code>```

Any idea ? Is there a pointer notion in SQL or something like ? Like I can use &cc.shid, or @cc.shid ?

Note that doing the following :

```<code>LEFT JOIN tab_s ts ON ts.shid = cc.shid
</code>```

Will make my request to take more than 1 minute to display results. And I cannot set an index in tab_s.shid aswell as cc.shid as its have multiple occurences.

Please keep in mind that content_c can have multiple occurence of cc.shid, that why I need to take only the first result (LIMIT 1). It's important.

答:
Use a correlated subquery:

```<code>SELECT cc.shid, cc.user, cc.type,
       SUM(cc.qty1) + SUM(cc.qty2) as qty_tot,
       COUNT(cc.id) as nb
FROM (SELECT cc.*,
             (SELECT s.type
              FROM tab_s s
              WHERE ts.shid = cc.shid
              LIMIT 1
             ) as type
      FROM content_c cc
     ) cc
WHERE cc.time_i >= '2019-01-01' AND
      cc.time_i < '2019-02-01'
GROUP BY cc.shid, cc.user, cc.type;
</code>```

Notes:

The use of LIMIT with no ORDER BY is suspicious.  Why would there be duplicates in the underlying table?

Your date comparisons are bad.  Use date/time functions when working with date/time values.  Don't use string functions.

The GROUP BY should include all non-aggregated columns in the SELECT.

Title: Passing argument in LEFT JOIN

Body:
I am currently trying to get data from 2 tables with a LEFT JOIN having an unknow value.

I tried using LEFT JOIN but it didn't work.

Here is my code example :

SELECT
    cc.shid,
    cc.user,
    ts.type,
    sum(cc.qty1) + sum(cc.qty2) as qty_tot,
    COUNT(cc.id) as nb
FROM
    content_c cc
LEFT JOIN
    (SELECT
        s.shid,
        s.type
    FROM
        tab_s s
    LIMIT 1
    ) as ts ON ts.shid = cc.shid
WHERE
    cc.time_i like '2019-01%'
GROUP BY
    cc.user,
    ts.type

With that query it will never work : ts will contain the first occurence of tab_s regardless of cc.shid. I wonder if there is a way to make this :

LEFT JOIN
    (SELECT
        s.shid,
        s.type
    FROM
        tab_s s
    WHERE
        s.shid = cc.shid
    LIMIT 1
    ) as ts ON ts.shid = cc.shid

Any idea ? Is there a pointer notion in SQL or something like ? Like I can use &cc.shid, or @cc.shid ?

Note that doing the following :

LEFT JOIN tab_s ts ON ts.shid = cc.shid

Will make my request to take more than 1 minute to display results. And I cannot set an index in tab_s.shid aswell as cc.shid as its have multiple occurences.

Please keep in mind that content_c can have multiple occurence of cc.shid, that why I need to take only the first result (LIMIT 1). It's important.

Body:
Use a correlated subquery:

SELECT cc.shid, cc.user, cc.type,
       SUM(cc.qty1) + SUM(cc.qty2) as qty_tot,
       COUNT(cc.id) as nb
FROM (SELECT cc.*,
             (SELECT s.type
              FROM tab_s s
              WHERE ts.shid = cc.shid
              LIMIT 1
             ) as type
      FROM content_c cc
     ) cc
WHERE cc.time_i >= '2019-01-01' AND
      cc.time_i < '2019-02-01'
GROUP BY cc.shid, cc.user, cc.type;

Notes:

The use of LIMIT with no ORDER BY is suspicious.  Why would there be duplicates in the underlying table?

Your date comparisons are bad.  Use date/time functions when working with date/time values.  Don't use string functions.

The GROUP BY should include all non-aggregated columns in the SELECT.


问:
vscode generate large configuration files
I have noticed that the .vscode files have 1.4 GB in each folder that I open a code. Why these file have become so large? Is there any way to stop making these large files? I need to scp code folder between remote machine and I need to remove these files frequently.

I use version: 1.32.3 on Limux Mint 18.3. and the following extensions:

Python, C++, Prettier, Peacoke, GitLense.

```<code>.vscode/
└── ipch
    ├── 21fd2401553c84f8
    │   ├── functions.ipch
    │   └── mmap_address.bin
    ├── 944dcfa22b114a8c
    │   ├── main.ipch
    │   └── mmap_address.bin
    └── 9f0098f535f71055
        ├── kuramoto.ipch
        └── mmap_address.bin

4 directories, 6 files
</code>```

Thank you for any guide.

答: The files in the ipch folder are IntelliSense cache files generated by the C/C++ extension. The maintainer has described how you can the customize cache path and size limit here.

Body:
I have noticed that the .vscode files have 1.4 GB in each folder that I open a code. Why these file have become so large? Is there any way to stop making these large files? I need to scp code folder between remote machine and I need to remove these files frequently.

I use version: 1.32.3 on Limux Mint 18.3. and the following extensions:

Python, C++, Prettier, Peacoke, GitLense.

.vscode/
└── ipch
    ├── 21fd2401553c84f8
    │   ├── functions.ipch
    │   └── mmap_address.bin
    ├── 944dcfa22b114a8c
    │   ├── main.ipch
    │   └── mmap_address.bin
    └── 9f0098f535f71055
        ├── kuramoto.ipch
        └── mmap_address.bin

4 directories, 6 files

Thank you for any guide.


问:
Running pytest test giving error for pluggy, is there something wrong with setup?
I am trying to run the pytest test.py file which contains tests for the project I am working on. Earlier the test was running fine but suddenly they stopped running with an error for pluggy package.

I have tried finding the issue but could not resolve, is there something related to virtualenv setup or pluggy package? Tried removing that but could not help?

This is the test I am running :

```<code>import subprocess
import time
from subprocess import Popen, PIPE, STDOUT

class Test:

    def test_yank_case(self):
    subprocess.call('echo Yanking case testing started', shell=True)
    assert subprocess.call('echo | yank 02041523', shell=True) == 0
</code>```

Running as below with error:

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

Expected results should be pytest running with all test green.

But getting below error:

```<code>[apaliwal@dhcp223-39 supportshell]$ pytest test/test.py
=============================================================================================== test session starts ===============================================================================================
platform linux -- Python 3.7.2, pytest-4.2.1, py-1.7.0, pluggy-0.8.1
rootdir: /home/apaliwal/Support_shell_test_repo/supportshell, inifile:
plugins: dependency-0.3.2, cov-2.6.1, bdd-3.1.0
collected 8 items

test/test.py
INTERNALERROR> Traceback (most recent call last):
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/_pytest/main.py", line 203, in wrap_session
INTERNALERROR>     session.exitstatus = doit(config, session) or 0
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/_pytest/main.py", line 243, in _main
INTERNALERROR>     config.hook.pytest_runtestloop(session=session)
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/pluggy/hooks.py", line 284, in __call__
INTERNALERROR>     return self._hookexec(self, self.get_hookimpls(), kwargs)
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/pluggy/manager.py", line 68, in _hookexec
INTERNALERROR>     return self._inner_hookexec(hook, methods, kwargs)
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/pluggy/manager.py", line 62, in <lambda>
INTERNALERROR>     firstresult=hook.spec.opts.get("firstresult") if hook.spec else False,
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/pluggy/callers.py", line 208, in _multicall
INTERNALERROR>     return outcome.get_result()
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/pluggy/callers.py", line 80, in get_result
INTERNALERROR>     raise ex[1].with_traceback(ex[2])
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/pluggy/callers.py", line 187, in _multicall
INTERNALERROR>     res = hook_impl.function(*args)
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/_pytest/main.py", line 264, in pytest_runtestloop
INTERNALERROR>     item.config.hook.pytest_runtest_protocol(item=item, nextitem=nextitem)
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/pluggy/hooks.py", line 284, in __call__
INTERNALERROR>     return self._hookexec(self, self.get_hookimpls(), kwargs)
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/pluggy/manager.py", line 68, in _hookexec
INTERNALERROR>     return self._inner_hookexec(hook, methods, kwargs)
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/pluggy/manager.py", line 62, in <lambda>
INTERNALERROR>     firstresult=hook.spec.opts.get("firstresult") if hook.spec else False,
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/pluggy/callers.py", line 208, in _multicall
INTERNALERROR>     return outcome.get_result()
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/pluggy/callers.py", line 80, in get_result
INTERNALERROR>     raise ex[1].with_traceback(ex[2])
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/pluggy/callers.py", line 187, in _multicall
INTERNALERROR>     res = hook_impl.function(*args)
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/_pytest/runner.py", line 78, in pytest_runtest_protocol
INTERNALERROR>     runtestprotocol(item, nextitem=nextitem)
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/_pytest/runner.py", line 87, in runtestprotocol
INTERNALERROR>     rep = call_and_report(item, "setup", log)
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/_pytest/runner.py", line 175, in call_and_report
INTERNALERROR>     report = hook.pytest_runtest_makereport(item=item, call=call)
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/pluggy/hooks.py", line 284, in __call__
INTERNALERROR>     return self._hookexec(self, self.get_hookimpls(), kwargs)
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/pluggy/manager.py", line 68, in _hookexec
INTERNALERROR>     return self._inner_hookexec(hook, methods, kwargs)
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/pluggy/manager.py", line 62, in <lambda>
INTERNALERROR>     firstresult=hook.spec.opts.get("firstresult") if hook.spec else False,
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/pluggy/callers.py", line 203, in _multicall
INTERNALERROR>     gen.send(outcome)
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/pytest_dependency.py", line 136, in pytest_runtest_makereport
INTERNALERROR>     marker = item.get_marker("dependency")
INTERNALERROR> AttributeError: 'Function' object has no attribute 'get_marker'

</code>```

I am really not sure why pluggy is been used in pytest and can I remove it to fix the issue?
Please provide help

答:
As per comment for my question below command can resolve the outdated dependency.</p>

```<code>pip install --upgrade pytest-dependency
</code>```

Body:
I am trying to run the pytest test.py file which contains tests for the project I am working on. Earlier the test was running fine but suddenly they stopped running with an error for pluggy package.

I have tried finding the issue but could not resolve, is there something related to virtualenv setup or pluggy package? Tried removing that but could not help?

This is the test I am running :

import subprocess
import time
from subprocess import Popen, PIPE, STDOUT

class Test:

    def test_yank_case(self):
    subprocess.call('echo Yanking case testing started', shell=True)
    assert subprocess.call('echo | yank 02041523', shell=True) == 0

Running as below with error:

Expected results should be pytest running with all test green.

But getting below error:

[apaliwal@dhcp223-39 supportshell]$ pytest test/test.py
=============================================================================================== test session starts ===============================================================================================
platform linux -- Python 3.7.2, pytest-4.2.1, py-1.7.0, pluggy-0.8.1
rootdir: /home/apaliwal/Support_shell_test_repo/supportshell, inifile:
plugins: dependency-0.3.2, cov-2.6.1, bdd-3.1.0
collected 8 items

test/test.py
INTERNALERROR> Traceback (most recent call last):
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/_pytest/main.py", line 203, in wrap_session
INTERNALERROR>     session.exitstatus = doit(config, session) or 0
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/_pytest/main.py", line 243, in _main
INTERNALERROR>     config.hook.pytest_runtestloop(session=session)
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/pluggy/hooks.py", line 284, in __call__
INTERNALERROR>     return self._hookexec(self, self.get_hookimpls(), kwargs)
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/pluggy/manager.py", line 68, in _hookexec
INTERNALERROR>     return self._inner_hookexec(hook, methods, kwargs)
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/pluggy/manager.py", line 62, in <lambda>
INTERNALERROR>     firstresult=hook.spec.opts.get("firstresult") if hook.spec else False,
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/pluggy/callers.py", line 208, in _multicall
INTERNALERROR>     return outcome.get_result()
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/pluggy/callers.py", line 80, in get_result
INTERNALERROR>     raise ex[1].with_traceback(ex[2])
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/pluggy/callers.py", line 187, in _multicall
INTERNALERROR>     res = hook_impl.function(*args)
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/_pytest/main.py", line 264, in pytest_runtestloop
INTERNALERROR>     item.config.hook.pytest_runtest_protocol(item=item, nextitem=nextitem)
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/pluggy/hooks.py", line 284, in __call__
INTERNALERROR>     return self._hookexec(self, self.get_hookimpls(), kwargs)
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/pluggy/manager.py", line 68, in _hookexec
INTERNALERROR>     return self._inner_hookexec(hook, methods, kwargs)
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/pluggy/manager.py", line 62, in <lambda>
INTERNALERROR>     firstresult=hook.spec.opts.get("firstresult") if hook.spec else False,
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/pluggy/callers.py", line 208, in _multicall
INTERNALERROR>     return outcome.get_result()
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/pluggy/callers.py", line 80, in get_result
INTERNALERROR>     raise ex[1].with_traceback(ex[2])
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/pluggy/callers.py", line 187, in _multicall
INTERNALERROR>     res = hook_impl.function(*args)
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/_pytest/runner.py", line 78, in pytest_runtest_protocol
INTERNALERROR>     runtestprotocol(item, nextitem=nextitem)
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/_pytest/runner.py", line 87, in runtestprotocol
INTERNALERROR>     rep = call_and_report(item, "setup", log)
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/_pytest/runner.py", line 175, in call_and_report
INTERNALERROR>     report = hook.pytest_runtest_makereport(item=item, call=call)
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/pluggy/hooks.py", line 284, in __call__
INTERNALERROR>     return self._hookexec(self, self.get_hookimpls(), kwargs)
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/pluggy/manager.py", line 68, in _hookexec
INTERNALERROR>     return self._inner_hookexec(hook, methods, kwargs)
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/pluggy/manager.py", line 62, in <lambda>
INTERNALERROR>     firstresult=hook.spec.opts.get("firstresult") if hook.spec else False,
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/pluggy/callers.py", line 203, in _multicall
INTERNALERROR>     gen.send(outcome)
INTERNALERROR>   File "/usr/local/lib/python3.7/site-packages/pytest_dependency.py", line 136, in pytest_runtest_makereport
INTERNALERROR>     marker = item.get_marker("dependency")
INTERNALERROR> AttributeError: 'Function' object has no attribute 'get_marker'

I am really not sure why pluggy is been used in pytest and can I remove it to fix the issue?
Please provide help

Body:
As per comment for my question below command can resolve the outdated dependency.

pip install --upgrade pytest-dependency


问:
Hashicorp vault: unable to write secret with node-vault
I am writing an application which uses Hashicorp vault to store passwords and certificates. Right now I am using the default username/pass method to authenticate my client app.

When I try to add a secret I am getting { statusCode: 301, body: undefined } when setting the apiVersion = v1 and { statusCode: 404, body: { errors: [] } } when it is set to v2.

Configuration:

```<code>let vaultOptions = {
    apiVersion: 'v2',
    endpoint: '0.0.0.0:8200'
};

const nodeVault = require('node-vault')(vaultOptions);
nodeVault.token = "secret token";

nodeVault.write('/secret/new', {"foo":"bar"}).then(
  function (value: any) {
    console.log(value);
  })
  .catch((err: any)=> {
    console.log(err);
  });
</code>```

As the vault container is initialised by default I am not using the init function.

I would like to know what am I missing here.

答:
The issue got fixed by adding /data to the path and also the request data had to be inside an object {"data": .....}.

```<code>nodeVault.write('/secret/data/new', {"data": {"foo":"bar"}}).then(
  function (value: any) {
    console.log(value);
  })
  .catch((err: any)=> {
    console.log(err);
  });
</code>```

This was because the vault container was running on v2 engine

Body:
I am writing an application which uses Hashicorp vault to store passwords and certificates. Right now I am using the default username/pass method to authenticate my client app.

When I try to add a secret I am getting { statusCode: 301, body: undefined } when setting the apiVersion = v1 and { statusCode: 404, body: { errors: [] } } when it is set to v2.

Configuration:

let vaultOptions = {
    apiVersion: 'v2',
    endpoint: '0.0.0.0:8200'
};

const nodeVault = require('node-vault')(vaultOptions);
nodeVault.token = "secret token";

nodeVault.write('/secret/new', {"foo":"bar"}).then(
  function (value: any) {
    console.log(value);
  })
  .catch((err: any)=> {
    console.log(err);
  });

As the vault container is initialised by default I am not using the init function.

I would like to know what am I missing here.

Body:
The issue got fixed by adding /data to the path and also the request data had to be inside an object {"data": .....}.

nodeVault.write('/secret/data/new', {"data": {"foo":"bar"}}).then(
  function (value: any) {
    console.log(value);
  })
  .catch((err: any)=> {
    console.log(err);
  });

This was because the vault container was running on v2 engine


问:
TypeError: unorderable types: dict() < dict()
I am totally new to python and i got a script that produces this error

```<code>for a in sorted([p for p in PRODUCERS.Get('PartitionName="{}"'.format(partition))
                 if p["SignalName"] not in EXCLUDED_SIGNALS]):
</code>```

```<code>TypeError: unorderable types: dict() < dict()
</code>```

The script was made with python 2.7 and i am using 3.5(32 bit).Is there something that changed?

Here is the function:

```<code>def tests_init(partition, dll, fce_name, limit_skip, limit_show, outputs):

all_inputs = {}
all_outputs = {}

# prepare inputs and outputs
for a in sorted([p for p in PRODUCERS.Get('PartitionName="{}"'.format(partition)) if p["SignalName"] not in EXCLUDED_SIGNALS]):
    all_inputs["{}__{}".format(a["ProducerFunction"],a["SignalName"])] = a["SignalType"]
for a in sorted([c for c in CONSUMERS.Get('PartitionName="{}"'.format(partition)) if c["SignalName"] not in EXCLUDED_SIGNALS]):
    all_outputs["{}__{}".format(a["ConsumerFunction"],a["SignalName"])] = a["SignalType"]

all_outputs["InvalidRdResult"] = "uint32"
all_outputs["InvalidRd4Result"] = "uint32"
all_outputs["InvalidWrResult"] = "uint32"
all_outputs["InvalidWr4Result"] = "uint32"

# init test
order_dict, help_out = test_init(all_inputs, all_outputs, partition, outputs, limit_skip, limit_show)

all_outputs = {o:all_outputs[o] for o in all_outputs if o in help_out}

file_desc =  "Testing Ports initialization and functions"
file_desc += "\n;                    portDclrRd()/portDclrRd4()/portDclrWr()/portDclrWr4()"
file_desc += "\n;                    for invalid signal name input"
file_desc += "\n;                    Initial values for port signals are defined in Input Tables"
file_desc += "\n;                    in related SRDD/DRD sections where the signals are produced."
if(partition=="fcm"):
    file_desc += "\n;                    This file contains {} half of output signals".format({0:"first", 1:"second"}[int(limit_skip/limit_show)])
    file_desc += "\n;                    Files are divided due to line length limitations in CTP tool"
</code>```

答:
An example of sorting list of dicts:

In the example the key is the 'id' field. You need to decide what is the proper field to use.

```<code>lst = [{'name':'jack','id':12},{'name':'sam','id':4},{'name':'ben','id':152}]
print(sorted(lst,key = lambda i: i['id']))
</code>```

output

```<code>[{'name': 'sam', 'id': 4}, {'name': 'jack', 'id': 12}, {'name': 'ben', 'id': 152}]
</code>```

Body:
I am totally new to python and i got a script that produces this error

for a in sorted([p for p in PRODUCERS.Get('PartitionName="{}"'.format(partition))
                 if p["SignalName"] not in EXCLUDED_SIGNALS]):

TypeError: unorderable types: dict() < dict()

The script was made with python 2.7 and i am using 3.5(32 bit).Is there something that changed?

Here is the function:

def tests_init(partition, dll, fce_name, limit_skip, limit_show, outputs):

all_inputs = {}
all_outputs = {}

# prepare inputs and outputs
for a in sorted([p for p in PRODUCERS.Get('PartitionName="{}"'.format(partition)) if p["SignalName"] not in EXCLUDED_SIGNALS]):
    all_inputs["{}__{}".format(a["ProducerFunction"],a["SignalName"])] = a["SignalType"]
for a in sorted([c for c in CONSUMERS.Get('PartitionName="{}"'.format(partition)) if c["SignalName"] not in EXCLUDED_SIGNALS]):
    all_outputs["{}__{}".format(a["ConsumerFunction"],a["SignalName"])] = a["SignalType"]

all_outputs["InvalidRdResult"] = "uint32"
all_outputs["InvalidRd4Result"] = "uint32"
all_outputs["InvalidWrResult"] = "uint32"
all_outputs["InvalidWr4Result"] = "uint32"

# init test
order_dict, help_out = test_init(all_inputs, all_outputs, partition, outputs, limit_skip, limit_show)

all_outputs = {o:all_outputs[o] for o in all_outputs if o in help_out}

file_desc =  "Testing Ports initialization and functions"
file_desc += "\n;                    portDclrRd()/portDclrRd4()/portDclrWr()/portDclrWr4()"
file_desc += "\n;                    for invalid signal name input"
file_desc += "\n;                    Initial values for port signals are defined in Input Tables"
file_desc += "\n;                    in related SRDD/DRD sections where the signals are produced."
if(partition=="fcm"):
    file_desc += "\n;                    This file contains {} half of output signals".format({0:"first", 1:"second"}[int(limit_skip/limit_show)])
    file_desc += "\n;                    Files are divided due to line length limitations in CTP tool"

Body:
An example of sorting list of dicts:

In the example the key is the 'id' field. You need to decide what is the proper field to use.

lst = [{'name':'jack','id':12},{'name':'sam','id':4},{'name':'ben','id':152}]
print(sorted(lst,key = lambda i: i['id']))

output

[{'name': 'sam', 'id': 4}, {'name': 'jack', 'id': 12}, {'name': 'ben', 'id': 152}]


问:
Unable to create call adapter for io.reactivex.Single
I want to conncet to server with retrofit and rxjava.it works when I used call and everything is good.but when try to use rxjava ,its getsinto trouble.
the error text:

Could not locate call adapter for io.reactivex.Single

in the build.gradle I implemented the retrofit adapter.but I dont know whats the problem.
this is my gradle:

```<code>implementation 'com.squareup.picasso:picasso:2.71828'
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
implementation 'io.reactivex.rxjava2:rxjava:2.2.8'
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.squareup.retrofit2:adapter-rxjava:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
implementation "android.arch.persistence.room:runtime:1.1.1"
annotationProcessor "android.arch.persistence.room:compiler:1.1.1"
</code>```

api client code:

```<code>public class ApiClient {
public static final String BASE_URL="http://192.168.1.100/digikala/";
private static Retrofit retrofit=null;
public static Retrofit getClient(){
    if(retrofit==null){
        retrofit=new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(BASE_URL)
                .build();
    }

    return  retrofit;
}
</code>```

api service code:

```<code>public interface ApiService {

   @GET("readamazing.php")
   Single<List<Product>> getSingleProducts();
 }
</code>```

main acitivity code:

```<code>ApiService apiService=ApiClient.getClient().create(ApiService.class);
apiService.getSingleProducts().subscribeOn(Schedulers.newThread())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(new SingleObserver<List<Product>>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onSuccess(List<Product> products) {
            Log.i("LOG", "onSuccess: "+products.toString());
        }

        @Override
        public void onError(Throwable e) {
            Log.i("LOG", "onSuccess: "+e.toString());
        }
    });
</code>```

答:
Use RxJava2CallAdapterFactory instead of RxJavaCallAdapterFactory as RxJava2 is used.

```<code>.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
</code>```

to the Retrofit.Builder().

Body:
I want to conncet to server with retrofit and rxjava.it works when I used call and everything is good.but when try to use rxjava ,its getsinto trouble.
the error text:

Could not locate call adapter for io.reactivex.Single

in the build.gradle I implemented the retrofit adapter.but I dont know whats the problem.
this is my gradle:

implementation 'com.squareup.picasso:picasso:2.71828'
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
implementation 'io.reactivex.rxjava2:rxjava:2.2.8'
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.squareup.retrofit2:adapter-rxjava:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
implementation "android.arch.persistence.room:runtime:1.1.1"
annotationProcessor "android.arch.persistence.room:compiler:1.1.1"

api client code:

public class ApiClient {
public static final String BASE_URL="http://192.168.1.100/digikala/";
private static Retrofit retrofit=null;
public static Retrofit getClient(){
    if(retrofit==null){
        retrofit=new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(BASE_URL)
                .build();
    }

    return  retrofit;
}

api service code:

public interface ApiService {

   @GET("readamazing.php")
   Single<List<Product>> getSingleProducts();
 }

main acitivity code:

ApiService apiService=ApiClient.getClient().create(ApiService.class);
apiService.getSingleProducts().subscribeOn(Schedulers.newThread())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(new SingleObserver<List<Product>>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onSuccess(List<Product> products) {
            Log.i("LOG", "onSuccess: "+products.toString());
        }

        @Override
        public void onError(Throwable e) {
            Log.i("LOG", "onSuccess: "+e.toString());
        }
    });

Body:
Use RxJava2CallAdapterFactory instead of RxJavaCallAdapterFactory as RxJava2 is used.

.addCallAdapterFactory(RxJava2CallAdapterFactory.create())

to the Retrofit.Builder().


问:
This iPhone 7 (Model 1660, 1778, 1779, 1780) is running iOS 12.3.1 (16F203), which may not be supported by this version of Xcode
I getting the following error when I run the app into device.

This iPhone 7 (Model 1660, 1778, 1779, 1780) is running iOS 12.3.1 (16F203), which may not be supported by this version of Xcode.

my Xcode is 10.1

答:
I have the same problem , and here is the solution worked for me

You should make a folder named 12.3 (... what is written in your error message) in Program/Xcode-beta/Contents/Developer/Platforms/iPhoneOS.platforms/DeviceSupport/ and copy the files from 12.2 in there.

Close xcode completely and reopen it.

Now you can run your apps on iOS 12.3.