问:
Avoid changing state of class from computed fields - Odoo v8
I have these classes:

```<code>class bsi_production_order(models.Model):
    _name = 'bsi.production.order'

    name = fields.Char('Reference', required=True, index=True, copy=False, readonly='True', default='New')
    order_lines = fields.One2many('bsi.production.order.lines', 'production_order', states={'finished': [('readonly', True)], 'cancel': [('readonly', True)]}, string="Order lines", copy=True)
print_orders = fields.One2many('bsi.print.order', 'production_orders', string="Print Orders")
state = fields.Selection([
        ('draft','Draft'),
        ('start','Started'),
        ('inprogress','In progress'),
        ('print_order_inprogress','Print Order In Progress'),
        ('finished','Finished'),
        ('cancel','Cancel'),
    ], string='State', index=True,
    track_visibility='onchange', copy=False,
    help=" ")

class bsi_print_order(models.Model):
    _name = 'bsi.print.order'

    name = fields.Char('Reference', required=True, index=True, copy=False, readonly='True', default='New')
    order_lines = fields.One2many('bsi.print.order.lines', 'print_order', string="Order lines")
    state = fields.Selection([
        ('inprogress','Draft'),
        ('awaitingraw','Awaiting raw materials'),
        ('work_in_progress','Work in Progress'),
        ('delivered','Delivered'),
        ('cancel','Cancel'),
    ], string="State")
    notes = fields.Text(string="Notes")

class bsi_production_order_lines(models.Model):
    _name = 'bsi.production.order.lines'

    production_order = fields.Many2one('bsi.production.order', string="Production Orders")
    isbn = fields.Many2one('product.product', string="ISBN", domain="[('is_isbn', '=', True)]")
    qty = fields.Float(string="Quantity")
    consumed_qty = fields.Float(string="Consumed quantity")
    remaining_qty = fields.Float(string="Remaining quantity", compute="_remaining_func") #

    @api.onchange('qty', 'consumed_qty')
    def _remaining_func(self):
        if self.qty or self.consumed_qty:
            self.remaining_qty = self.qty +(-self.consumed_qty)

class bsi_print_order_lines(models.Model):
    _name = 'bsi.print.order.lines'

    print_order = fields.Many2one('bsi.print.order', string="Print Order")
    production_orders = fields.Many2one('bsi.production.order', ondelete='cascade', string="Production Order")
    isbn = fields.Many2one('product.product', string="ISBN", domain="[('is_isbn', '=', True)]")
    qty = fields.Integer(string="Quantity")
    consumed_qty = fields.Integer(string="Quantity consumed")
    remaining_qty = fields.Float(string="Remaining quantity", compute="_remaining_func")
    is_book_block = fields.Boolean(string="Is Book Block Done")
    is_binding = fields.Boolean(string="Is Binding Done")
    is_edging = fields.Boolean(string="Is Edging Done")
    isbns = fields.Many2one('worksheets.isbns', string="Worksheet ISBNS")

@api.onchange('qty', 'consumed_qty')
def _remaining_func(self):
    if self.consumed_qty or self.qty:
        self.remaining_qty = self.qty +(-self.consumed_qty)
</code>```

I create a bsi.print.order from a bsi.production.order class with this method:

```<code>@api.multi
def create_printy(self):
    copy_record = self.env['bsi.print.order']
    for record in self:
        order_lines = []
        for rec in record.order_lines:
            order_lines.append(
            (0,0,
            {
                'isbn': rec.isbn.id,
                'qty': rec.qty,
                }
            ))
        copy_record.create({
            'state' : 'inprogress',
            'order_lines': order_lines, # here we pass the list of commands that we created earlier
        })
        record.update({'state': 'print_order_inprogress',},)
</code>```

But no matter what state I choose, on record.update the state it's always changed on bsi.print.order.

I know it's because of the calculated fields, so, is there a way to pass them indirectly? Or a way to not affect the states of the child class? (bsi.print.order).

EDIT

These are the computed fields:

```<code>class bsi_production_order_lines(models.Model):
    _name = 'bsi.production.order.lines'

    production_order = fields.Many2one('bsi.production.order', string="Production Orders")
    isbn = fields.Many2one('product.product', string="ISBN", domain="[('is_isbn', '=', True)]")
    qty = fields.Float(string="Quantity")
    consumed_qty = fields.Float(string="Consumed quantity")
    remaining_qty = fields.Float(string="Remaining quantity", compute="_remaining_func") #

@api.onchange('qty', 'consumed_qty')
def _remaining_func(self):
    for s in self:
        for qty in s.isbn:
            if s.qty or s.consumed_qty:
                s.remaining_qty = s.qty +(-s.consumed_qty)
</code>```

On the other class these are the same fields.

答:
Try to replace update with write in your ORM create method. I think it is the only problem, because I see computed fields nowhere, so why would the value field change after you modify it from the create method? I think that using that update in an ORM method is not working, so the state never changes its value.

```<code>@api.multi
def create_printy(self):
    copy_record = self.env['bsi.print.order']
    for record in self:
        order_lines = []
        for rec in record.order_lines:
            order_lines.append(
            (0,0,
            {
                'isbn': rec.isbn.id,
                'qty': rec.qty,
                }
            ))
        copy_record.create({
            'state' : 'inprogress',
            'order_lines': order_lines, # here we pass the list of commands that we created earlier
        })
        record.write({'state': 'print_order_inprogress',},)
</code>```

Body:
I have these classes:

class bsi_production_order(models.Model):
    _name = 'bsi.production.order'

    name = fields.Char('Reference', required=True, index=True, copy=False, readonly='True', default='New')
    order_lines = fields.One2many('bsi.production.order.lines', 'production_order', states={'finished': [('readonly', True)], 'cancel': [('readonly', True)]}, string="Order lines", copy=True)
print_orders = fields.One2many('bsi.print.order', 'production_orders', string="Print Orders")
state = fields.Selection([
        ('draft','Draft'),
        ('start','Started'),
        ('inprogress','In progress'),
        ('print_order_inprogress','Print Order In Progress'),
        ('finished','Finished'),
        ('cancel','Cancel'),
    ], string='State', index=True,
    track_visibility='onchange', copy=False,
    help=" ")

class bsi_print_order(models.Model):
    _name = 'bsi.print.order'

    name = fields.Char('Reference', required=True, index=True, copy=False, readonly='True', default='New')
    order_lines = fields.One2many('bsi.print.order.lines', 'print_order', string="Order lines")
    state = fields.Selection([
        ('inprogress','Draft'),
        ('awaitingraw','Awaiting raw materials'),
        ('work_in_progress','Work in Progress'),
        ('delivered','Delivered'),
        ('cancel','Cancel'),
    ], string="State")
    notes = fields.Text(string="Notes")

class bsi_production_order_lines(models.Model):
    _name = 'bsi.production.order.lines'

    production_order = fields.Many2one('bsi.production.order', string="Production Orders")
    isbn = fields.Many2one('product.product', string="ISBN", domain="[('is_isbn', '=', True)]")
    qty = fields.Float(string="Quantity")
    consumed_qty = fields.Float(string="Consumed quantity")
    remaining_qty = fields.Float(string="Remaining quantity", compute="_remaining_func") #

    @api.onchange('qty', 'consumed_qty')
    def _remaining_func(self):
        if self.qty or self.consumed_qty:
            self.remaining_qty = self.qty +(-self.consumed_qty)

class bsi_print_order_lines(models.Model):
    _name = 'bsi.print.order.lines'

    print_order = fields.Many2one('bsi.print.order', string="Print Order")
    production_orders = fields.Many2one('bsi.production.order', ondelete='cascade', string="Production Order")
    isbn = fields.Many2one('product.product', string="ISBN", domain="[('is_isbn', '=', True)]")
    qty = fields.Integer(string="Quantity")
    consumed_qty = fields.Integer(string="Quantity consumed")
    remaining_qty = fields.Float(string="Remaining quantity", compute="_remaining_func")
    is_book_block = fields.Boolean(string="Is Book Block Done")
    is_binding = fields.Boolean(string="Is Binding Done")
    is_edging = fields.Boolean(string="Is Edging Done")
    isbns = fields.Many2one('worksheets.isbns', string="Worksheet ISBNS")

@api.onchange('qty', 'consumed_qty')
def _remaining_func(self):
    if self.consumed_qty or self.qty:
        self.remaining_qty = self.qty +(-self.consumed_qty)

I create a bsi.print.order from a bsi.production.order class with this method:

@api.multi
def create_printy(self):
    copy_record = self.env['bsi.print.order']
    for record in self:
        order_lines = []
        for rec in record.order_lines:
            order_lines.append(
            (0,0,
            {
                'isbn': rec.isbn.id,
                'qty': rec.qty,
                }
            ))
        copy_record.create({
            'state' : 'inprogress',
            'order_lines': order_lines, # here we pass the list of commands that we created earlier
        })
        record.update({'state': 'print_order_inprogress',},)

But no matter what state I choose, on record.update the state it's always changed on bsi.print.order.

I know it's because of the calculated fields, so, is there a way to pass them indirectly? Or a way to not affect the states of the child class? (bsi.print.order).

EDIT

These are the computed fields:

class bsi_production_order_lines(models.Model):
    _name = 'bsi.production.order.lines'

    production_order = fields.Many2one('bsi.production.order', string="Production Orders")
    isbn = fields.Many2one('product.product', string="ISBN", domain="[('is_isbn', '=', True)]")
    qty = fields.Float(string="Quantity")
    consumed_qty = fields.Float(string="Consumed quantity")
    remaining_qty = fields.Float(string="Remaining quantity", compute="_remaining_func") #

@api.onchange('qty', 'consumed_qty')
def _remaining_func(self):
    for s in self:
        for qty in s.isbn:
            if s.qty or s.consumed_qty:
                s.remaining_qty = s.qty +(-s.consumed_qty)

On the other class these are the same fields.

Body:
Try to replace update with write in your ORM create method. I think it is the only problem, because I see computed fields nowhere, so why would the value field change after you modify it from the create method? I think that using that update in an ORM method is not working, so the state never changes its value.

@api.multi
def create_printy(self):
    copy_record = self.env['bsi.print.order']
    for record in self:
        order_lines = []
        for rec in record.order_lines:
            order_lines.append(
            (0,0,
            {
                'isbn': rec.isbn.id,
                'qty': rec.qty,
                }
            ))
        copy_record.create({
            'state' : 'inprogress',
            'order_lines': order_lines, # here we pass the list of commands that we created earlier
        })
        record.write({'state': 'print_order_inprogress',},)


来源: stackexchange

问:
How to selectively choose values in a composite key in hadoop mapreduce
I have the following csv files with 5 columns and a number of rows. But I'm showing only first 6 rows.

```<code>Date,Food,Vitamin,Protein,NumStudents
01/01/17, Pasta, A, Yes, 560
01/01/17, Pizza, A, Yes, 730
01/01/17, Burrito, C, Yes, 240
02/01/17, Pizza, A, Yes, 340
02/01/17, Pasta, B, Yes, 450
02/01/17, Beef, B, Yes, 450
</code>```

Now I want to find the sum of NumStudents on a particular day who had only Pizza and Pasta.

In essence for 01/01/17 I only have to sum NumStudents for Pizza and Pasta but not Burrito.

Expected Output

```<code>01/01/17 1290
02/01/17 790
</code>```

Output I'm getting

```<code>01/01/17 1530
02/01/17 1240
</code>```

In my code I'm able to sum NumStudents for all 3 types of food but don't know how to selectively exclude some type of food from my composite key in mapper. Any idea how should I go about it?

答:
You could just filter the types you're interested in, in the mapper. This could look something like:

```<code>public class InputMapper extends Mapper<LongWritable, Text, Text, IntWritable> {

    private Text oKey = new Text();
    private IntWritable oValue = new IntWritable();

    @Override
    public void map(LongWritable key, Text value, Context context)
                            throws IOException, InterruptedException {

        String parts[] = value.toString().split(",");
        if (parts[1].equals("Pasta") || parts[1].equals("Pizza")) {
            oKey.set(parts[0]);
            oValue.set(Integer.parseInt(parts[4]));
            context.write(oKey, oValue);
        }
    }
}
</code>```

So in the reduce you would just sum the values to get the total count and the key is the date.

ContentLicense: CC BY-SA 3.0

Body:
I have the following csv files with 5 columns and a number of rows. But I'm showing only first 6 rows.

Date,Food,Vitamin,Protein,NumStudents
01/01/17, Pasta, A, Yes, 560
01/01/17, Pizza, A, Yes, 730
01/01/17, Burrito, C, Yes, 240
02/01/17, Pizza, A, Yes, 340
02/01/17, Pasta, B, Yes, 450
02/01/17, Beef, B, Yes, 450

Now I want to find the sum of NumStudents on a particular day who had only Pizza and Pasta.

In essence for 01/01/17 I only have to sum NumStudents for Pizza and Pasta but not Burrito.

Expected Output

01/01/17 1290
02/01/17 790

Output I'm getting

01/01/17 1530
02/01/17 1240

In my code I'm able to sum NumStudents for all 3 types of food but don't know how to selectively exclude some type of food from my composite key in mapper. Any idea how should I go about it?

Body:
You could just filter the types you're interested in, in the mapper. This could look something like:

public class InputMapper extends Mapper<LongWritable, Text, Text, IntWritable> {

    private Text oKey = new Text();
    private IntWritable oValue = new IntWritable();

    @Override
    public void map(LongWritable key, Text value, Context context)
                            throws IOException, InterruptedException {

        String parts[] = value.toString().split(",");
        if (parts[1].equals("Pasta") || parts[1].equals("Pizza")) {
            oKey.set(parts[0]);
            oValue.set(Integer.parseInt(parts[4]));
            context.write(oKey, oValue);
        }
    }
}

So in the reduce you would just sum the values to get the total count and the key is the date.


问:
Jquery Live Validation
After having a search around I could not find exactly what I want, I am looking to validate a form client side using the Jquery library and some form of validation plugin.  I was hoping that some one could advise me on whether there are any validation plugins out there that do not use generic error messages, as my form is laid out with no room for these errors, and I also I want the validator to to for correct content as well.

Basically I want to be able to check the field on each key press and blur and if the fields validates for it to gain a green border, and if it does not validate for it to gain a red border, any one know of a plugin that can do this?

Thanks

sico87

答: I don't know what you searched for, but the Validation plugin (first google result for "jquery validation") does exactly what you want... Read the docs that come with it.</p>

ContentLicense: CC BY-SA 2.5

Title: Jquery Live Validation

OwnerDisplayName: Oli


问:
json removed if nested class repo is added to spring boot project
i am new to spring-boot, i am getting a strange problem.
i am using repository to get reviews of a movie

```<code>@RepositoryRestResource
public interface ReviewRepository extends JpaRepository<Review, Integer> {

    @Query("select rev from Review rev where rev.gymId=:gymId")
    Page findByMovieId(@Param("movieId") Integer movieId, Pageable page);

}
</code>```

when i tried to getting reviews i am getting below json

```<code> {
            "id": 1,
            "rating": 4,
            "movieId":6
            "movie":{
                id:6,
                name:"edge of tomorrow"
             }
  }
</code>```

problem is that when i am adding repository of Movie to my project.

```<code>{
                "id": 1,
                "rating": 4,
                "movieId":6
}
</code>```

can anyone help me in this.

what is happening here?

below is my Review Pojo

```<code>@Entity
@Table(name = "review", schema = "public")
@NamedQueries({
        @NamedQuery(name = "Review.countAll", query = "SELECT COUNT(x) FROM Review x")
})
public class Review implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", nullable = false)
    private Integer id;
    @Column(name = "rating")
    private Integer rating;

    @ManyToOne
    @JoinColumn(name = "movie_id", referencedColumnName = "id", updatable = false, insertable = false)
    private Movie movie;

    @ManyToOne
    @JoinColumn(name = "consumer_id", referencedColumnName = "id", updatable = false, insertable = false)
    private Consumer consumer;

    //setter getter
}
</code>```

答:
This happen because you use Spring Data REST in your project (I see @RepositoryRestResource annotation).

To solve this issue you can, for example, add parameter exported=false to @RepositoryRestResource of your Movie repo.

More info is here.

Body:
i am new to spring-boot, i am getting a strange problem.
i am using repository to get reviews of a movie

@RepositoryRestResource
public interface ReviewRepository extends JpaRepository<Review, Integer> {

    @Query("select rev from Review rev where rev.gymId=:gymId")
    Page findByMovieId(@Param("movieId") Integer movieId, Pageable page);

}

when i tried to getting reviews i am getting below json

 {
            "id": 1,
            "rating": 4,
            "movieId":6
            "movie":{
                id:6,
                name:"edge of tomorrow"
             }
  }

problem is that when i am adding repository of Movie to my project.

{
                "id": 1,
                "rating": 4,
                "movieId":6
}

can anyone help me in this.

what is happening here?

below is my Review Pojo

@Entity
@Table(name = "review", schema = "public")
@NamedQueries({
        @NamedQuery(name = "Review.countAll", query = "SELECT COUNT(x) FROM Review x")
})
public class Review implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", nullable = false)
    private Integer id;
    @Column(name = "rating")
    private Integer rating;

    @ManyToOne
    @JoinColumn(name = "movie_id", referencedColumnName = "id", updatable = false, insertable = false)
    private Movie movie;

    @ManyToOne
    @JoinColumn(name = "consumer_id", referencedColumnName = "id", updatable = false, insertable = false)
    private Consumer consumer;

    //setter getter
}


问:
Advantage of using H in cron in Jenkins
Is there a real big advantage of using H in cron in Jenkins?
Like:

```<code>H 21 * * 1-5
</code>```

instead of

```<code>0 21 * * 1-5
</code>```

I prefer the last step in my case because I really want to run the job on 06.00 etc. The warning in Jenkins is always showing:

```<code>Spread load evenly by using ‘H 21 * * 1-5’ rather than ‘0 21 * * 1-5’
</code>```

Do I have to bee worried for this?

答: As long as you are not scheduling many jobs for the same time, you don't have to worry. Just the more you schedule for a certain time, the less likely it is that they can be executed in parallel (depending on the number of executors). If you just don't care about, when a job is executed, then give Jenkins the chance to distribute the load.</p>

Title: Advantage of using H in cron in Jenkins

Body:
Is there a real big advantage of using H in cron in Jenkins?
Like:

H 21 * * 1-5

instead of

0 21 * * 1-5

I prefer the last step in my case because I really want to run the job on 06.00 etc. The warning in Jenkins is always showing:

Spread load evenly by using ‘H 21 * * 1-5’ rather than ‘0 21 * * 1-5’

Do I have to bee worried for this?


问:
Call to a controller inside a javascript function
I have a controller: messages
a method in that controller: favourite_checked()
a variable that stores messages_id from my messages table in my database

This URL is produced

mysite.com/messages/favourite_checked/1
mysite.com/controller/method/message_id

When this URL is successfully called it connects to my model and updates a column in my messages table called "favourite". The 0 in that column is updated to 1.

0 = boxed unchecked (not favourite inbox message) - Greyed out image
1= boxed checked (user selected specific message as favourite message) - Coloured image

Anyway I some how need to have this URL loaded in my (ischecked) function in my javascript.
The problem is it needs to also load the correct message_id the specific row that is being clicked on.

message_id = id...   from my messages table so that is grabbed from the db and is added on to the end of the URL and is basically what my controller method stored in a variable and passes to a model as an argument and used in an sql query in a model to make sure correct row in database is updated.

In the following code I do the same kind of thing for my message inbox links. Works perfectly.

```<code> <?php foreach ($query as $row):  ?>
  <tr>
    <?php switch($row['status']){
        case 0: $status = "unread"; break;
        case 1: $status = "read"; break;
        case 2: $status = "replied"; break;
        case 3: $status = "fav"; break;
        default: $status = '';
    }?>

    <td width="5%"><input name="message" id="messages" type="checkbox" value="" class="<?php echo $status; ?>"/></td>
    <td width="5%"><input name="sunny" id="" type="checkbox" value="" class="favourite" checked="checked" /></td>
    <td><?php echo $status; ?></td>
    <td><?php echo $row['from_user']; ?></td>
    <td><div id="test"><a href="<?php echo site_url("messages/read_message/".$row['id']); ?>"><?php echo $row['subject'] . " " . $row['message']; ?></a></a></div></td>
    <td><?php if ($row['date_sent'] == date('Y-m-d')) { echo $row['time_sent']; } else echo $row['date_sent']; ?></td>
  </tr>
<?php endforeach; ?>
</code>```

I just some how need to have the URL above with the id grabbed from my database load after box is checked so query can run and update the specific column in my database

and do the same thing when the box is unchecked again.

I would also need a foreach loop inside the javascript function because each message in their inbox would need to made available in order for them to be able to make messages favourite messages.

Here's my javascript

```<code>// favourite check box
    $('input.favourite:checkbox').simpleImageCheck({
  image: '<?php echo base_url()?>images/messages/check.png',
  imageChecked: '<?php echo base_url()?>images/messages/unchecked.png',
  afterCheck: function(isChecked) {
    if (isChecked) {

  //query to db from php to update favourite number to 1
  $.post('');

    }
//    else (!isChecked)
//        {
//            //query to db from php to update favourite number to 0
//              $.post('');
//        }
  }
});
</code>```

Help appreciated thanks in advance.

答:
You can save message id as data attribute in html. E.g.,

```<code><tr data-message-id="<?php echo $id_goes_here; ?>">
</code>```

instead of simple

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

Then, in your event handler, you can get message id like this

```<code>$(this).closest('tr').attr('data-message-id')
</code>```

I assume this points to an element clicked (or any DOM element inside that row)

PS With a recent jquery version (1.4.4, I think), you can also replace .attr('data-message-id') with .data('message-id').

Body:
I have a controller: messages
a method in that controller: favourite_checked()
a variable that stores messages_id from my messages table in my database

This URL is produced

mysite.com/messages/favourite_checked/1
mysite.com/controller/method/message_id

When this URL is successfully called it connects to my model and updates a column in my messages table called "favourite". The 0 in that column is updated to 1.

0 = boxed unchecked (not favourite inbox message) - Greyed out image
1= boxed checked (user selected specific message as favourite message) - Coloured image

Anyway I some how need to have this URL loaded in my (ischecked) function in my javascript.
The problem is it needs to also load the correct message_id the specific row that is being clicked on.

message_id = id...   from my messages table so that is grabbed from the db and is added on to the end of the URL and is basically what my controller method stored in a variable and passes to a model as an argument and used in an sql query in a model to make sure correct row in database is updated.

In the following code I do the same kind of thing for my message inbox links. Works perfectly.

 <?php foreach ($query as $row):  ?>

    <?php switch($row['status']){
        case 0: $status = "unread"; break;
        case 1: $status = "read"; break;
        case 2: $status = "replied"; break;
        case 3: $status = "fav"; break;
        default: $status = '';
    }?>

    <input name="message" id="messages" type="checkbox" value="" class="<?php echo $status; ?>"/>
    <input name="sunny" id="" type="checkbox" value="" class="favourite" checked="checked" />
    <?php echo $status; ?>
    <?php echo $row['from_user']; ?>

<a href="<?php echo site_url("messages/read_message/".$row['id']); ?>"><?php echo $row['subject'] . " " . $row['message']; ?>

    <?php if ($row['date_sent'] == date('Y-m-d')) { echo $row['time_sent']; } else echo $row['date_sent']; ?>

<?php endforeach; ?>

I just some how need to have the URL above with the id grabbed from my database load after box is checked so query can run and update the specific column in my database

and do the same thing when the box is unchecked again.

I would also need a foreach loop inside the javascript function because each message in their inbox would need to made available in order for them to be able to make messages favourite messages.

Here's my javascript

// favourite check box
    $('input.favourite:checkbox').simpleImageCheck({
  image: '<?php echo base_url()?>images/messages/check.png',
  imageChecked: '<?php echo base_url()?>images/messages/unchecked.png',
  afterCheck: function(isChecked) {
    if (isChecked) {

  //query to db from php to update favourite number to 1
  $.post('');

    }
//    else (!isChecked)
//        {
//            //query to db from php to update favourite number to 0
//              $.post('');
//        }
  }
});

Help appreciated thanks in advance.

Body:
You can save message id as data attribute in html. E.g.,

<tr data-message-id="<?php echo $id_goes_here; ?>">

instead of simple

<tr>

Then, in your event handler, you can get message id like this

$(this).closest('tr').attr('data-message-id')

I assume this points to an element clicked (or any DOM element inside that row)

PS With a recent jquery version (1.4.4, I think), you can also replace .attr('data-message-id') with .data('message-id').


问:
Unable to merge dex
I have Android Studio Beta. I created a new project with compile my old modules but when I tried launching the app it did not launch with the message:

```<code>Error:Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
</code>```

com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

But I don't know how to solve this error. I googled this for hours but with no success.

My project gradle:

```<code>    // Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-beta6'
        classpath "io.realm:realm-gradle-plugin:3.7.1"
        classpath 'com.google.gms:google-services:3.1.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        google()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

My app gradle:

```<code>    apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "parad0x.sk.onlyforyou"
        minSdkVersion 21
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
        }
    }
    compileOptions {
        targetCompatibility 1.7
        sourceCompatibility 1.7
    }
    packagingOptions {
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/NOTICE'
    }
    lintOptions {
        checkReleaseBuilds false
    }
    productFlavors {
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    //noinspection GradleCompatible
    compile 'com.android.support:appcompat-v7:26.0.0-alpha1'
    compile project(path: ':loginregisterview')

}
</code>```

And my module gradle:

```<code>    apply plugin: 'com.android.library'
apply plugin: 'realm-android'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"

    defaultConfig {
        minSdkVersion 19
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.0.2'
    compile 'com.android.support:support-v4:26.1.0'
    compile 'com.github.bumptech.glide:glide:4.0.0'
    testCompile 'junit:junit:4.12'
    compile project(path: ':parser')

}
</code>```

My second module:

```<code>     apply plugin: 'com.android.library'
apply plugin: 'realm-android'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }

    realm {
        syncEnabled = true
    }
    useLibrary 'org.apache.http.legacy'

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile 'junit:junit:4.12'
    //  compile 'com.android.support:appcompat-v7:23.1.0'

    //   compile 'com.fasterxml.jackson.core:jackson-core:2.9.0'
 //   compile 'com.fasterxml.jackson.core:jackson-annotations:2.9.0'
 //   compile 'com.fasterxml.jackson.core:jackson-databind:2.9.0'
    compile 'com.google.code.gson:gson:2.6.2'
}
</code>```

____________finding_________

When I did not import the second module (parser) the app did not crash on dex but when the module was not imported app did not work. :D :D

答: In my case, I import one 'android_support' lib twice ,so I delete one under 'libs' directory and rebuild.</p>

Title: Unable to merge dex

Body:
I have Android Studio Beta. I created a new project with compile my old modules but when I tried launching the app it did not launch with the message:

Error:Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.

com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

But I don't know how to solve this error. I googled this for hours but with no success.

My project gradle:

    // Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-beta6'
        classpath "io.realm:realm-gradle-plugin:3.7.1"
        classpath 'com.google.gms:google-services:3.1.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        google()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

My app gradle:

    apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "parad0x.sk.onlyforyou"
        minSdkVersion 21
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
        }
    }
    compileOptions {
        targetCompatibility 1.7
        sourceCompatibility 1.7
    }
    packagingOptions {
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/NOTICE'
    }
    lintOptions {
        checkReleaseBuilds false
    }
    productFlavors {
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    //noinspection GradleCompatible
    compile 'com.android.support:appcompat-v7:26.0.0-alpha1'
    compile project(path: ':loginregisterview')

}

And my module gradle:

    apply plugin: 'com.android.library'
apply plugin: 'realm-android'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"

    defaultConfig {
        minSdkVersion 19
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.0.2'
    compile 'com.android.support:support-v4:26.1.0'
    compile 'com.github.bumptech.glide:glide:4.0.0'
    testCompile 'junit:junit:4.12'
    compile project(path: ':parser')

}

My second module:

     apply plugin: 'com.android.library'
apply plugin: 'realm-android'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }

    realm {
        syncEnabled = true
    }
    useLibrary 'org.apache.http.legacy'

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile 'junit:junit:4.12'
    //  compile 'com.android.support:appcompat-v7:23.1.0'

    //   compile 'com.fasterxml.jackson.core:jackson-core:2.9.0'
 //   compile 'com.fasterxml.jackson.core:jackson-annotations:2.9.0'
 //   compile 'com.fasterxml.jackson.core:jackson-databind:2.9.0'
    compile 'com.google.code.gson:gson:2.6.2'
}

____________finding_________

When I did not import the second module (parser) the app did not crash on dex but when the module was not imported app did not work. :D :D


问:
how can I do facebook login using FB.api

var FB = require('fb'),
    fb = new FB.Facebook(options);
    var options = FB.options();
var {Facebook, FacebookApiException} = require('fb'),
    fb = new Facebook(options);

FB.api('me/feed', 'post', { fields: ['email', 'name']}, function (req, res) {
//FB.setAccessToken(req.query.fb_token);
  if(!res || res.error) {
    console.log(!res ? 'error occurred' : res.error);
    return;
  }
  console.log('Post Id: ' + res.id);
});```

How can I get user email and name by passing access token as a query parameter.

答:
Not tested, but according to the docs on npm:

```<code>FB.setAccessToken(req.query.fb_token);
FB.api('me', {fields: ['email', 'name'], (req, res) => {
  if(!res || res.error) {
    console.log(!res ? 'error occurred' : res.error);
    return;
  }
  console.log(res.email, res.name);
});
</code>```

Make sure you know when to use GET and POST, and of course the feed endpoint does not return any email. You just copied that code from the docs, but from the wrong place ;)

Body:
var FB = require('fb'),
    fb = new FB.Facebook(options);
    var options = FB.options();
var {Facebook, FacebookApiException} = require('fb'),
    fb = new Facebook(options);

FB.api('me/feed', 'post', { fields: ['email', 'name']}, function (req, res) {
//FB.setAccessToken(req.query.fb_token);
  if(!res || res.error) {
    console.log(!res ? 'error occurred' : res.error);
    return;
  }
  console.log('Post Id: ' + res.id);
});

How can I get user email and name by passing access token as a query parameter.

Body:
Not tested, but according to the docs on npm:

FB.setAccessToken(req.query.fb_token);
FB.api('me', {fields: ['email', 'name'], (req, res) => {
  if(!res || res.error) {
    console.log(!res ? 'error occurred' : res.error);
    return;
  }
  console.log(res.email, res.name);
});

Make sure you know when to use GET and POST, and of course the feed endpoint does not return any email. You just copied that code from the docs, but from the wrong place ;)


问:
How to assign static values into the query result - codeigniter
So I have this site which has a select box containing:

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

But I want to change them into a static value like:

```<code>Travel
Housing
Gourmet
Medical
</code>```

There is no specified field name in the database, like Travel,etc. It's purely number. So I have to assign static values representing each number.

The only field names in the db is id, industry_id, company_name. the one I specified above(numbers 1-4) are industry_id.

In my Controller:

```<code>$params["filter"] = $this->Users->get_category();
</code>```

Model:

```<code>$sql = "SELECT industry_id FROM company GROUP BY industry_id ORDER BY industry_id ASC";
$query = $this->db->query($sql);
return $query->result();
</code>```

View:

```<code><select class="form-control" name="field">
<?php foreach($filter as $cat)
{
    echo '<option value="'.$cat->industry_id.'">'.$cat->industry_id.'</option>';
}
?>
</select>
</code>```

How can I do it?

答:
what about that

```<code>$sql = "SELECT industry_id, CASE WHEN industry_id = 1 THEN 'Travel' WHEN industry_id = 2 THEN 'Housing' WHEN industry_id = 3 THEN 'Gourmet' WHEN industry_id = 4 THEN 'Medical' END AS industry_description  FROM company GROUP BY industry_id ORDER BY industry_id ASC";
</code>```

Be aware if industry_id is an INT this code should work - if its a VARCHAR you have to use e.g. WHEN industry_id = '1'

and in your view you simply access to industry_description

```<code><select class="form-control" name="field">
<?php foreach($filter as $cat)
{
    echo '<option value="'.$cat->industry_id.'">'.$cat->industry_description.'</option>';
}
?>
</select>
</code>```

Body:
So I have this site which has a select box containing:

1
2
3
4

But I want to change them into a static value like:

Travel
Housing
Gourmet
Medical

There is no specified field name in the database, like Travel,etc. It's purely number. So I have to assign static values representing each number.

The only field names in the db is id, industry_id, company_name. the one I specified above(numbers 1-4) are industry_id.

In my Controller:

$params["filter"] = $this->Users->get_category();

Model:

$sql = "SELECT industry_id FROM company GROUP BY industry_id ORDER BY industry_id ASC";
$query = $this->db->query($sql);
return $query->result();

View:

<select class="form-control" name="field">
<?php foreach($filter as $cat)
{
    echo '<option value="'.$cat->industry_id.'">'.$cat->industry_id.'</option>';
}
?>
</select>

How can I do it?

Body:
what about that

$sql = "SELECT industry_id, CASE WHEN industry_id = 1 THEN 'Travel' WHEN industry_id = 2 THEN 'Housing' WHEN industry_id = 3 THEN 'Gourmet' WHEN industry_id = 4 THEN 'Medical' END AS industry_description  FROM company GROUP BY industry_id ORDER BY industry_id ASC";

Be aware if industry_id is an INT this code should work - if its a VARCHAR you have to use e.g. WHEN industry_id = '1'

and in your view you simply access to industry_description

<select class="form-control" name="field">
<?php foreach($filter as $cat)
{
    echo '<option value="'.$cat->industry_id.'">'.$cat->industry_description.'</option>';
}
?>
</select>


问:
How to use addroutes method in Vue-router?
I have created a function "addroute()" to add routes dynamically,but it didn't work(the router does not changed).
Is this a right way to use addRoutes method? I have learned this from tutorial.
If not then give me a correct example,Thanks!</p>

```<code>...
const Bar={
    template:'#panels',
    data(){
        return {title:'badss'}
    }
        };
const Foo={
    template:"#panels",
        data(){
        return {title:'hell'}
    }
        };

const router = new VueRouter({
  routes:[
      {path:'/foo',component:Foo},
      {path:'/bar',component:Bar}
  ]
});

new Vue({
    el:'#root',
    router:router,
    data:{
    stats:stats
},
methods: {
    //
},

});

function addroute(){//watch here
    router.addRoutes([{path:'/ioio',component:{template:'#panels'}}])
}
setInterval("addroute()", 2000)//watch here
...
</code>```

答:
The router instance that you are trying to change is already added to the Vue instance that you have. Changing that router does not update the Vue instance. What you want to do is call the router instance that you have added to the Vue instance. A complete working example can be found at: Add routes in vue-router

So you access the router inside a method in the Vue instance using this.$router. You then add the desired route that you want to add using the .addRoutes functionality.

In the fiddle, you can see that I have added the ioio link in the HTML already, but it does not work yet (clicking it will result in the Default being added to the <router-view></router-view>). When clicking on the button, you are adding a new route. I have added the this.$router.push('/ioio'); to force an update on the <router-view></router-view> after adding the route. If you remove this line of the code, the <router-view></router-view> will display the last shown element (which is desirable in most cases), and clicking on the ioio-button again will show the newly created route.

Hope this helps!

Body:
I have created a function "addroute()" to add routes dynamically,but it didn't work(the router does not changed).
Is this a right way to use addRoutes method? I have learned this from tutorial.
If not then give me a correct example,Thanks!

...
const Bar={
    template:'#panels',
    data(){
        return {title:'badss'}
    }
        };
const Foo={
    template:"#panels",
        data(){
        return {title:'hell'}
    }
        };

const router = new VueRouter({
  routes:[
      {path:'/foo',component:Foo},
      {path:'/bar',component:Bar}
  ]
});

new Vue({
    el:'#root',
    router:router,
    data:{
    stats:stats
},
methods: {
    //
},

});

function addroute(){//watch here
    router.addRoutes([{path:'/ioio',component:{template:'#panels'}}])
}
setInterval("addroute()", 2000)//watch here
...

Body:
The router instance that you are trying to change is already added to the Vue instance that you have. Changing that router does not update the Vue instance. What you want to do is call the router instance that you have added to the Vue instance. A complete working example can be found at: Add routes in vue-router

So you access the router inside a method in the Vue instance using this.$router. You then add the desired route that you want to add using the .addRoutes functionality.

In the fiddle, you can see that I have added the ioio link in the HTML already, but it does not work yet (clicking it will result in the <span>Default</span> being added to the <router-view></router-view>). When clicking on the button, you are adding a new route. I have added the this.$router.push('/ioio'); to force an update on the <router-view></router-view> after adding the route. If you remove this line of the code, the <router-view></router-view> will display the last shown element (which is desirable in most cases), and clicking on the ioio-button again will show the newly created route.

Hope this helps!


问:
How to generate unique ids for RecyclerView, in case of 2 ids per item?

Background

Suppose I have a RecyclerView, which has items that can only be unique if you look at 2 ids they have, but not just one of them.

The first Id is the primary one. Usually there aren't 2 items that have the same primary ID, but sometimes it might occur, which is why there is a secondary ID.

In my

The problem

The RecyclerView adapter needs to have a "long" type being returned:

https://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter.html#getItemId(int)

What I've tried

The easy way to overcome this, is to have a HashMap and a counter.

The HashMap will contain the combined-keys, and the value will be the id that should be returned. The counter is used to generated the next id in case of a new combined key. The combined key can be a "Pair" class in this case.

Suppose each item in the RecyclerView data has 2 long-type keys:

```<code>HashMap<Pair<Long,Long>,Long> keyToIdMap=new HashMap();
long idGenerator=0;
</code>```

this is what to do in getItemId :

```<code>Pair<Long,Long> combinedKey=new Pair(item.getPrimaryId(), item.getSecondary());
Long uniqueId=keyToIdMap.get(combinedKey);
if(uniqueId==null)
  keyToIdMap.put(combinedKey,uniqueId=idGenerator++);
return uniqueId;
</code>```

This has the drawback of taking more and more memory. Not much though, and it's very small and proportional to the data you already have, but still...

However, this has the advantage of being able to handle all types of IDs, and you can use even more IDs as you wish (just need something similar to Pair).

Another advantage is that it will use all IDs starting from 0.

The question

Is there perhaps a better way to achieve this?

Maybe a mathematical way? I remember I learned in the past of using prime numbers for similar tasks. Will it work here somehow?

答:
Do the existing primary and secondary ids use the entire 64-bit range of longs? If not then it's possible to compute a unique 64-bit long from their values with e.g bit slicing.

Another approach would be to hash the two together with a hash with very low collisions (a crypto hash like SHA2 for example) and using the first 64 bits of the result. Having a range of 64 bits means you can comfortably have millions of items before the chance of a collision becomes likely - the chance of a collision is 50% when you add sqrt(64)=2**32 items, which is more than 4 billion.

Finally, having an unique independent mapping is very versatile and assuming the map is always accessible it's fine (it gets tricky when you try to synchronize that new id across machine etc). In Java you can attempt to increase performance by avoiding the boxed Longs and a separate Pair instance using a custom map implementation, but that's micro-optimizing.

Example using SHA1:

With Guava - the usage is clean and obvious.

```<code>HashFunction hf = Hashing.sha1();
long hashedId = hf.newHasher()
       .putLong(primary)
       .putLong(secondary)
       .hash()
       .asLong();
</code>```

Just the standard JDK, it's pretty horrible and can probably be more efficient, should look something like this (I'm ignoring checked exceptions):

```<code>static void updateDigestWithLong(MessageDigest md, long l) {
  md.update((byte)l);
  md.update((byte)(l >> 8));
  md.update((byte)(l >> 16));
  md.update((byte)(l >> 24));
}

// this is from the Guava sources, can reimplement if you prefer
static long padToLong(bytes[] bytes) {
  long retVal = (bytes[0] & 0xFF);
  for (int i = 1; i < Math.min(bytes.length, 8); i++) {
    retVal |= (bytes[i] & 0xFFL) << (i * 8);
  }
  return retVal;
}

static long hashLongsToLong(long primary, long secondary) {
  MessageDigest md = MessageDigest.getInstance("SHA-1");
  updateDigestWithLong(md, primary);
  updateDigestWithLong(md, secondary);
  return padToLong(md.digest());
}
</code>```

Body:
Background

Suppose I have a RecyclerView, which has items that can only be unique if you look at 2 ids they have, but not just one of them.

The first Id is the primary one. Usually there aren't 2 items that have the same primary ID, but sometimes it might occur, which is why there is a secondary ID.

In my

The problem

The RecyclerView adapter needs to have a "long" type being returned:

https://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter.html#getItemId(int)

What I've tried

The easy way to overcome this, is to have a HashMap and a counter.

The HashMap will contain the combined-keys, and the value will be the id that should be returned. The counter is used to generated the next id in case of a new combined key. The combined key can be a "Pair" class in this case.

Suppose each item in the RecyclerView data has 2 long-type keys:

HashMap<Pair<Long,Long>,Long> keyToIdMap=new HashMap();
long idGenerator=0;

this is what to do in getItemId :

Pair<Long,Long> combinedKey=new Pair(item.getPrimaryId(), item.getSecondary());
Long uniqueId=keyToIdMap.get(combinedKey);
if(uniqueId==null)
  keyToIdMap.put(combinedKey,uniqueId=idGenerator++);
return uniqueId;

This has the drawback of taking more and more memory. Not much though, and it's very small and proportional to the data you already have, but still...

However, this has the advantage of being able to handle all types of IDs, and you can use even more IDs as you wish (just need something similar to Pair).

Another advantage is that it will use all IDs starting from 0.

The question

Is there perhaps a better way to achieve this?

Maybe a mathematical way? I remember I learned in the past of using prime numbers for similar tasks. Will it work here somehow?

Body:
Do the existing primary and secondary ids use the entire 64-bit range of longs? If not then it's possible to compute a unique 64-bit long from their values with e.g bit slicing.

Another approach would be to hash the two together with a hash with very low collisions (a crypto hash like SHA2 for example) and using the first 64 bits of the result. Having a range of 64 bits means you can comfortably have millions of items before the chance of a collision becomes likely - the chance of a collision is 50% when you add sqrt(64)=2**32 items, which is more than 4 billion.

Finally, having an unique independent mapping is very versatile and assuming the map is always accessible it's fine (it gets tricky when you try to synchronize that new id across machine etc). In Java you can attempt to increase performance by avoiding the boxed Longs and a separate Pair instance using a custom map implementation, but that's micro-optimizing.

Example using SHA1:

With Guava - the usage is clean and obvious.

HashFunction hf = Hashing.sha1();
long hashedId = hf.newHasher()
       .putLong(primary)
       .putLong(secondary)
       .hash()
       .asLong();

Just the standard JDK, it's pretty horrible and can probably be more efficient, should look something like this (I'm ignoring checked exceptions):

static void updateDigestWithLong(MessageDigest md, long l) {
  md.update((byte)l);
  md.update((byte)(l >> 8));
  md.update((byte)(l >> 16));
  md.update((byte)(l >> 24));
}

// this is from the Guava sources, can reimplement if you prefer
static long padToLong(bytes[] bytes) {
  long retVal = (bytes[0] & 0xFF);
  for (int i = 1; i < Math.min(bytes.length, 8); i++) {
    retVal |= (bytes[i] & 0xFFL) << (i * 8);
  }
  return retVal;
}

static long hashLongsToLong(long primary, long secondary) {
  MessageDigest md = MessageDigest.getInstance("SHA-1");
  updateDigestWithLong(md, primary);
  updateDigestWithLong(md, secondary);
  return padToLong(md.digest());
}


问:
Is it possible to change the background of a sub screen (PreferenceScreen) of a PreferenceActivity?
I found that you can change the background of a PreferenceActivity by using getListView().setBackgroundResource(R.drawable.bg);

However, if you go to any deeper PreferenceScreens the background returns to being black.

There don't appear to be any methods in PreferenceScreen that would allow changes to the background either.

答:
The nested PreferenceScreens are supposed to take the theme from the parent however due to this bug http://code.google.com/p/android/issues/detail?id=4611&q=preference%20nested&colspec=ID%20Type%20Status%20Owner%20Summary%20Stars they don't and I don't know of how to set the background manually in the nested preference. Hopefully this helps at least explain why.

Would love to hear if you find a workaround :)


问:
Separate a string with different delimiters in python
I came across a csv file which made me wonder what should be the correct processes to get the info out of it. I want to read each line and then each row in variables lastname, firstname and department but,

structure of the csv file is like this

```<code>lastname, firstname (department)
</code>```

lets say we have a name Jean-Claude Van Damme

```<code>Van Damme, Jean-Claude (Karate-Master)
</code>```

what would be the best way to separate such string and store in variables lastname, firstname and the department?

```<code>import csv
import string
import re

file = open('path/testing_delimiters.csv', 'rb')
reader = csv.reader(file)
for row in reader:
    data = map(string.strip, row)
print data
# output so far
# ['Van Damme', 'Jean-Claude (Karate-Master)']
</code>```

task is to separate Jean-Claude and (Karate-Master)

```<code># expected output
# ['Van Damme', 'Jean-Claude', 'Karate-Master']
</code>```

答:
You can use Pandas library:

```<code>import pandas as pd
df = pd.read_csv('your_file.csv',sep=',|\(',engine='python',header=None)
</code>```

Use two separators , andd (
Then you can strip )

```<code>df[2]=df[2].str.strip(')')
</code>```

[2] in this case is column number.

Body:
I came across a csv file which made me wonder what should be the correct processes to get the info out of it. I want to read each line and then each row in variables lastname, firstname and department but,

structure of the csv file is like this

lastname, firstname (department)

lets say we have a name Jean-Claude Van Damme

Van Damme, Jean-Claude (Karate-Master)

what would be the best way to separate such string and store in variables lastname, firstname and the department?

import csv
import string
import re

file = open('path/testing_delimiters.csv', 'rb')
reader = csv.reader(file)
for row in reader:
    data = map(string.strip, row)
print data
# output so far
# ['Van Damme', 'Jean-Claude (Karate-Master)']

task is to separate Jean-Claude and (Karate-Master)

# expected output
# ['Van Damme', 'Jean-Claude', 'Karate-Master']

Body:
You can use Pandas library:

import pandas as pd
df = pd.read_csv('your_file.csv',sep=',|\(',engine='python',header=None)

Use two separators , andd (
Then you can strip )

df[2]=df[2].str.strip(')')

[2] in this case is column number.


问:
Macro Excel won't past exact image to Powerpoint Presentation
The strangest thing is happening with my macro in Excel. It works like a charm, but when it has to copy 2 charts and paste into my powerpoint presentation, suddenly, the Chart isn't exactly the same.

My code:

```<code>Set Wb = Workbooks.Open("Path\WbName.xlsx", ReadOnly:=True, UpdateLinks:=0)
</code>```

It opens 5 more workbooks... And then it goes through a loop, to copy all the Charts

```<code>Dim Charts_Arr As Variant
    Charts_Arr = Worksheets("Parameters").ListObjects("Parameters").DataBodyRange.Value

For i = LBound(Charts_Arr) To UBound(Charts_Arr)
    SourcePath = Charts_Arr(i, 8)
    SheetName = Charts_Arr(i, 4)
    ShapeNr = Charts_Arr(i, 2)
    SlideNr = Charts_Arr(i, 3)
    Schaling = Charts_Arr(i, 6)

    Set Source = Workbooks(SourcePath)
    Set PPpres = oPPTApp.ActivePresentation
    Set Sh = Source.Sheets(SheetName).Shapes(ShapeNr)

    Sh.Copy

    Set NewSh = PPpres.Slides(SlideNr).Shapes.PasteSpecial(ppPasteJPG)
    With NewSh
      .Top = Charts_Arr(i, 5)
      .Left = Charts_Arr(i, 7)
      .ScaleHeight Schaling, msoTrue
    End With

Next i
</code>```

This goes perfectly. But when I take a look at the ppt-file, 2 charts are not exactly the same.

(TIP: Excel is Chartarea, not a shape - didn't know this at first)

When copy the picture manually, I get the correct picture:

And what's more bizarre, I have 2 other Charts on another Sheet in the same workbook who doesn't cause any problems.

Could this be a problem with links, or the way I copy?

UPDATE

If I adjust the code as suggested below:

```<code> Source.Sheets(SheetName).ChartObjects(ShapeNr).Chart.CopyPicture
        Set NewSh = PPpres.Slides(SlideNr).Shapes.Paste
            With NewSh
                        .Top = Charts_Arr(i, 5)
                        .Left = Charts_Arr(i, 7)
                        .ScaleHeight Schaling, msoTrue
            End With
</code>```

I get this:

I'm doing something wrong with the Paste part of the code, I guess.
Tried other possibilities, always end up getting no images, or the one above.

FIXERSUPDATE

So I made/used a loophole. Couldn't find a way to paste the images directly into Powerpoint, So I pasted it into an excelsheet 'Temp' instead. And adjusted the Array, and that seemed to work. But I still would like to know how to do this directly in Powerpoint.

Thanks in advance for your insights!

答:
I couldn't find a PasteSpecial Option that could fix the issue.
CopyasPicture works, but I can't seem to figure out how to paste it directly into ppt. So I used a workaround. I created a 'Temp' Sheet, where I could paste the Chart as Picture in the right format, afterwards I could program it to paste the shape into Ppt. Not the cleanest way to solve the issue, but it works.</p>

Body:
The strangest thing is happening with my macro in Excel. It works like a charm, but when it has to copy 2 charts and paste into my powerpoint presentation, suddenly, the Chart isn't exactly the same.

My code:

Set Wb = Workbooks.Open("Path\WbName.xlsx", ReadOnly:=True, UpdateLinks:=0)

It opens 5 more workbooks... And then it goes through a loop, to copy all the Charts

Dim Charts_Arr As Variant
    Charts_Arr = Worksheets("Parameters").ListObjects("Parameters").DataBodyRange.Value

For i = LBound(Charts_Arr) To UBound(Charts_Arr)
    SourcePath = Charts_Arr(i, 8)
    SheetName = Charts_Arr(i, 4)
    ShapeNr = Charts_Arr(i, 2)
    SlideNr = Charts_Arr(i, 3)
    Schaling = Charts_Arr(i, 6)

    Set Source = Workbooks(SourcePath)
    Set PPpres = oPPTApp.ActivePresentation
    Set Sh = Source.Sheets(SheetName).Shapes(ShapeNr)

    Sh.Copy

    Set NewSh = PPpres.Slides(SlideNr).Shapes.PasteSpecial(ppPasteJPG)
    With NewSh
      .Top = Charts_Arr(i, 5)
      .Left = Charts_Arr(i, 7)
      .ScaleHeight Schaling, msoTrue
    End With

Next i

This goes perfectly. But when I take a look at the ppt-file, 2 charts are not exactly the same.

(TIP: Excel is Chartarea, not a shape - didn't know this at first)

When copy the picture manually, I get the correct picture:

And what's more bizarre, I have 2 other Charts on another Sheet in the same workbook who doesn't cause any problems.

Could this be a problem with links, or the way I copy?

UPDATE

If I adjust the code as suggested below:

 Source.Sheets(SheetName).ChartObjects(ShapeNr).Chart.CopyPicture
        Set NewSh = PPpres.Slides(SlideNr).Shapes.Paste
            With NewSh
                        .Top = Charts_Arr(i, 5)
                        .Left = Charts_Arr(i, 7)
                        .ScaleHeight Schaling, msoTrue
            End With

I get this:

I'm doing something wrong with the Paste part of the code, I guess.
Tried other possibilities, always end up getting no images, or the one above.

FIXERSUPDATE

So I made/used a loophole. Couldn't find a way to paste the images directly into Powerpoint, So I pasted it into an excelsheet 'Temp' instead. And adjusted the Array, and that seemed to work. But I still would like to know how to do this directly in Powerpoint.

Thanks in advance for your insights!


问:
Read CSV data and add it into dictionary
This is an empty Dictionary

```<code>d = {}
</code>```

This is the csv file data

```<code>M, Max, Sporting, Football, Cricket
M, Jack, Sporting, Cricket, Tennis
M, Kevin, Sporting, Cricket, Basketball
M, Ben, Sporting, Football, Rugby
</code>```

I tried to use the following code to append data from the csv to dictionary.

```<code>with open('example.csv', "r") as csvfile:
        csv_reader = csv.reader(csvfile)
        for row in csv_reader:
            if row:
                d.setdefault(row[0], {})[row[1]] = {row[2]: [row[3]]}
</code>```

But it gives me an error:

```<code>d.setdefault(row[0], {})[row[1]] = {row[2]: [row[3]]}
IndexError: list index out of range
</code>```

It there any way, i can add data from csv to the dictionary, in the form:

```<code>d = {'M': {'Max': {'Sporting': ['Football', 'Cricket']}, 'Jack': {'Sporting': ['Cricket', 'Tennis']}}}
</code>```

I am new to this so help me.

答:
You can use a nested collections.defaultdict tree and check if the rows are long enough:

```<code>from collections import defaultdict

def tree():
    return defaultdict(tree)

d = tree()
# ...
for row in csv_reader:
    if len(row) >= 3:
        d[row[0]][row[1]][row[2]] = row[3:]
</code>```

Body:
This is an empty Dictionary

d = {}

This is the csv file data

M, Max, Sporting, Football, Cricket
M, Jack, Sporting, Cricket, Tennis
M, Kevin, Sporting, Cricket, Basketball
M, Ben, Sporting, Football, Rugby

I tried to use the following code to append data from the csv to dictionary.

with open('example.csv', "r") as csvfile:
        csv_reader = csv.reader(csvfile)
        for row in csv_reader:
            if row:
                d.setdefault(row[0], {})[row[1]] = {row[2]: [row[3]]}

But it gives me an error:

d.setdefault(row[0], {})[row[1]] = {row[2]: [row[3]]}
IndexError: list index out of range

It there any way, i can add data from csv to the dictionary, in the form:

d = {'M': {'Max': {'Sporting': ['Football', 'Cricket']}, 'Jack': {'Sporting': ['Cricket', 'Tennis']}}}

I am new to this so help me.

Body:
You can use a nested collections.defaultdict tree and check if the rows are long enough:

from collections import defaultdict

def tree():
    return defaultdict(tree)

d = tree()
# ...
for row in csv_reader:
    if len(row) >= 3:
        d[row[0]][row[1]][row[2]] = row[3:]


问:
How to upgrade to Firefox Quantum in Ubuntu from existing firefox without adding ppa?
I don't want to add the official Mozilla ppa. Any other solution that does not require me to uninstall my current version (since I don't want to lose the placing and sequence of extensions and visual bookmark icons) is welcome. I am currently running version 56.</p>

答:
Ubuntu Community Help Wiki has a nice article about performing a manual installation. It boils down to:

Download Firefox for Linux on the official website.

Unpacking the archive in a directory.

Making a backup of the current ~/.mozilla directory.

Running firefox with firefox -no-remote -P mozilla-official.

The last command will make sure to run the new Firefox on a new profile (mozilla-official) and that you can run both the old version and the new version at the same time (-no-remote).


问:
Java: static abstract (again) - best practice how to work around
I theoretically understand the point why there is no abstract static in Java, as explained for instance in Why can't static methods be abstract in Java .

But how do I solve such a problem then?

My application uses files of a few types, which I want to assign static properties like a description of that file type (like "data file", the other being "config file", etc.).
Obviously, I would put that into a static String so that the description is accessible without instancing a file (useful for the GUI f.i.).
On the other hand, obviously all file types should have some common methods like getStatus(), which obviously I want to inherit from a common superclass MyFileType.

getDescription() would of course be abstract in the superclass.

Tried using a combination of a superclass and an interface, but similar problem: A static implementation of an abstract method is not allowed.

How would a Java guru solve this?
Is it really such a bad implementation that I want to create?

Many thanks,
Philipp

答:
annotations could be fine for your purpose.

```<code>@FileProperties(desc="data file")
public class DataFile extends XFile { ... }

FileProperties props = DataFile.class.getAnnotation(FileProperties.class);
String desc = props.desc();
</code>```

Accessing the info still requires reflection, however it's a little better than using static field/method.

Java compiler does not enforce that all subclasses are annotated as such. You can add your logic to the compiler (using annotation processing) but that's too complicated. It's ok to check it at runtime.

Update:

This is also possible:

```<code>@FileInfoClass ( DataFileInfo.class )
@public class DataFile
</code>```

Body:
annotations could be fine for your purpose.

@FileProperties(desc="data file")
public class DataFile extends XFile { ... }

FileProperties props = DataFile.class.getAnnotation(FileProperties.class);
String desc = props.desc();

Accessing the info still requires reflection, however it's a little better than using static field/method.

Java compiler does not enforce that all subclasses are annotated as such. You can add your logic to the compiler (using annotation processing) but that's too complicated. It's ok to check it at runtime.

Update:

This is also possible:

@FileInfoClass ( DataFileInfo.class )
@public class DataFile


问:
How to trigger login for IdentityServer4 without accessing secure page in the MVC app?
In the docs
http://docs.identityserver.io/en/release/quickstarts/3_interactive_login.html

it says "Trigger the authentication handshake by navigating to the protected controller action".  This would be by simply accessing any action in your MVC site with [Authorize].  After signin, this would redirect to the page they were trying to access, not to the page they last visited (which is good, expected behavior).

Great. But what about this scenario?

User is in some anonymous part of the site.

User clicks "Sign in" from the menu

User Signs in at Identity server

User is redirected back to the anonymous (un-secure) page they were last visiting (could be one of many) BUT is now signed in should she decide to later hit an [Authorize] page.

How do we initiate oidc Sign-in without hitting a secure page in MVC?

答:
That's just standard ASP.NET Core authentication - call

HttpContext.ChallengeAsync("name_of_oidc_scheme");

You also want to pass in an AuthenticationProperties object where you can set the URL where you want to end up after authentication.


问:
cbind on ggplotGrob objects fails with "Error in mmm < each : comparison of these types is not implemented"
This appears to be similar to an issue that @baptiste was trying to work around back in 2014. I am revisiting code I wrote back in June that involved creating three ggplotGrobs and combining them with a call to cbind. Now, this code fails with the message: "Error in mmm < each : comparison of these types is not implemented."

I thought that this would be specific to my particular application, but I was able to make a very simple, reproducible example. Even if the cbind is performed on two identical ggplotGrobs, this code still fails.

```<code>library(ggplot2)
library(gtable)

# Make some plots
pl1 <- ggplot(mtcars, aes(x = disp, y = mpg)) +
    geom_point()
pl2 <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, colour = Species)) +
    geom_point()

# Convert to grobs
pl1_grob <- ggplotGrob(pl1)
pl2_grob <- ggplotGrob(pl2)

# Bind them together -- Error!
combined_grob <- cbind(pl1_grob, pl2_grob)
</code>```

The error and relevant traceback are here:

```<code>> combined_grob <- cbind(pl1_grob, pl2_grob)
Error in mmm < each : comparison of these types is not implemented
> traceback()
8: comp(x_val, y_val)
7: unit(comp(x_val, y_val), x_unit)
6: compare_unit(x$heights, y$heights, pmax)
5: cbind_gtable(x, y, size = size)
4: f(init, x[[i]])
3: Reduce(function(x, y) cbind_gtable(x, y, size = size), gtables)
2: cbind(deparse.level, ...)
1: cbind(pl1_grob, pl2_grob)
</code>```

This code fails with R-3.4.2 on OS X 10.11.6 with grid_3.4.2, gtable_0.2.0, and ggplot2_2.2.1, AND with R-3.3.2 on Linux (compiled from source on Ubuntu 16.04) with grid_3.3.2, gtable_0.2.0, and ggplot2_2.2.1.

Before making the example above, I noticed that one of the vignettes in the "lemon" package ("gtable_show_lemonade") fails near the very end with the same error upon a cbind of two gtables. I confirmed this error by running the code for this vignette from source, which goes something like:

```<code>library(lemon)
edit(vignette('gtable_show_lemonade', package = 'lemon'))
# Then use whichever editor you opened to copy the temporary filename
# of the vignette source, and run this with source()
</code>```

The compiled vignette (with failed cbind) is here: https://cran.r-project.org/web/packages/lemon/vignettes/gtable_show_lemonade.html

The failure during vignette compilation was obtained using the aforementioned R-3.4.2 instance running on OS X 10.11 (El Capitan).

I would appreciate any help with working around this! Since I would like to use my Mac to generate the figures (better font situation), I'm hoping there is a way I can overload a function to fix this.

UPDATE:

This is "only" a problem if size = 'max', which is the default, is specified (or size = 'min'). I think that I can work around it using size = 'first' or size = 'last', which do not perform the offending height comparisons, but it is certainly not convenient that the default behavior doesn't work (and there are certain situations size = 'max' is useful).

答: I never managed to get this fixed in gtable so gridExtra has a modified version called gtable_cbind.

ContentLicense: CC BY-SA 4.0

Body:
This appears to be similar to an issue that @baptiste was trying to work around back in 2014. I am revisiting code I wrote back in June that involved creating three ggplotGrobs and combining them with a call to cbind. Now, this code fails with the message: "Error in mmm < each : comparison of these types is not implemented."

I thought that this would be specific to my particular application, but I was able to make a very simple, reproducible example. Even if the cbind is performed on two identical ggplotGrobs, this code still fails.

library(ggplot2)
library(gtable)

# Make some plots
pl1 <- ggplot(mtcars, aes(x = disp, y = mpg)) +
    geom_point()
pl2 <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, colour = Species)) +
    geom_point()

# Convert to grobs
pl1_grob <- ggplotGrob(pl1)
pl2_grob <- ggplotGrob(pl2)

# Bind them together -- Error!
combined_grob <- cbind(pl1_grob, pl2_grob)

The error and relevant traceback are here:

> combined_grob <- cbind(pl1_grob, pl2_grob)
Error in mmm < each : comparison of these types is not implemented
> traceback()
8: comp(x_val, y_val)
7: unit(comp(x_val, y_val), x_unit)
6: compare_unit(x$heights, y$heights, pmax)
5: cbind_gtable(x, y, size = size)
4: f(init, x[[i]])
3: Reduce(function(x, y) cbind_gtable(x, y, size = size), gtables)
2: cbind(deparse.level, ...)
1: cbind(pl1_grob, pl2_grob)

This code fails with R-3.4.2 on OS X 10.11.6 with grid_3.4.2, gtable_0.2.0, and ggplot2_2.2.1, AND with R-3.3.2 on Linux (compiled from source on Ubuntu 16.04) with grid_3.3.2, gtable_0.2.0, and ggplot2_2.2.1.

Before making the example above, I noticed that one of the vignettes in the "lemon" package ("gtable_show_lemonade") fails near the very end with the same error upon a cbind of two gtables. I confirmed this error by running the code for this vignette from source, which goes something like:

library(lemon)
edit(vignette('gtable_show_lemonade', package = 'lemon'))
# Then use whichever editor you opened to copy the temporary filename
# of the vignette source, and run this with source()

The compiled vignette (with failed cbind) is here: https://cran.r-project.org/web/packages/lemon/vignettes/gtable_show_lemonade.html

The failure during vignette compilation was obtained using the aforementioned R-3.4.2 instance running on OS X 10.11 (El Capitan).

I would appreciate any help with working around this! Since I would like to use my Mac to generate the figures (better font situation), I'm hoping there is a way I can overload a function to fix this.

UPDATE:

This is "only" a problem if size = 'max', which is the default, is specified (or size = 'min'). I think that I can work around it using size = 'first' or size = 'last', which do not perform the offending height comparisons, but it is certainly not convenient that the default behavior doesn't work (and there are certain situations size = 'max' is useful).


问:
curl via Jenkins only works sometimes
I want to upload some files via ftp using curl command inside Jenkins Pipeline. The command I use looks like this:

```<code>sh "curl --verbose -T my.file --proxytunnel --proxy http://${PROXY_USER}:${PROXY_PASS}@MYPROXY:MYPROXYPORT ftp://${AZURE_USER}:${AZURE_PASS}@MYSITE.ftp.azurewebsites.windows.net/site/wwwroot/"
</code>```

Sometimes, I click on "Build"-button in Jenkins 5 times in a row and all 5 builds are successful. Then, 10 minutes later, I click again the build-button and it fails 5 times in a row - without changing anything inside the Jenkins Job!

So it looks to me as if there is sometimes some kind of session cached and sometimes not. But I don't know which kind of session, because I set {http|https|ftp|no}_proxy, PROXY_USER and AZURE_USER.

Here is the error message when the build fails:

```<code>* About to connect() to proxy MYPROXY port 80 (#0)
*   Trying 1.2.3.4... connected
* Connected to MYPROXY (1.2.3.4) port 80 (#0)
* Establish HTTP proxy tunnel to MYSITE.ftp.azurewebsites.windows.net:21
* Proxy auth using Basic with user '****'
* Server auth using Basic with user 'MYUSER\****'
> CONNECT MYSITE.ftp.azurewebsites.windows.net:21 HTTP/1.1
> Host: MYSITE.ftp.azurewebsites.windows.net:21
> Proxy-Authorization: Basic xxx-xxx-xxx
> User-Agent: curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.27.1 zlib/1.2.3 libidn/1.18 libssh2/1.4.2
> Proxy-Connection: Keep-Alive
>
< HTTP/1.1 200 Connection Established
< Proxy-Agent: Zscaler/6.0
<
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed

  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0* Proxy replied OK to CONNECT request
< 220 Microsoft FTP Service
> USER MYUSER\****
< 331 Password required
> PASS ****
< 230 User logged in.
> PWD
< 257 "/" is current directory.
* Entry path is '/'
> CWD site
< 250 CWD command successful.
> CWD wwwroot
< 250 CWD command successful.
> EPSV
* Connect data stream passively
< 229 Entering Extended Passive Mode (|||10201|)
*   Trying 1.2.3.4... connected
* Connecting to MYSITE.ftp.azurewebsites.windows.net (1.2.3.4) port 80
* Establish HTTP proxy tunnel to MYSITE.ftp.azurewebsites.windows.net:10201
* Proxy auth using Basic with user '****'
* Server auth using Basic with user 'MYUSER\****'
> CONNECT MYSITE.ftp.azurewebsites.windows.net:10201 HTTP/1.1
> Host: MYSITE.ftp.azurewebsites.windows.net:10201
> Proxy-Authorization: Basic xxxxx
> User-Agent: curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.27.1 zlib/1.2.3 libidn/1.18 libssh2/1.4.2
> Proxy-Connection: Keep-Alive
>
< HTTP/1.1 200 Connection Established
< Proxy-Agent: Zscaler/6.0
<

  0     0    0     0    0     0      0      0 --:--:--  0:00:02 --:--:--     0* Proxy replied OK to CONNECT request
> TYPE I
< 200 Type set to I.
> STOR web.config
< 150 Opening BINARY mode data connection.
} [data not shown]

104   521    0     0  104   521      0    201  0:00:02  0:00:02 --:--:--   204* Remembering we are in dir "site/wwwroot/"

104   521    0     0  104   521      0    145  0:00:03  0:00:03 --:--:--   146
104   521    0     0  104   521      0    113  0:00:04  0:00:04 --:--:--   114
104   521    0     0  104   521      0     93  0:00:05  0:00:05 --:--:--    93
104   521    0     0  104   521      0     79  0:00:06  0:00:06 --:--:--   128
104   521    0     0  104   521      0     68  0:00:07  0:00:07 --:--:--     0
104   521    0     0  104   521      0     60  0:00:08  0:00:08 --:--:--     0
104   521    0     0  104   521      0     54  0:00:09  0:00:09 --:--:--     0
104   521    0     0  104   521      0     49  0:00:10  0:00:10 --:--:--     0
104   521    0     0  104   521      0     44  0:00:11  0:00:11 --:--:--     0
104   521    0     0  104   521      0     41  0:00:12  0:00:12 --:--:--     0
104   521    0     0  104   521      0     38  0:00:13  0:00:13 --:--:--     0
104   521    0     0  104   521      0     35  0:00:14  0:00:14 --:--:--     0
104   521    0     0  104   521      0     33  0:00:15  0:00:15 --:--:--     0
104   521    0     0  104   521      0     31  0:00:16  0:00:16 --:--:--     0
104   521    0     0  104   521      0     29  0:00:17  0:00:17 --:--:--     0
104   521    0     0  104   521      0     28  0:00:18  0:00:18 --:--:--     0
104   521    0     0  104   521      0     26  0:00:20  0:00:19  0:00:01     0
104   521    0     0  104   521      0     25  0:00:20  0:00:20 --:--:--     0
104   521    0     0  104   521      0     24  0:00:21  0:00:21 --:--:--     0
104   521    0     0  104   521      0     23  0:00:22  0:00:22 --:--:--     0
104   521    0     0  104   521      0     22  0:00:23  0:00:23 --:--:--     0
104   521    0     0  104   521      0     21  0:00:24  0:00:24 --:--:--     0
104   521    0     0  104   521      0     20  0:00:26  0:00:25  0:00:01     0
104   521    0     0  104   521      0     19  0:00:27  0:00:26  0:00:01     0
104   521    0     0  104   521      0     18  0:00:28  0:00:27  0:00:01     0
104   521    0     0  104   521      0     18  0:00:28  0:00:28 --:--:--     0
104   521    0     0  104   521      0     17  0:00:30  0:00:29  0:00:01     0
104   521    0     0  104   521      0     17  0:00:30  0:00:30 --:--:--     0
104   521    0     0  104   521      0     16  0:00:32  0:00:31  0:00:01     0
104   521    0     0  104   521      0     15  0:00:34  0:00:32  0:00:02     0
104   521    0     0  104   521      0     15  0:00:34  0:00:33  0:00:01     0
104   521    0     0  104   521      0     15  0:00:34  0:00:34 --:--:--     0
104   521    0     0  104   521      0     14  0:00:37  0:00:35  0:00:02     0
104   521    0     0  104   521      0     14  0:00:37  0:00:36  0:00:01     0
104   521    0     0  104   521      0     13  0:00:40  0:00:37  0:00:03     0
104   521    0     0  104   521      0     13  0:00:40  0:00:38  0:00:02     0
104   521    0     0  104   521      0     13  0:00:40  0:00:39  0:00:01     0
104   521    0     0  104   521      0     12  0:00:43  0:00:40  0:00:03     0< 425 Data channel timed out.
* server did not report OK, got 425

104   521    0     0  104   521      0     12  0:00:43  0:00:40  0:00:03     0* Connection #0 to host MYPROXY left intact

curl: (18) server did not report OK, got 425
> QUIT
< 221 Goodbye.
* Closing connection #0
</code>```

Do you have any idea?

答: Solution was that I had to enter a different proxy server. As I learned, my company has different proxies: some for "normal" users and some for servers. The proxy used by the servers don't require basic auth. With this proxy, it works now.</p>

Title: curl via Jenkins only works sometimes

Body:
I want to upload some files via ftp using curl command inside Jenkins Pipeline. The command I use looks like this:

sh "curl --verbose -T my.file --proxytunnel --proxy http://${PROXY_USER}:${PROXY_PASS}@MYPROXY:MYPROXYPORT ftp://${AZURE_USER}:${AZURE_PASS}@MYSITE.ftp.azurewebsites.windows.net/site/wwwroot/"

Sometimes, I click on "Build"-button in Jenkins 5 times in a row and all 5 builds are successful. Then, 10 minutes later, I click again the build-button and it fails 5 times in a row - without changing anything inside the Jenkins Job!

So it looks to me as if there is sometimes some kind of session cached and sometimes not. But I don't know which kind of session, because I set {http|https|ftp|no}_proxy, PROXY_USER and AZURE_USER.

Here is the error message when the build fails:

* About to connect() to proxy MYPROXY port 80 (#0)
*   Trying 1.2.3.4... connected
* Connected to MYPROXY (1.2.3.4) port 80 (#0)
* Establish HTTP proxy tunnel to MYSITE.ftp.azurewebsites.windows.net:21
* Proxy auth using Basic with user '****'
* Server auth using Basic with user 'MYUSER\****'
> CONNECT MYSITE.ftp.azurewebsites.windows.net:21 HTTP/1.1
> Host: MYSITE.ftp.azurewebsites.windows.net:21
> Proxy-Authorization: Basic xxx-xxx-xxx
> User-Agent: curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.27.1 zlib/1.2.3 libidn/1.18 libssh2/1.4.2
> Proxy-Connection: Keep-Alive
>
< HTTP/1.1 200 Connection Established
< Proxy-Agent: Zscaler/6.0
<
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed

  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0* Proxy replied OK to CONNECT request
< 220 Microsoft FTP Service
> USER MYUSER\****
< 331 Password required
> PASS ****
< 230 User logged in.
> PWD
< 257 "/" is current directory.
* Entry path is '/'
> CWD site
< 250 CWD command successful.
> CWD wwwroot
< 250 CWD command successful.
> EPSV
* Connect data stream passively
< 229 Entering Extended Passive Mode (|||10201|)
*   Trying 1.2.3.4... connected
* Connecting to MYSITE.ftp.azurewebsites.windows.net (1.2.3.4) port 80
* Establish HTTP proxy tunnel to MYSITE.ftp.azurewebsites.windows.net:10201
* Proxy auth using Basic with user '****'
* Server auth using Basic with user 'MYUSER\****'
> CONNECT MYSITE.ftp.azurewebsites.windows.net:10201 HTTP/1.1
> Host: MYSITE.ftp.azurewebsites.windows.net:10201
> Proxy-Authorization: Basic xxxxx
> User-Agent: curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.27.1 zlib/1.2.3 libidn/1.18 libssh2/1.4.2
> Proxy-Connection: Keep-Alive
>
< HTTP/1.1 200 Connection Established
< Proxy-Agent: Zscaler/6.0
<

  0     0    0     0    0     0      0      0 --:--:--  0:00:02 --:--:--     0* Proxy replied OK to CONNECT request
> TYPE I
< 200 Type set to I.
> STOR web.config
< 150 Opening BINARY mode data connection.
} [data not shown]

104   521    0     0  104   521      0    201  0:00:02  0:00:02 --:--:--   204* Remembering we are in dir "site/wwwroot/"

104   521    0     0  104   521      0    145  0:00:03  0:00:03 --:--:--   146
104   521    0     0  104   521      0    113  0:00:04  0:00:04 --:--:--   114
104   521    0     0  104   521      0     93  0:00:05  0:00:05 --:--:--    93
104   521    0     0  104   521      0     79  0:00:06  0:00:06 --:--:--   128
104   521    0     0  104   521      0     68  0:00:07  0:00:07 --:--:--     0
104   521    0     0  104   521      0     60  0:00:08  0:00:08 --:--:--     0
104   521    0     0  104   521      0     54  0:00:09  0:00:09 --:--:--     0
104   521    0     0  104   521      0     49  0:00:10  0:00:10 --:--:--     0
104   521    0     0  104   521      0     44  0:00:11  0:00:11 --:--:--     0
104   521    0     0  104   521      0     41  0:00:12  0:00:12 --:--:--     0
104   521    0     0  104   521      0     38  0:00:13  0:00:13 --:--:--     0
104   521    0     0  104   521      0     35  0:00:14  0:00:14 --:--:--     0
104   521    0     0  104   521      0     33  0:00:15  0:00:15 --:--:--     0
104   521    0     0  104   521      0     31  0:00:16  0:00:16 --:--:--     0
104   521    0     0  104   521      0     29  0:00:17  0:00:17 --:--:--     0
104   521    0     0  104   521      0     28  0:00:18  0:00:18 --:--:--     0
104   521    0     0  104   521      0     26  0:00:20  0:00:19  0:00:01     0
104   521    0     0  104   521      0     25  0:00:20  0:00:20 --:--:--     0
104   521    0     0  104   521      0     24  0:00:21  0:00:21 --:--:--     0
104   521    0     0  104   521      0     23  0:00:22  0:00:22 --:--:--     0
104   521    0     0  104   521      0     22  0:00:23  0:00:23 --:--:--     0
104   521    0     0  104   521      0     21  0:00:24  0:00:24 --:--:--     0
104   521    0     0  104   521      0     20  0:00:26  0:00:25  0:00:01     0
104   521    0     0  104   521      0     19  0:00:27  0:00:26  0:00:01     0
104   521    0     0  104   521      0     18  0:00:28  0:00:27  0:00:01     0
104   521    0     0  104   521      0     18  0:00:28  0:00:28 --:--:--     0
104   521    0     0  104   521      0     17  0:00:30  0:00:29  0:00:01     0
104   521    0     0  104   521      0     17  0:00:30  0:00:30 --:--:--     0
104   521    0     0  104   521      0     16  0:00:32  0:00:31  0:00:01     0
104   521    0     0  104   521      0     15  0:00:34  0:00:32  0:00:02     0
104   521    0     0  104   521      0     15  0:00:34  0:00:33  0:00:01     0
104   521    0     0  104   521      0     15  0:00:34  0:00:34 --:--:--     0
104   521    0     0  104   521      0     14  0:00:37  0:00:35  0:00:02     0
104   521    0     0  104   521      0     14  0:00:37  0:00:36  0:00:01     0
104   521    0     0  104   521      0     13  0:00:40  0:00:37  0:00:03     0
104   521    0     0  104   521      0     13  0:00:40  0:00:38  0:00:02     0
104   521    0     0  104   521      0     13  0:00:40  0:00:39  0:00:01     0
104   521    0     0  104   521      0     12  0:00:43  0:00:40  0:00:03     0< 425 Data channel timed out.
* server did not report OK, got 425

104   521    0     0  104   521      0     12  0:00:43  0:00:40  0:00:03     0* Connection #0 to host MYPROXY left intact

curl: (18) server did not report OK, got 425
> QUIT
< 221 Goodbye.
* Closing connection #0

Do you have any idea?


问:
Ansible: "sudo: a password is required\r\n"
quick question

I have setup an Ubuntu server with a user named test. I copy the authorized_keys to it, I can ssh no problem.
If I do $ ansible -m ping ubu1, no problem  I get a response

```<code>    <i><p>ubu1 | SUCCESS => {
        <br>"changed": false,
        <br>"ping": "pong"
    <br>}</i>
</code>```

What I dont get is this, If I do

$ ansible-playbook -vvvv Playbooks/htopInstall.yml

```<code>fatal: [ubu1]: FAILED! => {"changed": false, "failed": true, "invocation": {"module_name": "setup"}, "module_stderr": "OpenSSH_7.2p2 Ubuntu-4ubuntu2.1, OpenSSL 1.0.2g-fips  1 Mar 2016\r\ndebug1: Reading configuration data /etc/ssh/ssh_config\r\ndebug1: /etc/ssh/ssh_config line 19: Applying options for *\r\ndebug1: auto-mux: Trying existing master\r\ndebug2: fd 3 setting O_NONBLOCK\r\ndebug2: mux_client_hello_exchange: master version 4\r\ndebug3: mux_client_forwards: request forwardings: 0 local, 0 remote\r\ndebug3: mux_client_request_session: entering\r\ndebug3: mux_client_request_alive: entering\r\ndebug3: mux_client_request_alive: done pid = 6109\r\ndebug3: mux_client_request_session: session request sent\r\ndebug1: mux_client_request_session: master session id: 2\r\ndebug3: mux_client_read_packet: read header failed: Broken pipe\r\ndebug2: Received exit status from master 1\r\nShared connection to 192.168.1.112 closed.\r\n", "module_stdout": "sudo: a password is required\r\n", "msg": "MODULE FAILURE", "parsed": false}
</code>```

If I do $ ansible-playbook --ask-sudo-pass Playbooks/htopInstall.yml, then it ask my user password and the play is a success.

If I rename the authorized_keys it tells me I "Failed to connect to the host via ssh." which is ok.
What I dont understand is why is it asking for a sudo password. I definetly missed something along the way.

my ansible.cfg file looks like this

```<code>[defaults]
nocows = 1
inventory = ./Playbooks/hosts
remote_user = test
private_key_file = /home/test/.ssh/id_ubu
host_key_checking = false
</code>```

my hosts file looks like this

```<code>[servers]
ubu1 ansible_ssh_host=192.168.1.112 ansible_ssh_user=test
</code>```

答:
I solved this exact error sudo: a password is required\n which I got when running my playbook with become: true but somewhere in a task delegating to localhost, something like this:

```<code>uri:
  url: "{{ some_url }}"
  return_content: yes
  status_code: 200
delegate_to: 127.0.0.1
</code>```

If I understood correctly, the become: true causes Ansible to log into the remote host as my user and then use sudo in order to execute all commands on the remote host as root. Now when delegating to 127.0.0.1, sudo is also executed and as it happens that on my localhost a password is expected when using sudo.

For me the solution was simply to remove the delegate_to, which was not actually needed in that particular use case.

Body:
quick question

I have setup an Ubuntu server with a user named test. I copy the authorized_keys to it, I can ssh no problem.
If I do $ ansible -m ping ubu1, no problem  I get a response

ubu1 | SUCCESS => {

"changed": false,

"ping": "pong"

}

What I dont get is this, If I do

$ ansible-playbook -vvvv Playbooks/htopInstall.yml

fatal: [ubu1]: FAILED! => {"changed": false, "failed": true, "invocation": {"module_name": "setup"}, "module_stderr": "OpenSSH_7.2p2 Ubuntu-4ubuntu2.1, OpenSSL 1.0.2g-fips  1 Mar 2016\r\ndebug1: Reading configuration data /etc/ssh/ssh_config\r\ndebug1: /etc/ssh/ssh_config line 19: Applying options for *\r\ndebug1: auto-mux: Trying existing master\r\ndebug2: fd 3 setting O_NONBLOCK\r\ndebug2: mux_client_hello_exchange: master version 4\r\ndebug3: mux_client_forwards: request forwardings: 0 local, 0 remote\r\ndebug3: mux_client_request_session: entering\r\ndebug3: mux_client_request_alive: entering\r\ndebug3: mux_client_request_alive: done pid = 6109\r\ndebug3: mux_client_request_session: session request sent\r\ndebug1: mux_client_request_session: master session id: 2\r\ndebug3: mux_client_read_packet: read header failed: Broken pipe\r\ndebug2: Received exit status from master 1\r\nShared connection to 192.168.1.112 closed.\r\n", "module_stdout": "sudo: a password is required\r\n", "msg": "MODULE FAILURE", "parsed": false}

If I do $ ansible-playbook --ask-sudo-pass Playbooks/htopInstall.yml, then it ask my user password and the play is a success.

If I rename the authorized_keys it tells me I "Failed to connect to the host via ssh." which is ok.
What I dont understand is why is it asking for a sudo password. I definetly missed something along the way.

my ansible.cfg file looks like this

[defaults]
nocows = 1
inventory = ./Playbooks/hosts
remote_user = test
private_key_file = /home/test/.ssh/id_ubu
host_key_checking = false

my hosts file looks like this

[servers]
ubu1 ansible_ssh_host=192.168.1.112 ansible_ssh_user=test

Body:
I solved this exact error sudo: a password is required\n which I got when running my playbook with become: true but somewhere in a task delegating to localhost, something like this:

uri:
  url: "{{ some_url }}"
  return_content: yes
  status_code: 200
delegate_to: 127.0.0.1

If I understood correctly, the become: true causes Ansible to log into the remote host as my user and then use sudo in order to execute all commands on the remote host as root. Now when delegating to 127.0.0.1, sudo is also executed and as it happens that on my localhost a password is expected when using sudo.

For me the solution was simply to remove the delegate_to, which was not actually needed in that particular use case.


问:
Import a local module in Python - ImportError: Not module named *
I've read about the workarounds (adding to sys.path or more robust solutions), but other libraries don't use such workarounds (for example, this file in tf). I don't expect I really have to either, I want to be able to import on a single line and run - I must be missing something!

To get specific, I have something like the following directory:

```<code>project/
  foo/
  src/
    __init__.py
    bar.py
    foo/
      __init__.py
      boo.py
</code>```

I would expect that in bar.py I could simply write something like from foo import boo, however my IDE, PyCharm, sees this as an error.

So, trusting my IDE, I try from src.foo import boo but this results in an ImportError, as tested:

```<code>Traceback (most recent call last):
  File "bar.py", line 1, in <module>
    from src.foo import boo
ImportError: No module named 'src'
</code>```

I verified that the src folder was at sys.path[0], however inserting __file__ to it did seem to resolve the issue - I still do not want to use this workaround, but will as a last resort.

I have tried a million other tricks to get this to work without success.

How can I import from a local module without using one of the workarounds?

答:
This problem is caused by a bug in PyCharm. The initial instinct to use from foo import bar was correct and will work as intended despite PyCharm's supposed error. The fact that it claimed src was a module should have set off alarms in my head.

The PyCharm warning can be safely ignored and the code can be run.

In order to stop PyCharm from misleading us in the future, we will have have to disable the 'Unresolved references' inspection. This can be done by searching for 'unresolved references' in Settings and disabling the Python inspection.

Body:
I've read about the workarounds (adding to sys.path or more robust solutions), but other libraries don't use such workarounds (for example, this file in tf). I don't expect I really have to either, I want to be able to import on a single line and run - I must be missing something!

To get specific, I have something like the following directory:

project/
  foo/
  src/
    __init__.py
    bar.py
    foo/
      __init__.py
      boo.py

I would expect that in bar.py I could simply write something like from foo import boo, however my IDE, PyCharm, sees this as an error.

So, trusting my IDE, I try from src.foo import boo but this results in an ImportError, as tested:

Traceback (most recent call last):
  File "bar.py", line 1, in <module>
    from src.foo import boo
ImportError: No module named 'src'

I verified that the src folder was at sys.path[0], however inserting __file__ to it did seem to resolve the issue - I still do not want to use this workaround, but will as a last resort.

I have tried a million other tricks to get this to work without success.

How can I import from a local module without using one of the workarounds?


问:
Difference between x.toString() and x+""
Back in college one of my profs. taught us to just do x + "" as a quick conversion from basic types to strings.

I don't remember which class it was in I had him for some Java and C++ courses(I haven't used either for some time now), but I use it in C#/.Net now which is what I'm primarily developing in lately.

Is there an advantage to using .toString() over +"" for basic types such at int, decimal, float...?
What cases would .toString() be better?

Note:I was shown .toString() as well, that prof just recommended +"" because it was shorter and I have just done that since then without questioning it.

答:
In Java,

In addition to working with primitive types, x+"" also works with null. Where x.toString() throws a NullPointerException, x+"" returns "null". Whether that is better or not is up to you, but it is a difference.


答: Change "for column in csv_reader:" to "for row in csv_reader:"</p>

Title: Read CSV data and add it into dictionary


问:
theme font doesn't apply to paragraph
Okay, so I am just a beginner in HTML and CSS. I tried to apply wordpress themes font to everything else on the site. The font is "Roboto Condensed", sans-serif; . I even created a custom menu which works perfectly with this font, but when I try to apply it to paragraphs, like product descriptions, it just doesn't work. I tried to edit the style.css file with

* {
font-family: "Roboto Condensed", sans-serif;
}

or

```<code>body {font-family: "Roboto Condensed", sans-serif;}
</code>```

Can some one please tell me maybe I am doing something wrong?

答:
Append !important

```<code>body {font-family: "Roboto Condensed", sans-serif !important;}
</code>```

Title: theme font doesn't apply to paragraph

Body:
Okay, so I am just a beginner in HTML and CSS. I tried to apply wordpress themes font to everything else on the site. The font is "Roboto Condensed", sans-serif; . I even created a custom menu which works perfectly with this font, but when I try to apply it to paragraphs, like product descriptions, it just doesn't work. I tried to edit the style.css file with

* {
font-family: "Roboto Condensed", sans-serif;
}

or

body {font-family: "Roboto Condensed", sans-serif;}

Can some one please tell me maybe I am doing something wrong?

Body:
Append !important

body {font-family: "Roboto Condensed", sans-serif !important;}