问:
workflow in Odoo 9
I have created a module with field state which had the following attributes "draft", "open", "paid" , "cancel". In the xml, I have a button confirm and when the user click on this button, the state must change from "draft" to "open". However, the codes are not working, the state is unchanged. Any clue ?
Thanks

Below are my codes:

(1) module.py

```<code>'state': fields.selection([('draft', "New"), ('open', "Awaiting Payments"), ('paid', "Paid"), ('cancel', "Cancelled")], 'Status', default='draft', track_visibility='onchange'),

def action_draft(self, cr, uid, ids, context=None):
        return self.write(cr, uid, ids, {'state':'draft'})

def action_open(self , cr, uid, ids, context=None):
        return self.write(cr, uid, ids, {'state':'open'})

def action_paid(self , cr, uid, ids, context=None):
        return self.write(cr, uid, ids, {'state':'paid'})

def action_cancel(self , cr, uid, ids, context=None):
        return self.write(cr, uid, ids, {'state':'cancel'})
</code>```

(2) module.xml

```<code><header>

            <button name="button_confirm" string="Confirm Application"  states="draft" class="oe_highlight" type="action"/>

            <button name="button_email"  string="Send by Email" states="open" class="oe_highlight" type="action"/>

            <button name="button_print" string="Print" states="open" class="oe_highlight" type="action"/>

            <button name="%(test9_receipt_action)d" string="Register Payment" states="open" class="oe_highlight" type="action"/>

            <button name="button_refund" type="action" string="Refund Invoice" states="paid" class="oe_highlight"/>

            <button name="button_cancel" type="action" string="Cancel Application" states="draft,open,paid" class="oe_highlight"/>

            <field name="state" widget="statusbar" statusbar_visible="draft,open,paid,cancel" statusbar_colors='{"confirmed":"blue"}'/>

</header>
</code>```

(3) workflow.xml

```<code><openerp>
    <data>
        <record model="workflow" id="wkf_land2">
            <field name="name">m.wkf.land2</field>
            <field name="osv">m.land2</field>
            <field name="on_create">True</field>
        </record>

        <!-- Draft-->

        <record model="workflow.activity" id="land_draft">
            <field name="name">draft</field>
            <field name="wkf_id" ref="wkf_land2"/>
            <field name="flow_start" eval="True"/>
        </record>

        <!-- Awaiting Payments-->
        <record model="workflow.activity" id="land_open">
            <field name="name">open</field>
            <field name="wkf_id" ref="wkf_land2"/>
            <field name="kind">function</field>
            <field name="action">write({'state':'open'})</field>
        </record>

        <!--Paid-->
        <record model="workflow.activity" id="land_paid">
            <field name="name">paid</field>
            <field name="wkf_id" ref="wkf_land2"/>
            <field name="kind">function</field>
            <field name="action">write({'state':'paid'})</field>
            <field name="flow_stop">True</field>
        </record>

        <!--Cancel-->
        <record model="workflow.activity" id="land_cancel">
            <field name="name">cancel</field>
            <field name="wkf_id" ref="wkf_land2"/>
            <field name="kind">function</field>
            <field name="action">write({'state':'cancel'})</field>
            <field name="flow_stop">True</field>
        </record>

        <!-- WORKFLOW TRANSITION -->

        <record model="workflow.transition" id="land_draft_to_open">
            <field name="act_from" ref="land_draft"/>
            <field name="act_to" ref="land_open"/>
            <field name="condition">True</field>
            <field name="signal">button_confirm</field>
        </record>

        <record model="workflow.transition" id="land_open_to_paid">
            <field name="act_from" ref="land_open"/>
            <field name="act_to" ref="land_paid"/>
            <field name="condition">True</field>
            <field name="signal">button_register</field>
        </record>

        <record model="workflow.transition" id="land_paid_to_cancel">
            <field name="act_from" ref="land_paid"/>
            <field name="act_to" ref="land_cancel"/>
            <field name="signal">button_cancel</field>
            <field name="condition">True</field>
        </record>

        <record model="workflow.transition" id="land_draft_to_cancel">
            <field name="act_from" ref="land_draft"/>
            <field name="act_to" ref="land_cancel"/>
            <field name="signal">button_cancel</field>
            <field name="condition">True</field>
        </record>
        <record model="workflow.transition" id="land_open_to_cancel">
            <field name="act_from" ref="land_open"/>
            <field name="act_to" ref="land_cancel"/>
            <field name="signal">button_cancel</field>
            <field name="condition">True</field>
        </record>
    </data>
</openerp>
</code>```

答:
The name of the button should be the same name as your function.

Example:

```<code>...button name="action_cancel" type="action" string="Cancel Applicat...
</code>```

and

```<code>def action_cancel(self , cr, uid, ids, context=None):
    return self.write(cr, uid, ids, {'state':'cancel'})
</code>```

Title: workflow in Odoo 9

Body:
I have created a module with field state which had the following attributes "draft", "open", "paid" , "cancel". In the xml, I have a button confirm and when the user click on this button, the state must change from "draft" to "open". However, the codes are not working, the state is unchanged. Any clue ?
Thanks

Below are my codes:

(1) module.py

'state': fields.selection([('draft', "New"), ('open', "Awaiting Payments"), ('paid', "Paid"), ('cancel', "Cancelled")], 'Status', default='draft', track_visibility='onchange'),

def action_draft(self, cr, uid, ids, context=None):
        return self.write(cr, uid, ids, {'state':'draft'})

def action_open(self , cr, uid, ids, context=None):
        return self.write(cr, uid, ids, {'state':'open'})

def action_paid(self , cr, uid, ids, context=None):
        return self.write(cr, uid, ids, {'state':'paid'})

def action_cancel(self , cr, uid, ids, context=None):
        return self.write(cr, uid, ids, {'state':'cancel'})

(2) module.xml

            <button name="button_confirm" string="Confirm Application"  states="draft" class="oe_highlight" type="action"/>

            <button name="button_email"  string="Send by Email" states="open" class="oe_highlight" type="action"/>

            <button name="button_print" string="Print" states="open" class="oe_highlight" type="action"/>

            <button name="%(test9_receipt_action)d" string="Register Payment" states="open" class="oe_highlight" type="action"/>

            <button name="button_refund" type="action" string="Refund Invoice" states="paid" class="oe_highlight"/>

            <button name="button_cancel" type="action" string="Cancel Application" states="draft,open,paid" class="oe_highlight"/>

            <field name="state" widget="statusbar" statusbar_visible="draft,open,paid,cancel" statusbar_colors='{"confirmed":"blue"}'/>

(3) workflow.xml

<openerp>
    <data>
        <record model="workflow" id="wkf_land2">
            <field name="name">m.wkf.land2</field>
            <field name="osv">m.land2</field>
            <field name="on_create">True</field>
        </record>

        <record model="workflow.activity" id="land_draft">
            <field name="name">draft</field>
            <field name="wkf_id" ref="wkf_land2"/>
            <field name="flow_start" eval="True"/>
        </record>

        <record model="workflow.activity" id="land_open">
            <field name="name">open</field>
            <field name="wkf_id" ref="wkf_land2"/>
            <field name="kind">function</field>
            <field name="action">write({'state':'open'})</field>
        </record>

        <record model="workflow.activity" id="land_paid">
            <field name="name">paid</field>
            <field name="wkf_id" ref="wkf_land2"/>
            <field name="kind">function</field>
            <field name="action">write({'state':'paid'})</field>
            <field name="flow_stop">True</field>
        </record>

        <record model="workflow.activity" id="land_cancel">
            <field name="name">cancel</field>
            <field name="wkf_id" ref="wkf_land2"/>
            <field name="kind">function</field>
            <field name="action">write({'state':'cancel'})</field>
            <field name="flow_stop">True</field>
        </record>

        <record model="workflow.transition" id="land_draft_to_open">
            <field name="act_from" ref="land_draft"/>
            <field name="act_to" ref="land_open"/>
            <field name="condition">True</field>
            <field name="signal">button_confirm</field>
        </record>

        <record model="workflow.transition" id="land_open_to_paid">
            <field name="act_from" ref="land_open"/>
            <field name="act_to" ref="land_paid"/>
            <field name="condition">True</field>
            <field name="signal">button_register</field>
        </record>

        <record model="workflow.transition" id="land_paid_to_cancel">
            <field name="act_from" ref="land_paid"/>
            <field name="act_to" ref="land_cancel"/>
            <field name="signal">button_cancel</field>
            <field name="condition">True</field>
        </record>

        <record model="workflow.transition" id="land_draft_to_cancel">
            <field name="act_from" ref="land_draft"/>
            <field name="act_to" ref="land_cancel"/>
            <field name="signal">button_cancel</field>
            <field name="condition">True</field>
        </record>
        <record model="workflow.transition" id="land_open_to_cancel">
            <field name="act_from" ref="land_open"/>
            <field name="act_to" ref="land_cancel"/>
            <field name="signal">button_cancel</field>
            <field name="condition">True</field>
        </record>
    </data>
</openerp>

Body:
The name of the button should be the same name as your function.

Example:

...button name="action_cancel" type="action" string="Cancel Applicat...

and

def action_cancel(self , cr, uid, ids, context=None):
    return self.write(cr, uid, ids, {'state':'cancel'})


来源: stackexchange

问:
Can't get elements from json response
I can't get to see on my table elements from my json response, received from get method. Here it is my html:

```<code><div ng-controller="EstadisticaController" data-ng-init="init()">
  <div class="jumbotron text-center">
      <h1>Historico</h1>
      <div class="table-responsive">
        <table class="table table-striped">
          <tr ng-repeat="a in acontecimiento">
            <td>{{ a.campo }}</td>
          </tr>
        </table>
      </div>
  </div>
</div>
</code>```

the controller:

```<code>angular.module('EstadisticaCtrl', ['AcontecimientoService'])
  .controller('EstadisticaController', function($scope, Acontecimiento) {
    $scope.init = function(res) {
      Acontecimiento.get($scope.acontecimiento);
    };
  });
</code>```

the service:

```<code>angular.module('AcontecimientoService', [])
  .factory('Acontecimiento', function($http) {
    return {
        // call to get all nerds
        get : function() {
            return $http.get('/api/acontecimiento');
        }
    }
});
</code>```

and finally the get method:

```<code>var Acontecimiento = require('./models/acontecimiento');
 module.exports = function(app) {
   app.get('/api/acontecimiento', function(req, res) {
       Acontecimiento.find(function(err, acontecimiento) {
           if (err)
               res.send(err);
           res.json(acontecimiento); // return all nerds in JSON format
       });
   });
}
</code>```

example of the returned json:

```<code>[{"_id":"593567528656c9b107d4e6ac","campo":"TRES MARIAS","titular":"RUBEN CARLOS P.","tipo":"CONTAR STOCK ACTUAL","__v":0,"terneros":0,"terneras":0,"vaquillonas":0,"novillitos":0,"toros":0,"vacas":0,"brucelosis":12,"fecha":"2017-06-08T03:00:00.000Z"},{"_id":"593567c08656c9b107d4e6af","campo":"TRES MARIAS","titular":"VICTOR HUGO P.","tipo":"TRANSLADO","__v":0,"terneros":0,"terneras":0,"vaquillonas":0,"novillitos":23,"toros":0,"vacas":0,"brucelosis":0,"fecha":"2017-06-15T03:00:00.000Z"},{"_id":"593568c98656c9b107d4e6b0","campo":"TRES MARIAS","titular":"RUBEN CARLOS P.","tipo":"TRANSLADO","__v":0,"terneros":0,"terneras":0,"vaquillonas":0,"novillitos":0,"toros":0,"vacas":0,"brucelosis":2,"fecha":"2017-06-08T03:00:00.000Z"},{"_id":"593568f28656c9b107d4e6b1","campo":"GUARANIMINI","titular":"RUBEN CARLOS P.","tipo":"VENTA","__v":0,"terneros":0,"terneras":0,"vaquillonas":0,"novillitos":0,"toros":0,"vacas":0,"brucelosis":2,"fecha":"2017-06-03T03:00:00.000Z"},{"_id":"593569348656c9b107d4e6b2","campo":"GUARANIMINI","titular":"RUBEN CARLOS P.","tipo":"MUERTE","__v":0,"terneros":0,"terneras":0,"vaquillonas":0,"novillitos":0,"toros":0,"vacas":0,"brucelosis":2,"fecha":"2017-06-03T03:00:00.000Z"},{"_id":"59356adb8656c9b107d4e6b7","campo":"ESPADAÑAL","titular":"VICTOR HUGO P.","tipo":"TRANSLADO","__v":0,"terneros":0,"terneras":0,"vaquillonas":0,"novillitos":0,"toros":0,"vacas":12,"brucelosis":0,"fecha":"2017-06-05T03:00:00.000Z"},{"_id":"59356bf98656c9b107d4e6b9","campo":"GUARANIMINI","titular":"RUBEN CARLOS P.","tipo":"VACUNA","__v":0,"terneros":34,"terneras":0,"vaquillonas":0,"novillitos":0,"toros":0,"vacas":0,"brucelosis":null,"fecha":"1994-03-12T03:00:00.000Z"},{"_id":"59356c338656c9b107d4e6bb","campo":"GUARANIMINI","titular":"RUBEN CARLOS P.","tipo":"VACUNA","__v":0,"terneros":0,"terneras":0,"vaquillonas":3232,"novillitos":0,"toros":0,"vacas":0,"brucelosis":0,"fecha":"1994-03-12T03:00:00.000Z"},{"_id":"59356fc6f22ca186088a38d7","campo":"GUARANIMINI","titular":"VICTOR HUGO P.","tipo":"VACUNA","__v":0,"terneros":0,"terneras":0,"vaquillonas":0,"novillitos":0,"toros":0,"vacas":0,"brucelosis":1,"fecha":"2017-06-05T03:00:00.000Z"},{"_id":"59356ff0f22ca186088a38d9","campo":"TRES MARIAS","titular":"RUBEN CARLOS P.","tipo":"VACUNA","__v":0,"terneros":0,"terneras":0,"vaquillonas":0,"novillitos":0,"toros":0,"vacas":0,"brucelosis":0,"fecha":"2017-06-02T03:00:00.000Z"},{"_id":"59357009f22ca186088a38dc","campo":"GUARANIMINI","titular":"RUBEN CARLOS P.","tipo":"VENTA","__v":0,"terneros":0,"terneras":0,"vaquillonas":0,"novillitos":0,"toros":0,"vacas":1,"brucelosis":0,"fecha":"2017-06-05T03:00:00.000Z"},{"_id":"593581761587ccdb084f8de5","campo":"TRES MARIAS","titular":"VICTOR HUGO P.","tipo":"MUERTE","__v":0,"terneros":55555,"terneras":0,"vaquillonas":0,"novillitos":0,"toros":0,"vacas":0,"brucelosis":0,"fecha":"2017-06-03T03:00:00.000Z"}]
</code>```

答:
Here it is how I solved the problem, I needed to get the response and assign it to my scope. This is what my new controller looks like:</p>

```<code>angular.module('EstadisticaCtrl', ['AcontecimientoService'])
  .controller('EstadisticaController', function($scope, Acontecimiento) {
    $scope.init = function(res) {
      Acontecimiento
        .get($scope.acontecimiento)
        .then(function(res) {
          $scope.acontecimiento = res.data;
        }, function(error) {
          console.log('Error: ' + res.data);
        });
    };
  });
</code>```

ContentLicense: CC BY-SA 3.0

Title: Can't get elements from json response

Body:
I can't get to see on my table elements from my json response, received from get method. Here it is my html:

Historico

            {{ a.campo }}

the controller:

angular.module('EstadisticaCtrl', ['AcontecimientoService'])
  .controller('EstadisticaController', function($scope, Acontecimiento) {
    $scope.init = function(res) {
      Acontecimiento.get($scope.acontecimiento);
    };
  });

the service:

angular.module('AcontecimientoService', [])
  .factory('Acontecimiento', function($http) {
    return {
        // call to get all nerds
        get : function() {
            return $http.get('/api/acontecimiento');
        }
    }
});

and finally the get method:

var Acontecimiento = require('./models/acontecimiento');
 module.exports = function(app) {
   app.get('/api/acontecimiento', function(req, res) {
       Acontecimiento.find(function(err, acontecimiento) {
           if (err)
               res.send(err);
           res.json(acontecimiento); // return all nerds in JSON format
       });
   });
}

example of the returned json:

[{"_id":"593567528656c9b107d4e6ac","campo":"TRES MARIAS","titular":"RUBEN CARLOS P.","tipo":"CONTAR STOCK ACTUAL","__v":0,"terneros":0,"terneras":0,"vaquillonas":0,"novillitos":0,"toros":0,"vacas":0,"brucelosis":12,"fecha":"2017-06-08T03:00:00.000Z"},{"_id":"593567c08656c9b107d4e6af","campo":"TRES MARIAS","titular":"VICTOR HUGO P.","tipo":"TRANSLADO","__v":0,"terneros":0,"terneras":0,"vaquillonas":0,"novillitos":23,"toros":0,"vacas":0,"brucelosis":0,"fecha":"2017-06-15T03:00:00.000Z"},{"_id":"593568c98656c9b107d4e6b0","campo":"TRES MARIAS","titular":"RUBEN CARLOS P.","tipo":"TRANSLADO","__v":0,"terneros":0,"terneras":0,"vaquillonas":0,"novillitos":0,"toros":0,"vacas":0,"brucelosis":2,"fecha":"2017-06-08T03:00:00.000Z"},{"_id":"593568f28656c9b107d4e6b1","campo":"GUARANIMINI","titular":"RUBEN CARLOS P.","tipo":"VENTA","__v":0,"terneros":0,"terneras":0,"vaquillonas":0,"novillitos":0,"toros":0,"vacas":0,"brucelosis":2,"fecha":"2017-06-03T03:00:00.000Z"},{"_id":"593569348656c9b107d4e6b2","campo":"GUARANIMINI","titular":"RUBEN CARLOS P.","tipo":"MUERTE","__v":0,"terneros":0,"terneras":0,"vaquillonas":0,"novillitos":0,"toros":0,"vacas":0,"brucelosis":2,"fecha":"2017-06-03T03:00:00.000Z"},{"_id":"59356adb8656c9b107d4e6b7","campo":"ESPADAÑAL","titular":"VICTOR HUGO P.","tipo":"TRANSLADO","__v":0,"terneros":0,"terneras":0,"vaquillonas":0,"novillitos":0,"toros":0,"vacas":12,"brucelosis":0,"fecha":"2017-06-05T03:00:00.000Z"},{"_id":"59356bf98656c9b107d4e6b9","campo":"GUARANIMINI","titular":"RUBEN CARLOS P.","tipo":"VACUNA","__v":0,"terneros":34,"terneras":0,"vaquillonas":0,"novillitos":0,"toros":0,"vacas":0,"brucelosis":null,"fecha":"1994-03-12T03:00:00.000Z"},{"_id":"59356c338656c9b107d4e6bb","campo":"GUARANIMINI","titular":"RUBEN CARLOS P.","tipo":"VACUNA","__v":0,"terneros":0,"terneras":0,"vaquillonas":3232,"novillitos":0,"toros":0,"vacas":0,"brucelosis":0,"fecha":"1994-03-12T03:00:00.000Z"},{"_id":"59356fc6f22ca186088a38d7","campo":"GUARANIMINI","titular":"VICTOR HUGO P.","tipo":"VACUNA","__v":0,"terneros":0,"terneras":0,"vaquillonas":0,"novillitos":0,"toros":0,"vacas":0,"brucelosis":1,"fecha":"2017-06-05T03:00:00.000Z"},{"_id":"59356ff0f22ca186088a38d9","campo":"TRES MARIAS","titular":"RUBEN CARLOS P.","tipo":"VACUNA","__v":0,"terneros":0,"terneras":0,"vaquillonas":0,"novillitos":0,"toros":0,"vacas":0,"brucelosis":0,"fecha":"2017-06-02T03:00:00.000Z"},{"_id":"59357009f22ca186088a38dc","campo":"GUARANIMINI","titular":"RUBEN CARLOS P.","tipo":"VENTA","__v":0,"terneros":0,"terneras":0,"vaquillonas":0,"novillitos":0,"toros":0,"vacas":1,"brucelosis":0,"fecha":"2017-06-05T03:00:00.000Z"},{"_id":"593581761587ccdb084f8de5","campo":"TRES MARIAS","titular":"VICTOR HUGO P.","tipo":"MUERTE","__v":0,"terneros":55555,"terneras":0,"vaquillonas":0,"novillitos":0,"toros":0,"vacas":0,"brucelosis":0,"fecha":"2017-06-03T03:00:00.000Z"}]

Body:
Here it is how I solved the problem, I needed to get the response and assign it to my scope. This is what my new controller looks like:

angular.module('EstadisticaCtrl', ['AcontecimientoService'])
  .controller('EstadisticaController', function($scope, Acontecimiento) {
    $scope.init = function(res) {
      Acontecimiento
        .get($scope.acontecimiento)
        .then(function(res) {
          $scope.acontecimiento = res.data;
        }, function(error) {
          console.log('Error: ' + res.data);
        });
    };
  });


问:
Assign same category to similar messages
I have this simple Categorizer:

```<code>import re

class Categorizer:

    '''
    Classifies messages according to a pre-defined list of regex-es
    If no match is found, an automatic algorithm is used to decide the category
    '''

    def __init__(self, categories, message):
        self._categories = categories
        self._message = message

    def _auto_detec_category(self):
        # TODO: auto-detect category based on message (message distance / bayes classifier / ...)
        return message

    @property
    def category(self):
        '''Returns the first matching category, or an automaticaly generated one if no match found'''
        for category, regex in self._categories.items():
            if regex.search(self._message):
                return category
        return self._auto_detec_category()

CATEGORIES = {
    "aaa": "aaa.*AAA",
    "bbb": "bbb.*BBB",
}

categories = { category: re.compile(regex) for category, regex in CATEGORIES.items() }

MESSAGES = [
    "aaa 12345 AAA",
    "aaa 66666 AAA",
    "bbb 12345 BBB",
    "bbb 66666 BBB",
    "ccc 12345 CCC",
    "ccc 66666 CCC",
]

for message in MESSAGES:
    print("{} -> {}".format(Categorizer(categories, message).category, message))
</code>```

Which gives me this:

```<code>aaa -> aaa 12345 AAA
aaa -> aaa 66666 AAA
bbb -> bbb 12345 BBB
bbb -> bbb 66666 BBB
ccc 12345 CCC -> ccc 12345 CCC
ccc 66666 CCC -> ccc 66666 CCC
</code>```

My goal is that not pre-configured patterns can still be classified so that similar messages get assigned the same category. But I am not sure how to define "similar", or what implementation to use in order to ensure that the Categozier is doing a good job with unknown messages.

Those messages are log entries, with generic information but also some specific data which shouldn't be relevant to select the category.

Basically, I would be satisfied with an output like this:

```<code>aaa -> aaa 12345 AAA
aaa -> aaa 66666 AAA
bbb -> bbb 12345 BBB
bbb -> bbb 66666 BBB
auto1 -> ccc 12345 CCC
auto1 -> ccc 66666 CCC
</code>```

Where the two last messages are auto-classified as auto1.

答:
Judging from your comment, I don't think regular expressions is the tool you want.

Have you tried using the fuzzywuzzy library (see Docs). It allows you to compare the "closeness" of two strings. Its not perfect, but in your case, I would try comparing the "closeness" of each of your log entries to some set of standards. Here I classify by the closest match.

```<code>from fuzzywuzzy import fuzz

message = [
    'aaa 12345 AAA',
    'aaa 66666 AAA',
    'bbb 12345 BBB',
    'bbb 66666 BBB',
    'ccc 12345 CCC',
    'ccc 66666 CCC',
]

def classify(input_str):
    # Define standard classifications, and reset them to zero score.
    standards = {
        'AAA': 0,
        'BBB': 0,
        'CCC': 0,
    }

    # Score each classification according to how well is matches.
    for key in standards:
        standards[key] = fuzz.ratio(key, input_str)

    # Return the classification with the highest score.
    return max(standards, key=lambda k: standards[k])

for msg in messages:
    print ('{msg}: {standard}'.format(msg=msg, standard=classify(msg)))
</code>```

Body:
I have this simple Categorizer:

import re

class Categorizer:

    '''
    Classifies messages according to a pre-defined list of regex-es
    If no match is found, an automatic algorithm is used to decide the category
    '''

    def __init__(self, categories, message):
        self._categories = categories
        self._message = message

    def _auto_detec_category(self):
        # TODO: auto-detect category based on message (message distance / bayes classifier / ...)
        return message

    @property
    def category(self):
        '''Returns the first matching category, or an automaticaly generated one if no match found'''
        for category, regex in self._categories.items():
            if regex.search(self._message):
                return category
        return self._auto_detec_category()

CATEGORIES = {
    "aaa": "aaa.*AAA",
    "bbb": "bbb.*BBB",
}

categories = { category: re.compile(regex) for category, regex in CATEGORIES.items() }

MESSAGES = [
    "aaa 12345 AAA",
    "aaa 66666 AAA",
    "bbb 12345 BBB",
    "bbb 66666 BBB",
    "ccc 12345 CCC",
    "ccc 66666 CCC",
]

for message in MESSAGES:
    print("{} -> {}".format(Categorizer(categories, message).category, message))

Which gives me this:

aaa -> aaa 12345 AAA
aaa -> aaa 66666 AAA
bbb -> bbb 12345 BBB
bbb -> bbb 66666 BBB
ccc 12345 CCC -> ccc 12345 CCC
ccc 66666 CCC -> ccc 66666 CCC

My goal is that not pre-configured patterns can still be classified so that similar messages get assigned the same category. But I am not sure how to define "similar", or what implementation to use in order to ensure that the Categozier is doing a good job with unknown messages.

Those messages are log entries, with generic information but also some specific data which shouldn't be relevant to select the category.

Basically, I would be satisfied with an output like this:

aaa -> aaa 12345 AAA
aaa -> aaa 66666 AAA
bbb -> bbb 12345 BBB
bbb -> bbb 66666 BBB
auto1 -> ccc 12345 CCC
auto1 -> ccc 66666 CCC

Where the two last messages are auto-classified as auto1.

Body:
Judging from your comment, I don't think regular expressions is the tool you want.

Have you tried using the fuzzywuzzy library (see Docs). It allows you to compare the "closeness" of two strings. Its not perfect, but in your case, I would try comparing the "closeness" of each of your log entries to some set of standards. Here I classify by the closest match.

from fuzzywuzzy import fuzz

message = [
    'aaa 12345 AAA',
    'aaa 66666 AAA',
    'bbb 12345 BBB',
    'bbb 66666 BBB',
    'ccc 12345 CCC',
    'ccc 66666 CCC',
]

def classify(input_str):
    # Define standard classifications, and reset them to zero score.
    standards = {
        'AAA': 0,
        'BBB': 0,
        'CCC': 0,
    }

    # Score each classification according to how well is matches.
    for key in standards:
        standards[key] = fuzz.ratio(key, input_str)

    # Return the classification with the highest score.
    return max(standards, key=lambda k: standards[k])

for msg in messages:
    print ('{msg}: {standard}'.format(msg=msg, standard=classify(msg)))


问:
making a single xdf files from 2 other xdf files
I am using the RevoScaleR package in MS Visual Studio, and I'm stuck on a step.

I have one XDF file with a column called "Total_Admits_Pred". I have another XDF file with a column called "Total_Admits".

Both XDF files have the same number of rows. I would like to combine the two XDF files into a single XDF file with both of these columns. How could I do that?

Thanks!

Thomas

答:
You would do something like this:</p>

```<code>xdf_df1 <- rxImport("<path/to/xdf1>")
xdf_df2 <- rxImport("<path/to/xdf2>")

xdfOut <- RxXdfData("<path/to/merged/xdf>") # Should not already exist

# This assumes that xdf2 was the one containing "Total_Admits_Pred"
# and that xdf1 contained "Total_Admits", you'll have to adjust this
# based on your data.
xdf_df1[["Total_Admits_Pred"]] <- xdf_df2$Total_Admits_Pred

# Verify the Data Frame is correct
head(xdf_df1)

# Export it
rxDataStep(inData = xdf_df1, outFile = xdfOut)
</code>```

Body:
You would do something like this:

xdf_df1 <- rxImport("<path/to/xdf1>")
xdf_df2 <- rxImport("<path/to/xdf2>")

xdfOut <- RxXdfData("<path/to/merged/xdf>") # Should not already exist

# This assumes that xdf2 was the one containing "Total_Admits_Pred"
# and that xdf1 contained "Total_Admits", you'll have to adjust this
# based on your data.
xdf_df1[["Total_Admits_Pred"]] <- xdf_df2$Total_Admits_Pred

# Verify the Data Frame is correct
head(xdf_df1)

# Export it
rxDataStep(inData = xdf_df1, outFile = xdfOut)


问:
Display the selected category when selecting from a drop down
I want to show the name of the category selected from a drop-down when someone searches in the category.

The page should show search results for "category name here."

I tried using get_search_query(); but it shows only the results from the search form, doesn't work on drop-downs.

答:
There are to ways to handle it.

If your search page URL is similar like http://YOURHOST/?s=query&category=uncategorized then you can get the term object like;

Add the following lines in main functions.php

```add_filter( 'query_vars', function($vars) {
    $vars[] = 'category';
    return $vars;
} );```

Then in search.php get the value

$cat_slug = get_query_var('category');
$term = get_category_by_slug( $cat_slug );
$term_id = $term->term_id; // Here is your required id

The 2nd way that your URL should be http://YOURHOST/?s=query&cat=uncategorized Then you can handle with cat parameter

$cat_slug = get_query_var('cat');
$term = get_category_by_slug( $cat_slug );
$term_id = $term->term_id; // Here is your required id

Body:
There are to ways to handle it.

If your search page URL is similar like http://YOURHOST/?s=query&category=uncategorized then you can get the term object like;

Add the following lines in main functions.php

add_filter( 'query_vars', function($vars) {
    $vars[] = 'category';
    return $vars;
} );

Then in search.php get the value

$cat_slug = get_query_var('category');
$term = get_category_by_slug( $cat_slug );
$term_id = $term->term_id; // Here is your required id

The 2nd way that your URL should be http://YOURHOST/?s=query&cat=uncategorized Then you can handle with cat parameter

$cat_slug = get_query_var('cat');
$term = get_category_by_slug( $cat_slug );
$term_id = $term->term_id; // Here is your required id


问:
How to keep the JMS Headers coming from Upstream applications?
I am using Spring integration JMS Outbound adapter to send message to IBM MQ and I found that some of JMS headers coming from the upstream application is missed out or defaulted. The upstream application is sending the below JMS headers,

JMSType:

JMSDeliveryMode:

JMSExpiration:

JMSPriority:

JMSMessageID:

JMSTimestamp:

JMSCorrelationID:
JMSDestination:

JMSReplyTo:

JMSRedelivered:

After going through Spring's DefaultJmsHeaderMapper conversion, the below Headers are defaulted/missed.

JMSPriority:

JMSDeliveryMode:

JMSExpiration:

JMSRedelivered:

JMSReplyTo:

I enabled explicit-qos flag in JMS Outbound adapter and I do see Priority. But Still have issues with other Headers.

答:
If present, they are mapped from the JMS headers to spring-messaging headers:

```<code>GenericMessage [payload=sdf, headers={
jms_redelivered=false,
jms_destination=queue://queue.demo,
id=899e931b-7f77-3e92-9b95-349c0fc57afe,
priority=4,
jms_timestamp=1496695959175,
jms_messageId=ID:gollum.local-65233-1496695954961-4:1:2:1:1, timestamp=1496695965782}]
</code>```

The only one I see missing is JMSDeliveryMode. With the exception of priority, they are prefxed with jms_.

Not all brokers supply the delivery mode on incoming messages; it generally only applies to outbound. If you can confirm that your broker does indeed provide the delivery mode on inbound messages, we can add the mapping (and/or you can do it in a subclass of the default mapper). Open a JIRA issue with evidence (e.g. a screenshot of a debugger for an inbound message) if you want the mapping added.

Body:
If present, they are mapped from the JMS headers to spring-messaging headers:

GenericMessage [payload=sdf, headers={
jms_redelivered=false,
jms_destination=queue://queue.demo,
id=899e931b-7f77-3e92-9b95-349c0fc57afe,
priority=4,
jms_timestamp=1496695959175,
jms_messageId=ID:gollum.local-65233-1496695954961-4:1:2:1:1, timestamp=1496695965782}]

The only one I see missing is JMSDeliveryMode. With the exception of priority, they are prefxed with jms_.

Not all brokers supply the delivery mode on incoming messages; it generally only applies to outbound. If you can confirm that your broker does indeed provide the delivery mode on inbound messages, we can add the mapping (and/or you can do it in a subclass of the default mapper). Open a JIRA issue with evidence (e.g. a screenshot of a debugger for an inbound message) if you want the mapping added.


问:
Spring Boot, Angular2, Cross-origin
I have a web-server in Spring Boot. I can send HTTP requests to it and get answers from tools like Send HTTP. I also have a web site based on Angular2 whoich works too. Part of the functionality must include HTTP requests from the Angular2 running in Chrome to the Spring Boot server. Every time I do it I have an error in Chrome console:

XMLHttpRequest cannot load 'URL Server'. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'URL Client' is therefore not allowed access.

I put into Spring server @CrossOrigin in all places where it makes sense: before @Controller, @RequestMapping, @GetMapping, but it did not help. What I am missing and how to overcome?
Great thanks, a bit desperate, Levi

答:
You need setup a proxy to backend as is described here.

1) Create file proxy.conf.json (next to package.json) with the content

```<code>{
  "/api": {
    "target": "http://localhost:8080",
    "secure": false
  }
}
</code>```

2) Edit start script in package.json

```<code>"start": "ng serve --proxy-config proxy.conf.json"
</code>```

3) Run with

```<code>npm start
</code>```

Title: Spring Boot, Angular2, Cross-origin

Body:
You need setup a proxy to backend as is described here.

1) Create file proxy.conf.json (next to package.json) with the content

{
  "/api": {
    "target": "http://localhost:8080",
    "secure": false
  }
}

2) Edit start script in package.json

"start": "ng serve --proxy-config proxy.conf.json"

3) Run with

npm start


问:
System.Speech.Synthesis and Recognition on Windows 10 and 7
I'm using System.Speech.Synthesis; and System.Speech.Recognition; in C# winform desktop application.

I have Window 10 on my notebook and default Adult male or female voice sounds different then on the PC with Windows 7.

If system voice works, but sounds completely  different on the older OS, how also this can  affect such  using as System.Speech.Recognition;  for example, with using on older system?

I guess I can't make any  update with executable  installation for not appropriate reference.

It is  hardly relevant to my question, but also I use Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture; initialization to use only English language for program. I note this because maybe there is some limited by particular system capability, but  exist way to fix this  somehow. Maybe I can load some updates with  assemble, but I'm not sure how big is update between window 10 and windows 7  for this particular references.

答: I don't exactly understand your question. But AFAIK, the 'voice' of Synthesiser will vary between different Windows versions, and there's not really much you can do about it other than to use some 3rd party library that provides text-to-speech or so </p>


问:
How to tell protractor to ignore specific asynchronous Angular tasks?
My angularJS application using event-steaming and it keeps open the http event-steam request and listening server events. So my problem is when protractor start testing of my angularJS application, it keeps wait to complete event-stream request as i am using ignoreSynchronization=false so protractor waits until it gets timeout as event-stream http request never going to finish. So i would like to teach my protractor to ignore such event-stream $http tasks and proceed testing of my application.
These event-stream is implemented throughout of my application so every time there is event-stream request then protractor getting timeout.

The following error i am getting when its timeout:
Failed: Timed out waiting for asynchronous Angular tasks to finish after 300 seconds. This may be because the current page is not an Angular application. Please see the FAQ for more details: https://github.com/angular/protractor/blob/master/docs/timeouts.md#waiting-for-angular.
      The following tasks were pending:
       - $http: https://example.com/custom/xxx/sse

Can anyone please help me to get rid of this issue?

答:
In protractor you can add mocks.
So actually what you could do is to add few mock modules to mock whatever you need.

If the issue is just related with the timeout of asynchronous requests timing, you can also change that timeout value from the protractor.config.js, increasing it.

By the way, coming back to the mocks, you define mocks and add them in protractor through the browser.addMockModule method.

Here a good article about mocks in protractor:

http://eitanp461.blogspot.ie/2014/01/advanced-protractor-features.html

And here a good npm module in order to facilitate you mocking angularjs $http requests:

https://github.com/atecarlos/protractor-http-mock

This could be a little example of the mock module directly without using the node module above:

```<code>browser.addMockModule('httpMocker', function() {
  angular.module('httpMocker', ['ngMockE2E'])
  .run(function($httpBackend) {
    $httpBackend.whenGET('MYURL')
    .respond("MOCKED RESPONSE!");
  })
})
</code>```

You can define mocks directly inside the tests too, but if you want that globally in your tests, I suggest you to directly define your mocks inside the onPrepare method inside the protractor.config.js.

I hope it helps

Body:
In protractor you can add mocks.
So actually what you could do is to add few mock modules to mock whatever you need.

If the issue is just related with the timeout of asynchronous requests timing, you can also change that timeout value from the protractor.config.js, increasing it.

By the way, coming back to the mocks, you define mocks and add them in protractor through the browser.addMockModule method.

Here a good article about mocks in protractor:

http://eitanp461.blogspot.ie/2014/01/advanced-protractor-features.html

And here a good npm module in order to facilitate you mocking angularjs $http requests:

https://github.com/atecarlos/protractor-http-mock

This could be a little example of the mock module directly without using the node module above:

browser.addMockModule('httpMocker', function() {
  angular.module('httpMocker', ['ngMockE2E'])
  .run(function($httpBackend) {
    $httpBackend.whenGET('MYURL')
    .respond("MOCKED RESPONSE!");
  })
})

You can define mocks directly inside the tests too, but if you want that globally in your tests, I suggest you to directly define your mocks inside the onPrepare method inside the protractor.config.js.

I hope it helps


问:
Differences between Go and Cython
Today a great friend of mine asked me what are the main differences between the newest Go language and Cython, which is a set of C-extensions for Python. I don't have much knowledge on Python, can anyone tell me why Go is better/worse than Cython?</p>

答:
What about support. You are relying on a single compiler, provided by Google. What if Go folds or goes commercial?

With Cython you could always go back to Python (or port the C code) if the Cython project folded.

UPDATE: I must say that I am now upset with Cython. The lack of thread support is a major blow. Cython is thread-safe BUT at a serious cost. The global interpreter lock is held the whole time a function executes. Thereby disabling concurrent execution over an entire codebase!

Cython's C-like features are poorly documented and confusing to novices. I admit.

Cython's purpose is to support the Sage mathematics software; Go's is to support Google's ambitious plans for cutting-edge expensive $$ hardware.

In short, I no longer like either one of these languages. Going back to C++ (again). My favorite is Cython.

Title: Differences between Go and Cython


问:
How to copy a directory using Ant
I have used copydir to copy a directory tree but it is deprecated. My directory contains some sub-directories, and some of those contain files and others contain more sub-directories.

How can I copy the entire tree?

答:
Another ant task is Copydir. The key part here is to include the name of the directory you want to copy after the dest directory. The sub-directories and files will be copied automatically.</p>

```<code><target name="-post-jar">
    <copydir src="config" dest="${dist.dir}/config/"/>
</target>
</code>```

Title: How to copy a directory using Ant

Body:
Another ant task is Copydir. The key part here is to include the name of the directory you want to copy after the dest directory. The sub-directories and files will be copied automatically.

<target name="-post-jar">
    <copydir src="config" dest="${dist.dir}/config/"/>
</target>


问:
Unable to send JSON object to XMLHttpRequest
I am unable to send JSON object to XMLHttpRequest(). However, if I send string data through send(), it works. For example, the following code works:

```<code>var xhr = new XMLHttpRequest();
var url = 'https://xyz.info/api/contacts';
xhr.open("POST", url,true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

xhr.onreadystatechange = function() {//Call a function when the state changes.
     if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
                // Request finished. Do processing here.
     }
}
xhr.send("apikey=ee694eabf9e3&firstname=Raja1&lastname=Kumars&phone=123456");
</code>```

However, if I try to send data using JSON, it posts nothing to the url. The following code does not work.

```<code>var xhr = new XMLHttpRequest();
var url = 'https://xyz.info/api/contacts';
    xhr.open("POST", url,true);
    //xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.setRequestHeader("Content-Type", "application/json");

    xhr.onreadystatechange = function() {//Call a function when the state changes.
    if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
            // Request finished. Do processing here.
        }
    }
    xhr.send(JSON.stringify({
                    'apikey' :'ee6915d4ee4b4df66bba82277e3',
                    'firstname' : 'Kumar',
                    'lastname' : 'Sunder',
                    'phone':'5557773334'
    }));
</code>```

答:
You're sending very different information in your two calls. Some sample code:

    var _stringify = JSON.stringify({
                    'apikey' :'ee6915d4ee4b4df66bba82277e3',
                    'firstname' : 'Kumar',
                    'lastname' : 'Sunder',
                    'phone':'5557773334'
    });
    console.log(_stringify);
    var _orig = "apikey=ee694eabf9e3&firstname=Raja1&lastname=Kumars&phone=123456"
    var _encoded = encodeURI(_stringify);
    console.log(_orig);
    console.log(_encoded);

when your original string is printed to the console log, it looks as you would expect:

apikey=ee694eabf9e3&firstname=Raja1&lastname=Kumars&phone=123456

when the result of JSON.stringify is printed to the console, it returns:

{"apikey":"ee6915d4ee4b4df66bba82277e3","firstname":"Kumar","lastname":"Sunder","phone":"5557773334"}

That is, it comes complete with lots of extra double quote marks and left and right brackets. If you want to send all of that as a string (as in your initial example), you would need to URI encode the result of the JSON.stringify call. This is what happens with the "_encoded" variable, which contains:

%7B%22apikey%22:%22ee6915d4ee4b4df66bba82277e3%22,%22firstname%22:%22Kumar%22,%22lastname%22:%22Sunder%22,%22phone%22:%225557773334%22%7D

Body:
I am unable to send JSON object to XMLHttpRequest(). However, if I send string data through send(), it works. For example, the following code works:

var xhr = new XMLHttpRequest();
var url = 'https://xyz.info/api/contacts';
xhr.open("POST", url,true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

xhr.onreadystatechange = function() {//Call a function when the state changes.
     if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
                // Request finished. Do processing here.
     }
}
xhr.send("apikey=ee694eabf9e3&firstname=Raja1&lastname=Kumars&phone=123456");

However, if I try to send data using JSON, it posts nothing to the url. The following code does not work.

var xhr = new XMLHttpRequest();
var url = 'https://xyz.info/api/contacts';
    xhr.open("POST", url,true);
    //xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.setRequestHeader("Content-Type", "application/json");

    xhr.onreadystatechange = function() {//Call a function when the state changes.
    if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
            // Request finished. Do processing here.
        }
    }
    xhr.send(JSON.stringify({
                    'apikey' :'ee6915d4ee4b4df66bba82277e3',
                    'firstname' : 'Kumar',
                    'lastname' : 'Sunder',
                    'phone':'5557773334'
    }));


问:
MVC download file through AJAX POST
I want to allow users to choose a file to download from a drop down list. Once they have made a selection, they can click the download button. However, the file does not download correctly.

Here is the controller for generating and returning the file:

```<code>[HttpPost]
    public ActionResult DownloadReport(int? id, string templateChoice)
    {
        if (id == null)
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        try
        {
            byte[] file = GetReport(id, templateChoice);
            return File(file, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "ResumeReport.docx");
        }
        catch (InvalidOperationException)
        {
            return View();
        }
    }
</code>```

The JavaScript function which is called upon pressing the generate report button is:

```<code>function downloadReport(InputID) {
        $.ajax({
            type: 'POST',
            url: '@Url.Action("DownloadReport", "UserProfiles")',
            data: JSON.stringify({ "ID": InputID, "TemplateChoice": $("#resumeTemplates").val() }),
            contentType: 'application/json; charset=utf-8'
        });
    }
</code>```

Opening the inspect window in chrome and going to the network tab shows the document data is received, but it does not download like a regular file.

答:
I seemed to have found a working solution which does not reload page, does not redirect the user, and does not show any excess text in the URL upon pressing the download button. I replaced my current JavaScript function with the following:

```<code>function downloadReport(inputID) {
        window.location.href = '/UserProfiles/DownloadReport/?id=' + inputID + '&template=' + $('#resumeTemplates').val();
    }
</code>```

And my controller now looks like:

```<code>public ActionResult DownloadReport(int? id, string template)
    {
        if (id == null || template == null)
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        try
        {
            byte[] file = GetReport(id, template);
            return File(file, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "ResumeReport.docx");
        }
        catch (InvalidOperationException)
        {
            return View();
        }
    }
</code>```

I also added this into my RouteConfig.cs file:

```<code>routes.MapRoute(
            "DownloadReport",
            "{controller}/{action}/{id}/{template}",
            new { controller = "UserProfiles", action = "DownloadReport", id = UrlParameter.Optional, template = UrlParameter.Optional }
        );
</code>```

Title: MVC download file through AJAX POST

Body:
I want to allow users to choose a file to download from a drop down list. Once they have made a selection, they can click the download button. However, the file does not download correctly.

Here is the controller for generating and returning the file:

[HttpPost]
    public ActionResult DownloadReport(int? id, string templateChoice)
    {
        if (id == null)
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        try
        {
            byte[] file = GetReport(id, templateChoice);
            return File(file, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "ResumeReport.docx");
        }
        catch (InvalidOperationException)
        {
            return View();
        }
    }

The JavaScript function which is called upon pressing the generate report button is:

function downloadReport(InputID) {
        $.ajax({
            type: 'POST',
            url: '@Url.Action("DownloadReport", "UserProfiles")',
            data: JSON.stringify({ "ID": InputID, "TemplateChoice": $("#resumeTemplates").val() }),
            contentType: 'application/json; charset=utf-8'
        });
    }

Opening the inspect window in chrome and going to the network tab shows the document data is received, but it does not download like a regular file.

Body:
I seemed to have found a working solution which does not reload page, does not redirect the user, and does not show any excess text in the URL upon pressing the download button. I replaced my current JavaScript function with the following:

function downloadReport(inputID) {
        window.location.href = '/UserProfiles/DownloadReport/?id=' + inputID + '&template=' + $('#resumeTemplates').val();
    }

And my controller now looks like:

public ActionResult DownloadReport(int? id, string template)
    {
        if (id == null || template == null)
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        try
        {
            byte[] file = GetReport(id, template);
            return File(file, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "ResumeReport.docx");
        }
        catch (InvalidOperationException)
        {
            return View();
        }
    }

I also added this into my RouteConfig.cs file:

routes.MapRoute(
            "DownloadReport",
            "{controller}/{action}/{id}/{template}",
            new { controller = "UserProfiles", action = "DownloadReport", id = UrlParameter.Optional, template = UrlParameter.Optional }
        );


问:
How do you string a variable together along with a string in PHP?
So I have a variable in PHP that I would like to print along with an html tag but I am very new to PHP and I can't seem to get the syntax right

My goal is to output/print the following

```<code><div class="post-block" style="background-image:url(Whatever image here);">
</code>```

My code is below:

```<code>    $feature_posts = the_sub_field('feature_image_post');

      if ( get_sub_field('post-feature') == "" )  {
        echo '<div class="post-block" style="background-image:url(' .$feature_posts");>';
        echo '</div>';
      }
</code>```

答:
You are missing the concatenation operator and the closing single quote after your variable:

```<code>$feature_posts = the_sub_field('feature_image_post');

if ( get_sub_field('post-feature') == "" )  {
    echo '<div class="post-block" style="background-image:url(' . $feature_posts . ')">';
    echo '</div>';
}
</code>```

To keep the format more readable you can use double quotes to allow variables in your string. Just have to remember escaping the quotes within the markup:

```<code>$feature_posts = the_sub_field('feature_image_post');

if ( get_sub_field('post-feature') == "" )  {
    echo "<div class=\"post-block\" style=\"background-image:url($feature_posts)\">";
    echo '</div>';
}
</code>```

Body:
So I have a variable in PHP that I would like to print along with an html tag but I am very new to PHP and I can't seem to get the syntax right

My goal is to output/print the following

My code is below:

    $feature_posts = the_sub_field('feature_image_post');

      if ( get_sub_field('post-feature') == "" )  {
        echo '
';
        echo '
';
      }

Body:
You are missing the concatenation operator and the closing single quote after your variable:

$feature_posts = the_sub_field('feature_image_post');

if ( get_sub_field('post-feature') == "" )  {
    echo '<div class="post-block" style="background-image:url(' . $feature_posts . ')">';
    echo '</div>';
}

To keep the format more readable you can use double quotes to allow variables in your string. Just have to remember escaping the quotes within the markup:

$feature_posts = the_sub_field('feature_image_post');

if ( get_sub_field('post-feature') == "" )  {
    echo "<div class=\"post-block\" style=\"background-image:url($feature_posts)\">";
    echo '</div>';
}


问:
using php to place image names within a folder to feed HTML img src inside bootstrap carousel
I have a folder containing images that I want to put inside a Bootstrap carousel. Instead of hardcode everything in my HTML, I thought to use PHP to scan the image files and create my carousel list dynamically.

After various attempts, my best achievement was having a carousel listing the names of my images (rather than the image themselves).

My code is below. I have two question about it:

(obviously) Why is it not working?

Is there a better way to separate such a long PHP function from the HTML code (like a call with include but that would work with functions)?

```<code><div class="container-fluid">
  <?php
    $img_folder = './img/img_animazione/';
    function carousel_loop($folder)
    {
      echo '<div id="myCarousel" class="carousel slide" data-ride="carousel">';
      echo '<ol class="carousel-indicators">';
      $i = -1;
      $images = scandir($folder);
      foreach($images as $image) {
        $i++; //$i is the index of the current loop.
        if ($i == 0) {
          echo '<li data-target="#myCarousel" data-slide-to="' . $i . '" class="active"></li>';
        } else {
          echo '<li data-target="#myCarousel" data-slide-to="' . $i . '"</li>';
        }
      }
      echo '</ol>';
      echo '<div class="carousel-inner">';
      foreach($images as $image) {
        if ($image === reset($images)) {
          echo '<div class="item active">';
          echo '<img src="' . $image . '" alt="'. $image . '">';
          echo '</div>';
        } else {
          echo '<div class="item">';
          echo '<img src="' . $image . '" alt="'. $image . '">';
          echo '</div>';
        }
      }
      echo '</div>';
      echo '<a class="left carousel-control" href="#myCarousel" data-slide="prev">';
      echo '<span class="glyphicon glyphicon-chevron-left"></span>';
      echo '<span class="sr-only">Previous</span>';
      echo '</a>';
      echo '<a class="right carousel-control" href="#myCarousel" data-slide="next">';
      echo '<span class="glyphicon glyphicon-chevron-right"></span>';
      echo '<span class="sr-only">Next</span>';
      echo '</a>';
      echo '</div>';
    }
    carousel_loop($img_folder);
  ?>
</div>
</code>```

答:
Thanks to @Abraham A. answer, I finally was able to come up with a working (still "dirt") solution. I'll post the code below. The problems in my initial code were:

Using echo within a function instead of returning a (very long) HTML string in the function and "echoing" it from outside.

<img src= obviously wants a source and not just a filename. My first attempt was <img src= . $image, the correct form is <img src= . $folder . DIRECTORY_SEPARATOR . $image

It seems like [scandir()][1] creates an array with all the filenames within a folder AND ".", ".." (current and parent folder) in it. I got rid of the latters via $allFiles = scandir($folder); $images = array_diff($allFiles, array('.', '..')); as suggested here.

My working code is this one now.

```<code><?php
   function carousel_loop($folder)
   {
     $html = "";
     $html .= '<div id="myCarousel" class="carousel slide" data-ride="carousel">';
     $html .= '<ol class="carousel-indicators">';
     $i = -1;
     $allFiles = scandir($folder); // list all files in folders
     $images = array_diff($allFiles, array('.', '..')); // drop current and parent folder from array list (".", "..")
     foreach($images as $image) {
       $i++; //$i is the index of the current loop.
       if ($i == 0) {
         $html .= '<li data-target="#myCarousel" data-slide-to="' . $i . '" class="active"></li>';
       } else {
         $html .= '<li data-target="#myCarousel" data-slide-to="' . $i . '"></li>';
       }
     }
     $html .= '</ol>';
     $html .= '<div class="carousel-inner">';
     foreach($images as $image) {
       if ($image === reset($images)) {
         $html .= '<div class="item active">';
         $html .= '<img src="' . $folder . DIRECTORY_SEPARATOR . $image . '" alt="' . $image . '" style="width:100%;">';
         $html .= '</div>';
       } else {
         $html .= '<div class="item">';
         $html .= '<img src="' . $folder . DIRECTORY_SEPARATOR . $image . '" alt="' . $image . '" style="width:100%;">';
         $html .= '</div>';
       }
     }
     $html .= '</div>';
     $html .= '<a class="left carousel-control" href="#myCarousel" data-slide="prev">';
     $html .= '<span class="glyphicon glyphicon-chevron-left"></span>';
     $html .= '<span class="sr-only">Previous</span>';
     $html .= '</a>';
     $html .= '<a class="right carousel-control" href="#myCarousel" data-slide="next">';
     $html .= '<span class="glyphicon glyphicon-chevron-right"></span>';
     $html .= '<span class="sr-only">Next</span>';
     $html .= '</a>';
     $html .= '</div>';

     return $html;
   }
?>

<div class="container">
  <?php
    $img_folder = './img/img_animazione';
    echo carousel_loop($img_folder);
  ?>
</div>
</code>```

Body:
I have a folder containing images that I want to put inside a Bootstrap carousel. Instead of hardcode everything in my HTML, I thought to use PHP to scan the image files and create my carousel list dynamically.

After various attempts, my best achievement was having a carousel listing the names of my images (rather than the image themselves).

My code is below. I have two question about it:

(obviously) Why is it not working?

Is there a better way to separate such a long PHP function from the HTML code (like a call with include but that would work with functions)?

  <?php
    $img_folder = './img/img_animazione/';
    function carousel_loop($folder)
    {
      echo '
';
      echo '
';
      $i = -1;
      $images = scandir($folder);
      foreach($images as $image) {
        $i++; //$i is the index of the current loop.
        if ($i == 0) {
          echo '

';
        } else {
          echo '<li data-target="#myCarousel" data-slide-to="' . $i . '"
';
        }
      }
      echo '
';
      echo '
';
      foreach($images as $image) {
        if ($image === reset($images)) {
          echo '
';
          echo '';
          echo '
';
        } else {
          echo '
';
          echo '';
          echo '
';
        }
      }
      echo '
';
      echo '';
      echo '';
      echo 'Previous';
      echo '';
      echo '';
      echo '';
      echo 'Next';
      echo '';
      echo '
';
    }
    carousel_loop($img_folder);
  ?>

Body:
Thanks to @Abraham A. answer, I finally was able to come up with a working (still "dirt") solution. I'll post the code below. The problems in my initial code were:

Using echo within a function instead of returning a (very long) HTML string in the function and "echoing" it from outside.

<img src= obviously wants a source and not just a filename. My first attempt was <img src= . $image, the correct form is <img src= . $folder . DIRECTORY_SEPARATOR . $image

It seems like [scandir()][1] creates an array with all the filenames within a folder AND ".", ".." (current and parent folder) in it. I got rid of the latters via $allFiles = scandir($folder); $images = array_diff($allFiles, array('.', '..')); as suggested here.

My working code is this one now.

<?php
   function carousel_loop($folder)
   {
     $html = "";
     $html .= '<div id="myCarousel" class="carousel slide" data-ride="carousel">';
     $html .= '<ol class="carousel-indicators">';
     $i = -1;
     $allFiles = scandir($folder); // list all files in folders
     $images = array_diff($allFiles, array('.', '..')); // drop current and parent folder from array list (".", "..")
     foreach($images as $image) {
       $i++; //$i is the index of the current loop.
       if ($i == 0) {
         $html .= '<li data-target="#myCarousel" data-slide-to="' . $i . '" class="active"></li>';
       } else {
         $html .= '<li data-target="#myCarousel" data-slide-to="' . $i . '"></li>';
       }
     }
     $html .= '</ol>';
     $html .= '<div class="carousel-inner">';
     foreach($images as $image) {
       if ($image === reset($images)) {
         $html .= '<div class="item active">';
         $html .= '<img src="' . $folder . DIRECTORY_SEPARATOR . $image . '" alt="' . $image . '" style="width:100%;">';
         $html .= '</div>';
       } else {
         $html .= '<div class="item">';
         $html .= '<img src="' . $folder . DIRECTORY_SEPARATOR . $image . '" alt="' . $image . '" style="width:100%;">';
         $html .= '</div>';
       }
     }
     $html .= '</div>';
     $html .= '<a class="left carousel-control" href="#myCarousel" data-slide="prev">';
     $html .= '<span class="glyphicon glyphicon-chevron-left"></span>';
     $html .= '<span class="sr-only">Previous</span>';
     $html .= '</a>';
     $html .= '<a class="right carousel-control" href="#myCarousel" data-slide="next">';
     $html .= '<span class="glyphicon glyphicon-chevron-right"></span>';
     $html .= '<span class="sr-only">Next</span>';
     $html .= '</a>';
     $html .= '</div>';

     return $html;
   }
?>

<div class="container">
  <?php
    $img_folder = './img/img_animazione';
    echo carousel_loop($img_folder);
  ?>
</div>


问:
Does spring webflux supports javax bean validation?
I have annotated my bean with some @NotNull and use the spring @Valid annotation in the @GetMapping. But this did not work.

The only difference I see from other applications is that I use @EnableWebMvc instead of @EnableWebFlux.

In the controller:

```<code>    @PostMapping(value = "/something")
    public Mono<ResponseEntity> save(
                                @Valid @RequestBody MyBean mybean) {
        return myService.save(myBean)
                .map(RestResponses::ok)
                .defaultIfEmpty(RestResponses.empty());
    }
</code>```

In the Application.java:

```<code>    @SpringBootApplication
    @EnableWebFlux
    public class Application {

        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    }
</code>```

My bean class:

```<code>    import org.springframework.data.annotation.Id;
    import org.springframework.data.redis.core.RedisHash;
    import org.springframework.data.redis.core.index.Indexed;

    import javax.validation.constraints.NotNull;
    import java.util.Objects;

    @RedisHash("mybean")
    public class MyBean {

        @Id
        private Long id;

        @NotNull
        @Indexed
        private String name;

        //getters, setters...

    }
</code>```

and pom.xml:

```<code><parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.M1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

...

 <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
        </dependency>

</dependencies>
</code>```

Am I doing something wrong?

答:
Actually there is some dependencies problem.
In the dependencies you can see those two libraries:

```<code>org.hibernate:hibernate-validator:5.4.1.Final
javax.validation:validation-api:1.1.0.Final
</code>```

And according to documentation Hibernate Validator you should provide additional dependency for Unified Expression Language

```<code>compile group: 'org.glassfish', name: 'javax.el', version: '3.0.1-b08'
</code>```

After @Valid annotation should work as expected.

Body:
I have annotated my bean with some @NotNull and use the spring @Valid annotation in the @GetMapping. But this did not work.

The only difference I see from other applications is that I use @EnableWebMvc instead of @EnableWebFlux.

In the controller:

    @PostMapping(value = "/something")
    public Mono<ResponseEntity> save(
                                @Valid @RequestBody MyBean mybean) {
        return myService.save(myBean)
                .map(RestResponses::ok)
                .defaultIfEmpty(RestResponses.empty());
    }

In the Application.java:

    @SpringBootApplication
    @EnableWebFlux
    public class Application {

        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    }

My bean class:

    import org.springframework.data.annotation.Id;
    import org.springframework.data.redis.core.RedisHash;
    import org.springframework.data.redis.core.index.Indexed;

    import javax.validation.constraints.NotNull;
    import java.util.Objects;

    @RedisHash("mybean")
    public class MyBean {

        @Id
        private Long id;

        @NotNull
        @Indexed
        private String name;

        //getters, setters...

    }

and pom.xml:

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.M1</version>
        <relativePath/>
    </parent>

...

 <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
        </dependency>

</dependencies>

Am I doing something wrong?

Body:
Actually there is some dependencies problem.
In the dependencies you can see those two libraries:

org.hibernate:hibernate-validator:5.4.1.Final
javax.validation:validation-api:1.1.0.Final

And according to documentation Hibernate Validator you should provide additional dependency for Unified Expression Language

compile group: 'org.glassfish', name: 'javax.el', version: '3.0.1-b08'

After @Valid annotation should work as expected.


问:
Firebase Datatabase - Query object inside another object
I wanted to get this book by its title, however this query is returning me all nodes without any filtering. Any suggestions on how to get into volumeInfo and filter by title?

```<code>mDatabaseReference.child(userId)
                .child(REF_FOLDERS)
                .child(REF_MY_BOOKS_FOLDER)
                .child(REF_BOOKS)
                .orderByChild("volumeInfo")
                .startAt(bookQuery,"title")
                .addListenerForSingleValueEvent(buildValueEventListener(onDataSnapshotListener));
</code>```

答:
Finally I found out how to do that. I have to use slash to access attributes in object.

Like this:

```<code>mDatabaseReference.child(userId)
                .child(REF_FOLDERS)
                .child(REF_MY_BOOKS_FOLDER)
                .child(REF_BOOKS)
                .orderByChild("volumeInfo/title") // here I get title from volumeInfo
                .equalTo(bookQuery)
                .addListenerForSingleValueEvent(buildValueEventListener(onDataSnapshotListener));
</code>```

Body:
I wanted to get this book by its title, however this query is returning me all nodes without any filtering. Any suggestions on how to get into volumeInfo and filter by title?

mDatabaseReference.child(userId)
                .child(REF_FOLDERS)
                .child(REF_MY_BOOKS_FOLDER)
                .child(REF_BOOKS)
                .orderByChild("volumeInfo")
                .startAt(bookQuery,"title")
                .addListenerForSingleValueEvent(buildValueEventListener(onDataSnapshotListener));

Body:
Finally I found out how to do that. I have to use slash to access attributes in object.

Like this:

mDatabaseReference.child(userId)
                .child(REF_FOLDERS)
                .child(REF_MY_BOOKS_FOLDER)
                .child(REF_BOOKS)
                .orderByChild("volumeInfo/title") // here I get title from volumeInfo
                .equalTo(bookQuery)
                .addListenerForSingleValueEvent(buildValueEventListener(onDataSnapshotListener));


问:
Get all subsets of a Python dictionary with restrictions
I have the following dictionary:

```<code>intervals = {'param1': [0, 1],
             'param2_hi': [4, 5, 6, 7, 8, 9],
             'param2_lo': [0, 1, 2, 3, 4, 5],
             'param3_hi': [9, 10, 11, 12, 13, 14, 15],
             'param3_lo': [5, 6, 7, 8, 9, 10],
             'param4': [0, 1],
             'param5_hi': [4, 5, 6, 7, 8, 9],
             'param5_lo': [0, 1, 2, 3, 4, 5]}
</code>```

How would I create all possible subsets of this dictionary where I must have exactly one of each number x for 'paramx'? Meaning that I can only have one entry for param1 (_lo or _hi), one entry for param2 (_lo or _hi), and so on, and that each subset must include every paramx that does not have a _lo or _hi.

Here are two possible subsets:

```<code>subset_one = {'param1': [0, 1],
              'param2_hi': [4, 5, 6, 7, 8, 9],
              'param3_hi': [9, 10, 11, 12, 13, 14, 15],
              'param4': [0, 1],
              'param5_hi': [4, 5, 6, 7, 8, 9]}

subset_two = {'param1': [0, 1],
              'param2_lo': [0, 1, 2, 3, 4, 5],
              'param3_lo': [5, 6, 7, 8, 9, 10],
              'param4': [0, 1],
              'param5_lo': [0, 1, 2, 3, 4, 5]}

# Example of mixed '_hi' and '_lo' intervals
subset_three = {'param1': [0, 1],
                'param2_lo': [0, 1, 2, 3, 4, 5],
                'param3_hi': [9, 10, 11, 12, 13, 14, 15],
                'param4': [0, 1],
                'param5_lo': [0, 1, 2, 3, 4, 5]}

...
</code>```

Note: I want to preserve key, value pairs.

Edit: Added subset_three to show the possibility of having mixed '_lo' and '_hi' intervals.

Body:
I have the following dictionary:

intervals = {'param1': [0, 1],
             'param2_hi': [4, 5, 6, 7, 8, 9],
             'param2_lo': [0, 1, 2, 3, 4, 5],
             'param3_hi': [9, 10, 11, 12, 13, 14, 15],
             'param3_lo': [5, 6, 7, 8, 9, 10],
             'param4': [0, 1],
             'param5_hi': [4, 5, 6, 7, 8, 9],
             'param5_lo': [0, 1, 2, 3, 4, 5]}

How would I create all possible subsets of this dictionary where I must have exactly one of each number x for 'paramx'? Meaning that I can only have one entry for param1 (_lo or _hi), one entry for param2 (_lo or _hi), and so on, and that each subset must include every paramx that does not have a _lo or _hi.

Here are two possible subsets:

subset_one = {'param1': [0, 1],
              'param2_hi': [4, 5, 6, 7, 8, 9],
              'param3_hi': [9, 10, 11, 12, 13, 14, 15],
              'param4': [0, 1],
              'param5_hi': [4, 5, 6, 7, 8, 9]}

subset_two = {'param1': [0, 1],
              'param2_lo': [0, 1, 2, 3, 4, 5],
              'param3_lo': [5, 6, 7, 8, 9, 10],
              'param4': [0, 1],
              'param5_lo': [0, 1, 2, 3, 4, 5]}

# Example of mixed '_hi' and '_lo' intervals
subset_three = {'param1': [0, 1],
                'param2_lo': [0, 1, 2, 3, 4, 5],
                'param3_hi': [9, 10, 11, 12, 13, 14, 15],
                'param4': [0, 1],
                'param5_lo': [0, 1, 2, 3, 4, 5]}

...

Note: I want to preserve key, value pairs.

Edit: Added subset_three to show the possibility of having mixed '_lo' and '_hi' intervals.

Body:
You can use groupby and product from itertools module like this example in order to list all the possible combinations:

from itertools import groupby, product

intervals = {'param1': [0, 1],
             'param2_hi': [4, 5, 6, 7, 8, 9],
             'param2_lo': [0, 1, 2, 3, 4, 5],
             'param3_hi': [9, 10, 11, 12, 13, 14, 15],
             'param3_lo': [5, 6, 7, 8, 9, 10],
             'param4': [0, 1],
             'param5_hi': [4, 5, 6, 7, 8, 9],
             'param5_lo': [0, 1, 2, 3, 4, 5]}

sub = []

for _,v in groupby(sorted(intervals.keys()), lambda x: x[5]):
    # Or:
    # sub.append(list(v))
    sub.append(sorted(list(v)))

for k in product(*sub):
    print({j:intervals[j] for j in k})
    print("------")

Output:

{'param1': [0, 1], 'param3_hi': [9, 10, 11, 12, 13, 14, 15], 'param2_hi': [4, 5, 6, 7, 8, 9], 'param5_hi': [4, 5, 6, 7, 8, 9], 'param4': [0, 1]}
------
{'param1': [0, 1], 'param3_hi': [9, 10, 11, 12, 13, 14, 15], 'param2_hi': [4, 5, 6, 7, 8, 9], 'param5_lo': [0, 1, 2, 3, 4, 5], 'param4': [0, 1]}
------
{'param1': [0, 1], 'param2_hi': [4, 5, 6, 7, 8, 9], 'param5_hi': [4, 5, 6, 7, 8, 9], 'param3_lo': [5, 6, 7, 8, 9, 10], 'param4': [0, 1]}
------
{'param1': [0, 1], 'param2_hi': [4, 5, 6, 7, 8, 9], 'param3_lo': [5, 6, 7, 8, 9, 10], 'param5_lo': [0, 1, 2, 3, 4, 5], 'param4': [0, 1]}
------
....
------

{'param4': [0, 1], 'param1': [0, 1], 'param5_hi': [4, 5, 6, 7, 8, 9], 'param3_lo': [5, 6, 7, 8, 9, 10], 'param2_lo': [0, 1, 2, 3, 4, 5]}
------
{'param4': [0, 1], 'param1': [0, 1], 'param5_lo': [0, 1, 2, 3, 4, 5], 'param3_lo': [5, 6, 7, 8, 9, 10], 'param2_lo': [0, 1, 2, 3, 4, 5]}
------


问:
How do I mount a remote Linux folder in Windows through SSH?
I'm a blind student currently in a system admin/shell programming class. Although ssh works fine for executing commands like ls, pwd, etc editors do not work well with my screen reader and an ssh session. I was wondering if it is possible to mount a Linux folder over ssh so it appears as a windows drive? This way I could edit any files I needed to with accessible software and not have to constantly use SCP to send files back and fourth.</p>

答:
Back in 2002, Novell developed some software called NetDrive that can map a WebDAV, FTP, SFTP, etc. share to a windows drive letter. It is now abandonware, so it's no longer maintained (and not available on the Novell website), but it's free to use. I found quite a few available to download by searching for "netdrive.exe" I actually downloaded a few and compared their md5sums to make sure that I was getting a common (and hopefully safe) version.

Update 10 Nov 2017
SFTPNetDrive is the current project from the original netdrive project. And they made it free for personal use:

We Made SFTP Net Drive FREE for Personal Use

They have paid options as well on the website.

OwnerDisplayName: Jared

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Michael Haren

OwnerDisplayName: Sunny

ContentLicense: CC BY-SA 4.0

LastEditorDisplayName: Sunny


问:
Re-run an html
```

However, the problem I'm running into is that the script only runs when the webpage initially loads, and then never again. Since I'm adding more tags in an API call and then updating the list via the props, it means I'm left with a bunch of  tags that don't get converted when the call returns.

I've inspected the React console & html and can confirm the tags are there, it's just that the dynamically converted tags don't show up as pins.

I've already tried using jquery and document.appendChild() to add/get the script in componentDidUpdate(), but it doesn't seem to be working. Anybody have any clue how I can get around this?

答: If you look in your devtools you should see that when the html page loads this script it is just making a GET request to the script src (http://assets.pinterest.com/js/pinit.js). So, you should be able to recreate that behavior by making a simple http GET request to that url each time you need to rerun the script.

Title: Re-run an html <script> in React

Body:
I'm making a component in React that has Facebook data pulled from an API call. The API call returns and updates a list, which render() will then populate with  tags that are supposed to be converted to actual images by a script from Facebook's website. Something like this:

My html file includes this script, which I assume runs through the HTML code and converts the tags to something viewable.

However, the problem I'm running into is that the script only runs when the webpage initially loads, and then never again. Since I'm adding more tags in an API call and then updating the list via the props, it means I'm left with a bunch of  tags that don't get converted when the call returns.

I've inspected the React console & html and can confirm the tags are there, it's just that the dynamically converted tags don't show up as pins.

I've already tried using jquery and document.appendChild() to add/get the script in componentDidUpdate(), but it doesn't seem to be working. Anybody have any clue how I can get around this?


问:
Getting error: expression not assignable
I'm new to C and I can't find any answers on why it's giving me an error: expression is not assignable on lines 11 and 20.

This is a simple code for creating a random array and then sort it using a subroutine. I'm still learning C and couldn't find a solution with any research.

Here is my code:

```<code>#include <stdio.h>
#include <stdlib.h>
int myArray[100];
int* ptr = myArray;
int i;
int n = sizeof(myArray);
int SortedArray[100];

int MakeRandArray(ptr, i)
{
    for (i = 0; i < n; i++) {
        (ptr + i) = rand()
    }
}

int SortArray(ptr)
{
    int a;
    int j = (i + 1);
    for (i = 0; i < n; i++) {
        if ((ptr + i) > (ptr + j)) {
            (ptr + i) = (ptr + j)
        }
    }
}

int main()
{
    MakeRandArray(*ptr, i);
    SortArray(*ptr);
}
</code>```

答:
Here is a version with the errors avoided and -Wallwarnings, too.

I did not change things which are against good coding practice. Take some time later to learn about those, too. Read the comments on your question and on this answer for doing that.
As an encore I got your sorting working (in a very blind, inefficient way) and added a printer, for demonstration purposes. I use array size 10 instead of 100, for convenience. It seems that you intend to keep the orignal array and create a sorted version, I left that for you.

```<code>#include <stdio.h>
#include <stdlib.h>
    int myArray[10];
    int *ptr = myArray;
    // int i; Do not use globals for counters inside functions.

    // it would be better to give the size of arrays as an explicit
    // parameter to functions, instead of using a global variable
    // (keeping this only for minimised differences to your code)
    int n = sizeof(myArray)/sizeof(int);

void MakeRandArray(int *ptr)
{
    int i;
    for(i = 0; i < n; i++)
    {
        *(ptr + i) = rand();
    }
}

void PrintArray(int *ptr)
{
    int i;
    for(i = 0; i < n; i++)
    {
        printf("%8d\n", *(ptr + i));
    }
    printf("\n");
}

void SortArray(int *ptr)
{
    // this is far off even the simplest sorting algorithms
    // it is worth reading up on one (e.g. the quite simple bubble sort),
    // then enjoy optimising this (my) totally blind method here;
    // note that I sort within the original array,
    // you seem to intend to keep unsorted in addition to sorted
    int i;
    int j;
    for (j = 0; j < n; j++)
    {
        for (i = 0; i < n-1; i++)
        {   int help;
            if (*(ptr+i) > *(ptr + i + 1))
            {
                help = *(ptr+i);
                *(ptr + i) = *(ptr + i + 1);
                *(ptr + i + 1)=help;
            }
        }
    }
}

int main(void)
{
    MakeRandArray(ptr);
    PrintArray(ptr);
    SortArray(ptr);
    PrintArray(ptr);

    return 0;
}
</code>```

Output:

```<code>      41
   18467
    6334
   26500
   19169
   15724
   11478
   29358
   26962
   24464

      41
    6334
   11478
   15724
   18467
   19169
   24464
   26500
   26962
   29358
</code>```

Body:
I'm new to C and I can't find any answers on why it's giving me an error: expression is not assignable on lines 11 and 20.

This is a simple code for creating a random array and then sort it using a subroutine. I'm still learning C and couldn't find a solution with any research.

Here is my code:

#include <stdio.h>
#include <stdlib.h>
int myArray[100];
int* ptr = myArray;
int i;
int n = sizeof(myArray);
int SortedArray[100];

int MakeRandArray(ptr, i)
{
    for (i = 0; i < n; i++) {
        (ptr + i) = rand()
    }
}

int SortArray(ptr)
{
    int a;
    int j = (i + 1);
    for (i = 0; i < n; i++) {
        if ((ptr + i) > (ptr + j)) {
            (ptr + i) = (ptr + j)
        }
    }
}

int main()
{
    MakeRandArray(*ptr, i);
    SortArray(*ptr);
}

Body:
Here is a version with the errors avoided and -Wallwarnings, too.

I did not change things which are against good coding practice. Take some time later to learn about those, too. Read the comments on your question and on this answer for doing that.
As an encore I got your sorting working (in a very blind, inefficient way) and added a printer, for demonstration purposes. I use array size 10 instead of 100, for convenience. It seems that you intend to keep the orignal array and create a sorted version, I left that for you.

#include <stdio.h>
#include <stdlib.h>
    int myArray[10];
    int *ptr = myArray;
    // int i; Do not use globals for counters inside functions.

    // it would be better to give the size of arrays as an explicit
    // parameter to functions, instead of using a global variable
    // (keeping this only for minimised differences to your code)
    int n = sizeof(myArray)/sizeof(int);

void MakeRandArray(int *ptr)
{
    int i;
    for(i = 0; i < n; i++)
    {
        *(ptr + i) = rand();
    }
}

void PrintArray(int *ptr)
{
    int i;
    for(i = 0; i < n; i++)
    {
        printf("%8d\n", *(ptr + i));
    }
    printf("\n");
}

void SortArray(int *ptr)
{
    // this is far off even the simplest sorting algorithms
    // it is worth reading up on one (e.g. the quite simple bubble sort),
    // then enjoy optimising this (my) totally blind method here;
    // note that I sort within the original array,
    // you seem to intend to keep unsorted in addition to sorted
    int i;
    int j;
    for (j = 0; j < n; j++)
    {
        for (i = 0; i < n-1; i++)
        {   int help;
            if (*(ptr+i) > *(ptr + i + 1))
            {
                help = *(ptr+i);
                *(ptr + i) = *(ptr + i + 1);
                *(ptr + i + 1)=help;
            }
        }
    }
}

int main(void)
{
    MakeRandArray(ptr);
    PrintArray(ptr);
    SortArray(ptr);
    PrintArray(ptr);

    return 0;
}

Output:

      41
   18467
    6334
   26500
   19169
   15724
   11478
   29358
   26962
   24464

      41
    6334
   11478
   15724
   18467
   19169
   24464
   26500
   26962
   29358


问:
modify plist inside list?
I have a list of plists such as

```<code>'((:atom Toddler :visited nil :on-clauses (0 1))
  (:atom Child   :visited nil :on-clauses 1))
</code>```

how should I change the :onclauses property on a given :atom? I'd like to update this property, e.g. making the second plist (:atom Child :visited nil :on-clauses (1 2)) (only adding new values, never deleting the old ones).

the best I could do was to create a new list from scratch using

```<code>(remove-if-not #'(lambda(record)
                   (equal (getf record :atom) atom))
               *ATOMS*)
</code>```

to get the initial value, updating it, then using its analogue to get a list without this value, and append both together, but this is probably terribly inneficient (I know premature optimatization is bad, but I'm learning LISP and want to know how to do things properly!)

答:
these three functions seem to do the trick, as plists are destructively modified.</p>

```<code>(defun update-atom(atom ix)
  "adds to the atom's on-clauses property another clause where it was found."
   (let ((atomo (find-atom atom)))
    (setf (getf atomo :on-clauses) (cons ix (get-indices atom)))))

(defun find-atom(atom)   "returns the property list of a given atom"
  (first (remove-if-not #'(lambda(record) (equal (getf record :atom) atom)) *ATOMS*)))

(defun get-indices(atom)
  "gets indices of clauses where atom is found."
  (getf (find-atom atom) :on-clauses))
</code>```

Title: modify plist inside list?

Body:
I have a list of plists such as

'((:atom Toddler :visited nil :on-clauses (0 1))
  (:atom Child   :visited nil :on-clauses 1))

how should I change the :onclauses property on a given :atom? I'd like to update this property, e.g. making the second plist (:atom Child :visited nil :on-clauses (1 2)) (only adding new values, never deleting the old ones).

the best I could do was to create a new list from scratch using

(remove-if-not #'(lambda(record)
                   (equal (getf record :atom) atom))
               *ATOMS*)

to get the initial value, updating it, then using its analogue to get a list without this value, and append both together, but this is probably terribly inneficient (I know premature optimatization is bad, but I'm learning LISP and want to know how to do things properly!)

Body:
these three functions seem to do the trick, as plists are destructively modified.

(defun update-atom(atom ix)
  "adds to the atom's on-clauses property another clause where it was found."
   (let ((atomo (find-atom atom)))
    (setf (getf atomo :on-clauses) (cons ix (get-indices atom)))))

(defun find-atom(atom)   "returns the property list of a given atom"
  (first (remove-if-not #'(lambda(record) (equal (getf record :atom) atom)) *ATOMS*)))

(defun get-indices(atom)
  "gets indices of clauses where atom is found."
  (getf (find-atom atom) :on-clauses))


问:
Odoo workflow - How to hide/show workflow stage dynamically
I have a workflow stages ( Draft > Confirmed > Rejected > Done )

My goal are the following:

Initially I want to display in my workflow status as the following "Draft > Confirmed > Done"

When i click "Mark as Rejected",  the workflow status should hide the "Done" status bar and replace it by the "Rejected"

When i click "Mark as Done",  the workflow status should hide the "Reject" status bar and replace it by the "Done"

答:
check the attribute statusbar_visible

example

```<code>    <field name="state" widget="statusbar" **statusbar_visible**="open,close" statusbar_colors='{"pending":"blue"}' readonly="1"/>
</code>```

Body:
check the attribute statusbar_visible

example

    <field name="state" widget="statusbar" **statusbar_visible**="open,close" statusbar_colors='{"pending":"blue"}' readonly="1"/>


问:
pick first item of repeated in rxjs
I am receiving a bunch of streams from socket and want to merge repeated streams into one stream (or pick the first item)

In summary I want do this by rxjs:

```<code>In:  1 - 1 - 1 - 2 - 2 - 3 - 3 - 1 - 1 - 1 - 2 - 2 - 2 - 1 - 2 - 2 - 3 - 3
Out: 1 - - - - - 2 - - - 3 - - - 1 - - - - - 2 - - - - - 1 - 2 - - - 3 - -
</code>```

答:
Here is an approach that uses the Array.fitler() function:

```<code>[1,1,1,2,2,3,3,1,1,1,2,2,2,2,1,2,2,3,3].filter((value, index, src) => {
  if(index === 0) {
    //The first element of the array is always included
    return true;
  }
  // Return true (keep) if the current element `value` is different
  // than the element that was last encountered (`src[index-1]`)
  return src[index-1] !== value;
});
</code>```

The output to this is:

```<code>[ 1, 2, 3, 1, 2, 1, 2, 3 ]
</code>```

This works by iterating over the array and checking if each element is the same or different than the on that precedes it.  Here is the same thing but as a one liner:

```<code>[1,1,1,2,2,3,3,1,1,1,2,2,2,2,1,2,2,3,3].filter((value, index, src) => {
  return index === 0 || src[index-1] !== value;
});
</code>```

Title: pick first item of repeated in rxjs

Body:
I am receiving a bunch of streams from socket and want to merge repeated streams into one stream (or pick the first item)

In summary I want do this by rxjs:

In:  1 - 1 - 1 - 2 - 2 - 3 - 3 - 1 - 1 - 1 - 2 - 2 - 2 - 1 - 2 - 2 - 3 - 3
Out: 1 - - - - - 2 - - - 3 - - - 1 - - - - - 2 - - - - - 1 - 2 - - - 3 - -

Body:
Here is an approach that uses the Array.fitler() function:

[1,1,1,2,2,3,3,1,1,1,2,2,2,2,1,2,2,3,3].filter((value, index, src) => {
  if(index === 0) {
    //The first element of the array is always included
    return true;
  }
  // Return true (keep) if the current element `value` is different
  // than the element that was last encountered (`src[index-1]`)
  return src[index-1] !== value;
});

The output to this is:

[ 1, 2, 3, 1, 2, 1, 2, 3 ]

This works by iterating over the array and checking if each element is the same or different than the on that precedes it.  Here is the same thing but as a one liner:

[1,1,1,2,2,3,3,1,1,1,2,2,2,2,1,2,2,3,3].filter((value, index, src) => {
  return index === 0 || src[index-1] !== value;
});


问:
C# Ftp Upload in Windows 10 Universal app?
I want to upload files from windows 10 app using ftp, I tried the following code.

```<code>    using System;
    using System.IO;
    using System.Net;
    using System.Text;

    namespace Examples.System.Net
    {
        public class WebRequestGetExample
        {
            public static void Main ()
            {
        // Get the object used to communicate with the server.
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");
        request.Method = WebRequestMethods.Ftp.UploadFile;

        // This example assumes the FTP site uses anonymous logon.
        request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");

        // Copy the contents of the file to the request stream.
        StreamReader sourceStream = new StreamReader("testfile.txt");
        byte [] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
        sourceStream.Close();
        request.ContentLength = fileContents.Length;

        Stream requestStream = request.GetRequestStream();
        requestStream.Write(fileContents, 0, fileContents.Length);
        requestStream.Close();

        FtpWebResponse response = (FtpWebResponse)request.GetResponse();

        Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);

        response.Close();
        }
    }
        }
    }
</code>```

But visual studio couldn't find the name space FtpWebRequest or WebRequestMethods. The other method i tried using backgroundtransfer api's from link but it says that  WinRT information: 'uri': Uploading content is only supported for 'http' and 'https' schemes. not ftp.

So is there any solution to this where i can show progress bar and speed?

答:
Try this:
https://github.com/kiewic/FtpClient

If you cannot open the project (e. g. with VS 2017), just take the two relevant classes from it.

Body:
I want to upload files from windows 10 app using ftp, I tried the following code.

    using System;
    using System.IO;
    using System.Net;
    using System.Text;

    namespace Examples.System.Net
    {
        public class WebRequestGetExample
        {
            public static void Main ()
            {
        // Get the object used to communicate with the server.
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");
        request.Method = WebRequestMethods.Ftp.UploadFile;

        // This example assumes the FTP site uses anonymous logon.
        request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");

        // Copy the contents of the file to the request stream.
        StreamReader sourceStream = new StreamReader("testfile.txt");
        byte [] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
        sourceStream.Close();
        request.ContentLength = fileContents.Length;

        Stream requestStream = request.GetRequestStream();
        requestStream.Write(fileContents, 0, fileContents.Length);
        requestStream.Close();

        FtpWebResponse response = (FtpWebResponse)request.GetResponse();

        Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);

        response.Close();
        }
    }
        }
    }

But visual studio couldn't find the name space FtpWebRequest or WebRequestMethods. The other method i tried using backgroundtransfer api's from link but it says that  WinRT information: 'uri': Uploading content is only supported for 'http' and 'https' schemes. not ftp.

So is there any solution to this where i can show progress bar and speed?


问:
Filter and search DataGridView connected to a MS Access database in C#
I use this code to filter and search a DataGridView connected to a MS Access database in C#, but when I enter anything into the textbox, every row of data in the DataGridView  disappears - any help?

This code to appear in datagridview

```<code>    connection.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\AMR\Desktop\ABBagain-Copy.accdb;
Persist Security Info=False;";
                connection.Open();
                OleDbCommand command = new OleDbCommand();
                command.Connection = connection;
                string query = "select * from Query1";

                command.CommandText = query;
                OleDbDataAdapter da = new OleDbDataAdapter(command);
                DataTable dt;
                dt = new DataTable();
                da.Fill(dt);
                dataGridView1.DataSource = dt;
                da.Fill(dscontects);
                connection.Close();
</code>```

and this in textbox

```<code>DataView dv = new DataView(dt);
        dv.RowFilter = string.Format("SerialNumber LIKE '%{0}%'",textBox1.Text);
        table1DataGridView.DataSource = dv;
</code>```

答:
put all this code inside textbox keyup and make some changes like database and field name

string strProvider="Provider=Microsoft.ACE.OLEDB.12.0;Data      Source=Gym.accdb";

```<code>      string strSql = "Select * from cust";

      OleDbConnection con = new OleDbConnection(strProvider);

      OleDbCommand cmd = new OleDbCommand(strSql, con);

      con.Open();

      cmd.CommandType = CommandType.Text;

      OleDbDataAdapter da = new OleDbDataAdapter(cmd);

      DataTable scores = new DataTable();

      da.Fill(scores);

      dglist.DataSource = scores;

      DataView dv = new DataView(scores);

      dv.RowFilter = string.Format("name LIKE '%{0}%'", txtsearch.Text);

      dglist.DataSource = dv;
</code>```

Body:
I use this code to filter and search a DataGridView connected to a MS Access database in C#, but when I enter anything into the textbox, every row of data in the DataGridView  disappears - any help?

This code to appear in datagridview

    connection.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\AMR\Desktop\ABBagain-Copy.accdb;
Persist Security Info=False;";
                connection.Open();
                OleDbCommand command = new OleDbCommand();
                command.Connection = connection;
                string query = "select * from Query1";

                command.CommandText = query;
                OleDbDataAdapter da = new OleDbDataAdapter(command);
                DataTable dt;
                dt = new DataTable();
                da.Fill(dt);
                dataGridView1.DataSource = dt;
                da.Fill(dscontects);
                connection.Close();

and this in textbox

DataView dv = new DataView(dt);
        dv.RowFilter = string.Format("SerialNumber LIKE '%{0}%'",textBox1.Text);
        table1DataGridView.DataSource = dv;

Body:
put all this code inside textbox keyup and make some changes like database and field name

string strProvider="Provider=Microsoft.ACE.OLEDB.12.0;Data      Source=Gym.accdb";

      string strSql = "Select * from cust";

      OleDbConnection con = new OleDbConnection(strProvider);

      OleDbCommand cmd = new OleDbCommand(strSql, con);

      con.Open();

      cmd.CommandType = CommandType.Text;

      OleDbDataAdapter da = new OleDbDataAdapter(cmd);

      DataTable scores = new DataTable();

      da.Fill(scores);

      dglist.DataSource = scores;

      DataView dv = new DataView(scores);

      dv.RowFilter = string.Format("name LIKE '%{0}%'", txtsearch.Text);

      dglist.DataSource = dv;