问:
Can't call function inside custom directive. Scope is not what I want to use
I used to have this inside my html 'calculations-td-plan.html'

```<code><tr ng-repeat="foodCalculation in selectedMealCalc.calculated_foods">
          <td>{{foodCalculation.food.name}}</td>
          <td>{{foodCalculation.gram_amount}} g</td>
          <td>{{foodCalculation.kcal}} kcal</td>
          <td>{{foodCalculation.proteina}} g</td>
          <td>{{foodCalculation.cho}} g</td>
          <td>{{foodCalculation.lipideos}} g</td>
          <td class="text-center">
            <button class="btn btn--principal btn--xs" ng-click="edtiFoodCalc(selectedmealcalc, foodCalculation, $index)">Editar</button>
            <button class="btn btn--principal btn--xs" ng-click="removeFoodCalc(selectedmealcalc, foodCalculation)">Remover</button>
          </td>
        </tr>
</code>```

Then I create a directive like above.

```<code><div class="row">
  <div class="col-md-12" ng-show="( items | filter: { food_option: option } ).length > 0">
    Opção {{ option }}
    <table class="table table-calculo table-striped">
      <thead>
        <tr>
          <th>Alimento</th>
        </tr>
      </thead>
      <tbody>
        <tr ng-repeat="foodCalculation in ( items | filter: { food_option: option } ) track by $index">
          <td>{{foodCalculation.food.name}}</td>
          <td class="text-center">
            <button class="btn btn--principal btn--xs" ng-click="edtiFoodCalc(selectedmealcalc, foodCalculation, $index)">Editar</button>
            <button class="btn btn--principal btn--xs" ng-click="removeFoodCalc(selectedmealcalc, foodCalculation)">Remover</button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</div>
</code>```

And I call this diretive inside 'calculations-td-plan.html' as

```<code><div ng-repeat="option in [0,1,2,3,4]">
    <meal-option option="{{option}}"
                 items="selectedMealCalc.calculated_foods"
                 selectedmealcalc="selectedMealCalc"></meal-option>
</div>
</code>```

And this is my directive JS.

```<code>'use strict';

angular.module('nutriApp').directive('mealOption', ['$compile', function($compile) {
  var mealOption = {
    restrict: 'E',
    templateUrl: 'views/checkins/meal-options.html',
    require: 'foodSelector',
    scope: {
      option: "@",
      items: "=",
      selectedmealcalc: "="
    }
  };

  mealOption.controller = ['$scope', 'Food', function($scope, Food) {
    $scope.sumFood = {};
    $scope.summerizeOption = function(foods) {
      if(foods.length > 0){
          $scope.sumFood = Food.summerize(foods);
      }
    };
  }];

  return mealOption;

}]);
</code>```

But now the funcions that I am calling edtiFoodCalc and removeFoodCalc are not working.

When I put ng-controller in my directive it works, (Only call the method) but I can't get the same scope.

```<code><div class="row" ng-controller="CheckinsPlansCtrl">
</code>```

I am trying to edit with edtiFoodCalc and I am not getting the result that I want. I think ng-controller creates new scopes when I do ng-repeat, and when I did not have a directive the code worked.

```<code><div ng-repeat="option in [0,1,2,3,4]">
        <meal-option option="{{option}}"
                     items="selectedMealCalc.calculated_foods"
                     selectedmealcalc="selectedMealCalc"></meal-option>
    </div>
</code>```

答:
You can use angular's & binding, which allows the directive's scope to pass values back to the parent scope. These values don't need to be defined in the controller - they can be defined in the directive and then sent back to the controller.

For example, given a controller and directive:

```<code>// Controller
app.controller('MainCtrl', function($scope) {
  $scope.funcA = function(value, index) {
    console.log("Called funcA from " + value + " with index " + String(index));
  };

  $scope.funcB = function(value, index) {
    console.log("Called funcB from " + value + " with index " + String(index));
  }
});

// Directive
app.directive('arrayDirective', function() {
  return {
    templateUrl: "array_directive.html",
    scope: {
      controllerFuncA: "&controllerFuncA",
      controllerFuncB: "&controllerFuncB"
    },
    link: function (scope, element, attr) {
      scope.items = ["a","b","c","d","e"];

      scope.callControllerFuncA = function(i) {
        console.log("Calling controller funcA!");
        scope.controllerFuncA({from: "directive", index: i});
      };

      scope.callControllerFuncB = function(i) {
        console.log("Calling controller funcB!");
        scope.controllerFuncB({from: "directive", index: i});
      };
    }
  };
});
</code>```

And the following templates:

```<code><!-- Controller template -->
<body ng-controller="MainCtrl">
  <array-directive controller-func-a="funcA(from, index)" controller-func-b="funcB(from, index)"></array-directive>
</body>

<!-- Directive template -->
<div>
  <div ng-repeat="item in items">
    <div>{{item}}</div>
    <div><a href="#" ng-click="callControllerFuncA($index)">Call Controller Func A</a></div>
    <div><a href="#" ng-click="callControllerFuncB($index)">Call Controller Func B</a></div>
  </div>
</div>
</code>```

You can then use controllerFuncA and controllerFuncB from within the directive to call the corresponding parent controller functions, funcA and funcB. Note that these directive functions take an object as the parameter, where the keys of the object correspond to the keys that you passed into the directive on the <array-directive> tag.

See the attached fiddle and watch the developer console for the complete example: https://plnkr.co/edit/3h8J00ndBk4OQ16C8hf2

Body:
I used to have this inside my html 'calculations-td-plan.html'

          {{foodCalculation.food.name}}
          {{foodCalculation.gram_amount}} g
          {{foodCalculation.kcal}} kcal
          {{foodCalculation.proteina}} g
          {{foodCalculation.cho}} g
          {{foodCalculation.lipideos}} g

            <button class="btn btn--principal btn--xs" ng-click="edtiFoodCalc(selectedmealcalc, foodCalculation, $index)">Editar</button>
            <button class="btn btn--principal btn--xs" ng-click="removeFoodCalc(selectedmealcalc, foodCalculation)">Remover</button>

Then I create a directive like above.

 0">
    Opção {{ option }}

          Alimento

          {{foodCalculation.food.name}}

            <button class="btn btn--principal btn--xs" ng-click="edtiFoodCalc(selectedmealcalc, foodCalculation, $index)">Editar</button>
            <button class="btn btn--principal btn--xs" ng-click="removeFoodCalc(selectedmealcalc, foodCalculation)">Remover</button>

And I call this diretive inside 'calculations-td-plan.html' as

    <meal-option option="{{option}}"
                 items="selectedMealCalc.calculated_foods"
                 selectedmealcalc="selectedMealCalc"></meal-option>

And this is my directive JS.

'use strict';

angular.module('nutriApp').directive('mealOption', ['$compile', function($compile) {
  var mealOption = {
    restrict: 'E',
    templateUrl: 'views/checkins/meal-options.html',
    require: 'foodSelector',
    scope: {
      option: "@",
      items: "=",
      selectedmealcalc: "="
    }
  };

  mealOption.controller = ['$scope', 'Food', function($scope, Food) {
    $scope.sumFood = {};
    $scope.summerizeOption = function(foods) {
      if(foods.length > 0){
          $scope.sumFood = Food.summerize(foods);
      }
    };
  }];

  return mealOption;

}]);

But now the funcions that I am calling edtiFoodCalc and removeFoodCalc are not working.

When I put ng-controller in my directive it works, (Only call the method) but I can't get the same scope.

I am trying to edit with edtiFoodCalc and I am not getting the result that I want. I think ng-controller creates new scopes when I do ng-repeat, and when I did not have a directive the code worked.

        <meal-option option="{{option}}"
                     items="selectedMealCalc.calculated_foods"
                     selectedmealcalc="selectedMealCalc"></meal-option>

Body:
You can use angular's & binding, which allows the directive's scope to pass values back to the parent scope. These values don't need to be defined in the controller - they can be defined in the directive and then sent back to the controller.

For example, given a controller and directive:

// Controller
app.controller('MainCtrl', function($scope) {
  $scope.funcA = function(value, index) {
    console.log("Called funcA from " + value + " with index " + String(index));
  };

  $scope.funcB = function(value, index) {
    console.log("Called funcB from " + value + " with index " + String(index));
  }
});

// Directive
app.directive('arrayDirective', function() {
  return {
    templateUrl: "array_directive.html",
    scope: {
      controllerFuncA: "&controllerFuncA",
      controllerFuncB: "&controllerFuncB"
    },
    link: function (scope, element, attr) {
      scope.items = ["a","b","c","d","e"];

      scope.callControllerFuncA = function(i) {
        console.log("Calling controller funcA!");
        scope.controllerFuncA({from: "directive", index: i});
      };

      scope.callControllerFuncB = function(i) {
        console.log("Calling controller funcB!");
        scope.controllerFuncB({from: "directive", index: i});
      };
    }
  };
});

And the following templates:

<!-- Controller template -->
<body ng-controller="MainCtrl">
  <array-directive controller-func-a="funcA(from, index)" controller-func-b="funcB(from, index)"></array-directive>
</body>

<!-- Directive template -->
<div>
  <div ng-repeat="item in items">
    <div>{{item}}</div>
    <div><a href="#" ng-click="callControllerFuncA($index)">Call Controller Func A</a></div>
    <div><a href="#" ng-click="callControllerFuncB($index)">Call Controller Func B</a></div>
  </div>
</div>

You can then use controllerFuncA and controllerFuncB from within the directive to call the corresponding parent controller functions, funcA and funcB. Note that these directive functions take an object as the parameter, where the keys of the object correspond to the keys that you passed into the directive on the <array-directive> tag.

See the attached fiddle and watch the developer console for the complete example: https://plnkr.co/edit/3h8J00ndBk4OQ16C8hf2


来源: stackexchange

问:
Better way to convert JSON to arrays for graphing timeseries in C3?
I'm working on converting some JSON data into a format that will work for graphing a timeseries in C3, which takes an array of arrays as column input. I have my unique x values array, but I can't figure out a great way to get my y values. Once I get this done, I need to add y2 with numSold, but I think if I can solve this, I'll be able to figure that part out.

This is the final format I need for the data:

```<code>[
  ["x", "9-2-17", "9-4-17", "10-2-17"],
  ['item1-cost', 100, 150, 10],
  ['item3-cost', 200, null, 20],
  ...
]
</code>```

There isn't a set number of dates or set number of items. It's whatever I read from the database. The item numbers aren't necessarily consecutive. We only care about graphing the data for items we have data for. But there won't be data for every date-item combination. When that happens, I need to insert a null to indicate that the item didn't have data for that date. Item numbers are 1-indexed.

I'm fine with using anything from lo-dash or D3 in addition to the plain JavaScript functions to solve this, but I'm trying to avoid hard to read code and inefficient code. I feel like others must have had a need for this and that there must be some sort of function like maybe a filter function that I should be using instead.

My current implementation is not as efficient  as I'd like and is a bit hard to read. I'm using the item number as an index and making a sparse array that I'll have to condense later. Here's the psudocode:

```<code>For every d object in data
  For the i index of d.date in uniqueDates
    If values[d.item] is undefined
      Fill values[d.item]] with null for uniqueDates.length
    Set values[d.item][i] to d.cost
Convert values to dense format for graphing
</code>```

Here's a link to the Fiddle I'm playing with:

https://jsfiddle.net/dbkidd/q3r3moqu/

```<code>var data = [
  {date: '9-2-17', item: 1, cost: 100},
  {date: '9-2-17', item: 3, cost: 200},
  {date: '9-4-17', item: 1, cost: 150},
  /* '9-4-17' does not have an entry for item 3 so cost should be counted as null */
  {date: '10-2-17', item: 1, cost: 10},
  {date: '10-2-17', item: 3, cost: 20}
]

var uniqueDates = _.uniq(_.flatMap(data, 'date'));
uniqueDates.unshift('x');

var values = [];
values.push(uniqueDates);

function getLabel(index) {
  return 'item' + index + '-' + 'cost';
}

for (var d = 0; d < data.length; d++) {
  var i = _.indexOf(uniqueDates, data[d].date);
  if (data[d].item !== undefined) {
    var item = data[d].item;
    if (values[item] === undefined) {
        values[item] = _.fill(Array(uniqueDates.length), null);
        values[item][0] = getLabel(item);
    }
    values[item][i] = data[d].cost;
    }
}

function checkIfUndefined(x) {
    return (x !== undefined);
}

function sparseToDense(data) {
  return data.filter(checkIfUndefined);
}

values = sparseToDense(values);
</code>```

答:
I was intrigued by this problem and came up with a first version. It's a little different than yours but here it is. I will note that I didn't try to sort the dates or rename the items to something useful but those can be added.

var data = [
 {date: '9-2-17', item: 1, cost: 100},
  {date: '9-2-17', item: 3, cost: 200},
  {date: '9-4-17', item: 1, cost: 150},
  /* '9-4-17' does not have an entry for item 3 so cost should be counted as null */
  {date: '10-2-17', item: 1, cost: 10},
  {date: '10-2-17', item: 3, cost: 20},
  {date: '10-3-17', item: 2, cost: 2000}
]

// utility functions
const product = (...sets) =>
  sets.reduce((acc, set) =>
    _.flatten(acc.map(x => set.map(y => [ ...x, y ]))),
    [[]]);

// the meat and potatoes
const builder = lookup => pairs => pairs.reduce((agg, [item, date]) => {
   const out = _.cloneDeep(agg);
   const value = _.get(lookup, [date, item, 'cost'], null);
   const evalue = _.get(out, date, []);
   evalue.push(value);
   _.set(out, date, evalue);
   return out;
}, {})

// setup data structures for searching
const byDateByItem = _.mapValues(_.groupBy(data, 'date'), x => _.keyBy(x, 'item'));
const items = _.uniq(data.map(x=>x.item));
const dates = _.uniq(data.map(x=>x.date));

// create all posibilities
const pairs = product(items, dates);
// populate possibilities with values
const hash = builder(byDateByItem)(pairs);
// put keys with values in their respective lists
const p = _.toPairs(hash).map(_.flatten);
// smash data into a matrix type thing
const table = [['x',...items], ...p];
// flip the table on it's side (╯°□°）╯︵ ┻━┻
const out = _.zip(...table);
console.log('out', out);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script></code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm working on converting some JSON data into a format that will work for graphing a timeseries in C3, which takes an array of arrays as column input. I have my unique x values array, but I can't figure out a great way to get my y values. Once I get this done, I need to add y2 with numSold, but I think if I can solve this, I'll be able to figure that part out.

This is the final format I need for the data:

[
  ["x", "9-2-17", "9-4-17", "10-2-17"],
  ['item1-cost', 100, 150, 10],
  ['item3-cost', 200, null, 20],
  ...
]

There isn't a set number of dates or set number of items. It's whatever I read from the database. The item numbers aren't necessarily consecutive. We only care about graphing the data for items we have data for. But there won't be data for every date-item combination. When that happens, I need to insert a null to indicate that the item didn't have data for that date. Item numbers are 1-indexed.

I'm fine with using anything from lo-dash or D3 in addition to the plain JavaScript functions to solve this, but I'm trying to avoid hard to read code and inefficient code. I feel like others must have had a need for this and that there must be some sort of function like maybe a filter function that I should be using instead.

My current implementation is not as efficient  as I'd like and is a bit hard to read. I'm using the item number as an index and making a sparse array that I'll have to condense later. Here's the psudocode:

For every d object in data
  For the i index of d.date in uniqueDates
    If values[d.item] is undefined
      Fill values[d.item]] with null for uniqueDates.length
    Set values[d.item][i] to d.cost
Convert values to dense format for graphing

Here's a link to the Fiddle I'm playing with:

https://jsfiddle.net/dbkidd/q3r3moqu/

var data = [
  {date: '9-2-17', item: 1, cost: 100},
  {date: '9-2-17', item: 3, cost: 200},
  {date: '9-4-17', item: 1, cost: 150},
  /* '9-4-17' does not have an entry for item 3 so cost should be counted as null */
  {date: '10-2-17', item: 1, cost: 10},
  {date: '10-2-17', item: 3, cost: 20}
]

var uniqueDates = _.uniq(_.flatMap(data, 'date'));
uniqueDates.unshift('x');

var values = [];
values.push(uniqueDates);

function getLabel(index) {
  return 'item' + index + '-' + 'cost';
}

for (var d = 0; d < data.length; d++) {
  var i = _.indexOf(uniqueDates, data[d].date);
  if (data[d].item !== undefined) {
    var item = data[d].item;
    if (values[item] === undefined) {
        values[item] = _.fill(Array(uniqueDates.length), null);
        values[item][0] = getLabel(item);
    }
    values[item][i] = data[d].cost;
    }
}

function checkIfUndefined(x) {
    return (x !== undefined);
}

function sparseToDense(data) {
  return data.filter(checkIfUndefined);
}

values = sparseToDense(values);

Body:
I was intrigued by this problem and came up with a first version. It's a little different than yours but here it is. I will note that I didn't try to sort the dates or rename the items to something useful but those can be added.

var data = [
 {date: '9-2-17', item: 1, cost: 100},
  {date: '9-2-17', item: 3, cost: 200},
  {date: '9-4-17', item: 1, cost: 150},
  /* '9-4-17' does not have an entry for item 3 so cost should be counted as null */
  {date: '10-2-17', item: 1, cost: 10},
  {date: '10-2-17', item: 3, cost: 20},
  {date: '10-3-17', item: 2, cost: 2000}
]

// utility functions
const product = (...sets) =>
  sets.reduce((acc, set) =>
    _.flatten(acc.map(x => set.map(y => [ ...x, y ]))),
    [[]]);

// the meat and potatoes
const builder = lookup => pairs => pairs.reduce((agg, [item, date]) => {
   const out = _.cloneDeep(agg);
   const value = _.get(lookup, [date, item, 'cost'], null);
   const evalue = _.get(out, date, []);
   evalue.push(value);
   _.set(out, date, evalue);
   return out;
}, {})

// setup data structures for searching
const byDateByItem = _.mapValues(_.groupBy(data, 'date'), x => _.keyBy(x, 'item'));
const items = _.uniq(data.map(x=>x.item));
const dates = _.uniq(data.map(x=>x.date));

// create all posibilities
const pairs = product(items, dates);
// populate possibilities with values
const hash = builder(byDateByItem)(pairs);
// put keys with values in their respective lists
const p = _.toPairs(hash).map(_.flatten);
// smash data into a matrix type thing
const table = [['x',...items], ...p];
// flip the table on it's side (╯°□°）╯︵ ┻━┻
const out = _.zip(...table);
console.log('out', out);

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


问:
Inject external dependency Spring microservices
We are using spring boot microservices in our product , we are having up to 10 applications . In order to log we use Log4j MDC to generate transaction id and pass it along the services [http headers] using interceptors and filters and its working fine.
The problem is we have to add interceptors and filters in all our applications (say 10) to track this transaction.Is there any way like creating jar and inject in our microservice applications.

Can we achieve this using with minimal code changes in all our application ?

答:
From the filters project which builds a jar to be shared, provide a class which can be scanned by Spring to create the beans with a well defined name.  For example:

```<code>package com.me.common.interceptors;

public class InterceptorConfig {
    public static final String INTERCEPTOR_BEAN_1 = "comMeCommonInterceptorsInterceptor1";
    public static final String INTERCEPTOR_BEAN_2 = "comMeCommonInterceptorsInterceptor2";

    @Bean(name = INTERCEPTOR_BEAN_1)
    public HandlerInterceptor getInterceptor1() {
         return new Interceptor1();
    }

    @Bean(name = INTERCEPTOR_BEAN_1)
    public HandlerInterceptor getInterceptor2() {
         return new Interceptor2();
    }

}

public class Interceptor1 implements HandlerInterceptor {
  // ...
}

public class Interceptor2 implements HandlerInterceptor {
  // ...
}
</code>```

Then configure the app to scan the com.me.common.interceptors package to create the beans.  It doesn't matter the code is in a jar.

Within the app, those beans can then be autowired by name, and registered as usual.

```<code>@Autowired
@Qualifier(InterceptorConfig .FILTER_BEAN_1)
private HandlerInterceptor interceptor1;

@Autowired
@Qualifier(InterceptorConfig .FILTER_BEAN_2)
private HandlerInterceptor interceptor2;
</code>```

Body:
From the filters project which builds a jar to be shared, provide a class which can be scanned by Spring to create the beans with a well defined name.  For example:

package com.me.common.interceptors;

public class InterceptorConfig {
    public static final String INTERCEPTOR_BEAN_1 = "comMeCommonInterceptorsInterceptor1";
    public static final String INTERCEPTOR_BEAN_2 = "comMeCommonInterceptorsInterceptor2";

    @Bean(name = INTERCEPTOR_BEAN_1)
    public HandlerInterceptor getInterceptor1() {
         return new Interceptor1();
    }

    @Bean(name = INTERCEPTOR_BEAN_1)
    public HandlerInterceptor getInterceptor2() {
         return new Interceptor2();
    }

}

public class Interceptor1 implements HandlerInterceptor {
  // ...
}

public class Interceptor2 implements HandlerInterceptor {
  // ...
}

Then configure the app to scan the com.me.common.interceptors package to create the beans.  It doesn't matter the code is in a jar.

Within the app, those beans can then be autowired by name, and registered as usual.

@Autowired
@Qualifier(InterceptorConfig .FILTER_BEAN_1)
private HandlerInterceptor interceptor1;

@Autowired
@Qualifier(InterceptorConfig .FILTER_BEAN_2)
private HandlerInterceptor interceptor2;


问:
ddply summarize count based on string
My dataframe looks like this:

```<code>   userid                           Worktype  dwelltime
1 ABENAVI  Check Hazmat label Msg for carton  0.7666667
2 ARMITAJ  Check Hazmat label Msg for carton  0.3333333
3 ARMITAJ  Check Hazmat label Msg for carton  0.4166667
4 ARMITAJ         scanned to wrong sort rule  0.6500000
5 ARMITAJ         scanned to wrong sort rule  0.4666667
6 ARMITAJ  Check Hazmat label Msg for carton  0.4666667
7 ARMITAJ  Check Hazmat label Msg for carton 12.2333333
8 ARMITAJ  Check Hazmat label Msg for carton  4.5000000
</code>```

I want to get the number of times each userid has "scanned wrong sort rule" as their worktype.

My result would look like

```<code>userid    Worktype  Count
ABENAVI   Scanned to wrong sort rule       2
Nithin    Scanned to wrong sortrule        0
</code>```

I have written this code, which has been giving me an error

"Error in ifelse(x[, "rf_log2$Worktype"] == "scanned to wrong sort rule",  :    unused argument (0)"

My code is:

```<code>quality <- ddply(rf_log2, .(userid), function(x) c(
              rules <- sum(ifelse(x[ ,"Worktype"] == "scanned to wrong sort rule", x[,"Worktype"],1,0), na.rm = TRUE)))
</code>```

答:
You could create a vector checking whether df$Worktype is equal to "scanned to wrong sort rule" and then use table to get the counts per userid:

```<code>df$check <- (df$Worktype == "scanned to wrong sort rule")
table(df[, c(1,4)])[, 2]
# ABENAVI ARMITAJ
#       0       2
</code>```

Title: ddply summarize count based on string

Body:
My dataframe looks like this:

   userid                           Worktype  dwelltime
1 ABENAVI  Check Hazmat label Msg for carton  0.7666667
2 ARMITAJ  Check Hazmat label Msg for carton  0.3333333
3 ARMITAJ  Check Hazmat label Msg for carton  0.4166667
4 ARMITAJ         scanned to wrong sort rule  0.6500000
5 ARMITAJ         scanned to wrong sort rule  0.4666667
6 ARMITAJ  Check Hazmat label Msg for carton  0.4666667
7 ARMITAJ  Check Hazmat label Msg for carton 12.2333333
8 ARMITAJ  Check Hazmat label Msg for carton  4.5000000

I want to get the number of times each userid has "scanned wrong sort rule" as their worktype.

My result would look like

userid    Worktype  Count
ABENAVI   Scanned to wrong sort rule       2
Nithin    Scanned to wrong sortrule        0

I have written this code, which has been giving me an error

"Error in ifelse(x[, "rf_log2$Worktype"] == "scanned to wrong sort rule",  :    unused argument (0)"

My code is:

quality <- ddply(rf_log2, .(userid), function(x) c(
              rules <- sum(ifelse(x[ ,"Worktype"] == "scanned to wrong sort rule", x[,"Worktype"],1,0), na.rm = TRUE)))

Body:
You could create a vector checking whether df$Worktype is equal to "scanned to wrong sort rule" and then use table to get the counts per userid:

df$check <- (df$Worktype == "scanned to wrong sort rule")
table(df[, c(1,4)])[, 2]
# ABENAVI ARMITAJ
#       0       2


问:
VBA Excel Password will always accept last item in string (using Case)
This has been solved. Posted the proper code myself below. Someone shared and then removed it for an unknown reason so I duplicated it below. I am not allowed to answer my own question for 2 days however so I apologize if you came here to help. I am all set but our process is listed below.

I am currently having an issue with my code shown below. When I complete this action, it will only unlock whomever's name is listed last in the MyPassword section. For example, no matter what I type, Laura's sheet is ALWAYS executed and will make the sheet visible. I tested this by switching Chris to the third slot in just the MyPassword section and it then would make only his sheet visible even if a wrong password was entered.

Objective: They click a button and a box appears for a password. They enter their password and see only their sheet as listed in the row "Case is".

What happens: No matter what is entered, whomever's name is listed last in this section:

```<code>Dim MyPassword As String
    MyPassword = "Amanda"
    MyPassword = "Chris"
    MyPassword = "Laura"
    If InputBox("Please enter password to continue.", "Enter Password") <> MyPassword Then
</code>```

Then they will have their page show. In this case it is Laura.

I am self taught. What am I doing wrong?

```<code>Sub Pass()

Dim MyPassword As String
    MyPassword = "Amanda"
    MyPassword = "Chris"
    MyPassword = "Laura"
    If InputBox("Please enter password to continue.", "Enter Password") <> MyPassword Then

Select Case MyPassword
   Case Is = "Amanda"
      Sheets("Amanda").Visible = True
   Case Is = "Chris"
      Sheets("Chris").Visible = True
   Case Is = "Laura"
      Sheets("Laura").Visible = True
   Case ""
      MsgBox "Password can not be empty."
   Case Else
      MsgBox "Wrong password. Please contact the Compliance Department if you do not have a password."
End Select
End If
End Sub
</code>```

Note: Please stop telling me this is not the way to do this because there are back doors around this where they can still see xlVeryHidden sheets. The audience is not proficient in excel.

答:
Someone posted a corrected code and removed it for some reason. Here is the proper and working way they offered. (Please note the passwords are just placeholders. The passwords we use will not be like this.</p>

```<code>Sub Pass()

Dim MyPassword As String

MyPassword = InputBox("Please enter password to continue.", "Enter Password")

Select Case MyPassword
   Case "Amanda"
      Sheets("Amanda").Visible = True
   Case "Chris"
      Sheets("Chris").Visible = True
   Case "Laura"
      Sheets("Laura").Visible = True
   Case ""
      MsgBox "Password can not be empty."
   Case Else
      MsgBox "Wrong password. Please contact the Outcomes Department if you do not have a password."
End Select

End Sub
</code>```

Body:
This has been solved. Posted the proper code myself below. Someone shared and then removed it for an unknown reason so I duplicated it below. I am not allowed to answer my own question for 2 days however so I apologize if you came here to help. I am all set but our process is listed below.

I am currently having an issue with my code shown below. When I complete this action, it will only unlock whomever's name is listed last in the MyPassword section. For example, no matter what I type, Laura's sheet is ALWAYS executed and will make the sheet visible. I tested this by switching Chris to the third slot in just the MyPassword section and it then would make only his sheet visible even if a wrong password was entered.

Objective: They click a button and a box appears for a password. They enter their password and see only their sheet as listed in the row "Case is".

What happens: No matter what is entered, whomever's name is listed last in this section:

Dim MyPassword As String
    MyPassword = "Amanda"
    MyPassword = "Chris"
    MyPassword = "Laura"
    If InputBox("Please enter password to continue.", "Enter Password") <> MyPassword Then

Then they will have their page show. In this case it is Laura.

I am self taught. What am I doing wrong?

Sub Pass()

Dim MyPassword As String
    MyPassword = "Amanda"
    MyPassword = "Chris"
    MyPassword = "Laura"
    If InputBox("Please enter password to continue.", "Enter Password") <> MyPassword Then

Select Case MyPassword
   Case Is = "Amanda"
      Sheets("Amanda").Visible = True
   Case Is = "Chris"
      Sheets("Chris").Visible = True
   Case Is = "Laura"
      Sheets("Laura").Visible = True
   Case ""
      MsgBox "Password can not be empty."
   Case Else
      MsgBox "Wrong password. Please contact the Compliance Department if you do not have a password."
End Select
End If
End Sub

Note: Please stop telling me this is not the way to do this because there are back doors around this where they can still see xlVeryHidden sheets. The audience is not proficient in excel.

Body:
Someone posted a corrected code and removed it for some reason. Here is the proper and working way they offered. (Please note the passwords are just placeholders. The passwords we use will not be like this.

Sub Pass()

Dim MyPassword As String

MyPassword = InputBox("Please enter password to continue.", "Enter Password")

Select Case MyPassword
   Case "Amanda"
      Sheets("Amanda").Visible = True
   Case "Chris"
      Sheets("Chris").Visible = True
   Case "Laura"
      Sheets("Laura").Visible = True
   Case ""
      MsgBox "Password can not be empty."
   Case Else
      MsgBox "Wrong password. Please contact the Outcomes Department if you do not have a password."
End Select

End Sub


问:
Inserting multiple related model values in template with for loop
I am trying to post multiple values from different models in a for loop in a template. It is not doing what I am planning. I want to display a count of LeadActions that belong to Leads in a table. I did comment the part out that is not working as well. The table should display the list of Leads and the the count of how many overdue actions(LeadActions) there are for that specific lead.

My View

```<code>class LeadListView(LoginRequiredMixin, generic.ListView):
    login_url = '/scrty/login/'
    template_name = "nodiso/leadslist.html"
    model = models.Leads
    def get_context_data(self, **kwargs):
        ctx = super(LeadListView, self).get_context_data(**kwargs)
        ctx['actions']= models.LeadActions.objects.all()
        return ctx
    def get_queryset(self):
        return models.Leads.objects.filter(company=self.request.session['compid'],archive=False)
</code>```

My template

```<code><table class="table">

      <thead>
        <th>Name</th>
        <th>Overdue Tasks</th>
        <th>Total Tasks</th>
      </thead>
      {% for lead in leads_list %}
      {# {% for action in action_list %}#}

      <tr>
        <td><a href="{% url 'nodiso:leaddetail' lead.id %}">{{lead.name}}</a></td>
        <td><span class="badge">{{ actions.name|length }}</span></td>
        <td><span class="badge">42</span></td>
      </tr>

        {# {% endfor %}#}
        {% endfor %}
      </table>
</code>```

The Models

```<code>class LeadActions(models.Model):
    lead = models.ForeignKey(Leads)
    name = models.CharField(max_length=265)
    crdate = models.DateField(auto_now_add=True)
    Duedate = models.DateField()
    creator = models.CharField(max_length=265)
    overdue = models.IntegerField(null=True,blank=True)

    def __str__(self):
        return self.name
class Leads(models.Model):
    company = models.ManyToManyField(Company)
    user = models.ManyToManyField(settings.AUTH_USER_MODEL)
    name = models.CharField(max_length=265)
    email = models.EmailField(max_length=265)
    tel = models.IntegerField()
    archive = models.BooleanField(default=False)
    dateenq = models.DateField(auto_now_add=True,null=True)

    def get_absolute_url(self):
        return reverse('nodisoapp:leadlist')
    def __str__(self):
        return self.name
</code>```

答: You shouldn't be sending the list of actions from the view. Instead, in the template, you can access {{ lead.leadactions_set.count }} to give the count of LeadActions related to each Lead in the loop.

Body:
I am trying to post multiple values from different models in a for loop in a template. It is not doing what I am planning. I want to display a count of LeadActions that belong to Leads in a table. I did comment the part out that is not working as well. The table should display the list of Leads and the the count of how many overdue actions(LeadActions) there are for that specific lead.

My View

class LeadListView(LoginRequiredMixin, generic.ListView):
    login_url = '/scrty/login/'
    template_name = "nodiso/leadslist.html"
    model = models.Leads
    def get_context_data(self, **kwargs):
        ctx = super(LeadListView, self).get_context_data(**kwargs)
        ctx['actions']= models.LeadActions.objects.all()
        return ctx
    def get_queryset(self):
        return models.Leads.objects.filter(company=self.request.session['compid'],archive=False)

My template

        Name
        Overdue Tasks
        Total Tasks

      {% for lead in leads_list %}
      {# {% for action in action_list %}#}

        {{lead.name}}
        {{ actions.name|length }}
        42

        {# {% endfor %}#}
        {% endfor %}

The Models

class LeadActions(models.Model):
    lead = models.ForeignKey(Leads)
    name = models.CharField(max_length=265)
    crdate = models.DateField(auto_now_add=True)
    Duedate = models.DateField()
    creator = models.CharField(max_length=265)
    overdue = models.IntegerField(null=True,blank=True)

    def __str__(self):
        return self.name
class Leads(models.Model):
    company = models.ManyToManyField(Company)
    user = models.ManyToManyField(settings.AUTH_USER_MODEL)
    name = models.CharField(max_length=265)
    email = models.EmailField(max_length=265)
    tel = models.IntegerField()
    archive = models.BooleanField(default=False)
    dateenq = models.DateField(auto_now_add=True,null=True)

    def get_absolute_url(self):
        return reverse('nodisoapp:leadlist')
    def __str__(self):
        return self.name


问:
TSQL Datetime conversion looses a period of time
i'm playing around with a MsSQL Server for some days now and stumbled upon a strange behaviour when converting a datetime to/from a decimal.

```<code>SELECT [date] = GETDATE()

, [as decimal] = CAST(GETDATE() AS decimal)
, [from decimal] = CAST(CAST(GETDATE() AS decimal) AS datetime)

, [as float] = CAST(GETDATE() AS float)
, [from float] = CAST(CAST(GETDATE() AS float) AS datetime)

--                                  should be: 2009-08-15
, [from stored float] = CAST(CAST('40039.9583333333' AS float) AS datetime)
</code>```

When i convert a datetime without adding anything specific the decimal will be handled as i would define it decimal(18, 0). So there is a data loss in some way.

If i directly convert a float back to datetime which was converted from a datetime (as shown in line 7 of my query) everything is fine.

But when i load a value from a database table, for example 40039.9583333333 which definitely was calculated from a user input (2009-08-15) and convert it back to a datetime, it'll add one day.

I wasn't able to find anything specific for this time loss.

Is somebody able to describe the problem behind this strange behaviour?
And, if possible: add an example on how to do those conversions correctly?

Thanks.

答:
In SQL Server 40039.9583333333 is the result of SELECT CAST(CAST('2009-08-16 23:00' AS DATETIME) AS FLOAT)

You should check the inputs. Check which scale/code is being used to calculate the value that is stored on your table.

Body:
i'm playing around with a MsSQL Server for some days now and stumbled upon a strange behaviour when converting a datetime to/from a decimal.

SELECT [date] = GETDATE()

, [as decimal] = CAST(GETDATE() AS decimal)
, [from decimal] = CAST(CAST(GETDATE() AS decimal) AS datetime)

, [as float] = CAST(GETDATE() AS float)
, [from float] = CAST(CAST(GETDATE() AS float) AS datetime)

--                                  should be: 2009-08-15
, [from stored float] = CAST(CAST('40039.9583333333' AS float) AS datetime)

When i convert a datetime without adding anything specific the decimal will be handled as i would define it decimal(18, 0). So there is a data loss in some way.

If i directly convert a float back to datetime which was converted from a datetime (as shown in line 7 of my query) everything is fine.

But when i load a value from a database table, for example 40039.9583333333 which definitely was calculated from a user input (2009-08-15) and convert it back to a datetime, it'll add one day.

I wasn't able to find anything specific for this time loss.

Is somebody able to describe the problem behind this strange behaviour?
And, if possible: add an example on how to do those conversions correctly?

Thanks.


问:
How to combine data according to timestamps?
I have a series of text files containing data with two separate timestamps and would like to find out the sum of all values at a given time. The files may have different amounts of rows, but always three columns: value timestamp1 timestamp2, with entries such as

```<code>6.2 1 4
4.3 2 9
7.2 3 10
</code>```

or

```<code>1.2 2 3
0.3 3 9
0.1 5 12
</code>```

Below is an explanation of how the output is formed:

The timestamps from the two inputs are unified into a vector of unique values (so for the above example {1,2,3}∪{2,3,5} -> {1,2,3,5} or {4,9,10}∪{3,9,12} -> {3,4,9,10,12}).

For every unique timestamp a data point is selected from each of the inputs such that:

If the queried timestamp is lower than the smallest available one, the first data value is taken.

Otherwise, the data value having a lower or equal timestamp is taken.

The two values are summed and the next unique timestamp is processed (if available).

If I apply this algorithm on the example data above using timestamp1, I would get:

```<code>7.4 1  %6.2+1.2
5.5 2  %4.3+0.3
7.5 3  %7.2+0.3
7.3 5  %7.2+0.1
</code>```

and for timestamp2:

```<code>7.4 3  %6.2+1.2
7.4 4  %6.2+1.2
4.6 9  %4.3+0.3
7.5 10 %7.2+0.3
7.3 12 %7.2+0.1
</code>```

I think I need to do something with time series so for that I already have the following converter code:

```<code>logs = dir('log1/*.txt');
k=1
for log = logs'

    t{k}=timeseries(load(log.name))
    k=k+1
end
</code>```

I guess the next step would be something like sum(t) but that doesn't work. Does anybody know how to combine them like the above?

For anyone interested these are cpu and realtime timestamps (since algorithm start), for measuring the performance of an algorithm.

答:
I've been thinking about this quite some time, and finally came up with the solution below. Although it's not conceptually different from Steve's answer, at least it's vectorized :)

```<code>%% Preparations:
%{
In the same folder:

data1.txt:
6.2 1 4
4.3 2 9
7.2 3 10

data2.txt:
1.2 2 3
0.3 3 9
0.1 5 12
%}
</code>```

```<code>function out = q47303825(fname1,fname2,whichStamp)
%% Input handling:
if nargin < 3
  whichStamp = 1;
end
if nargin == 0
  fname1 = 'data1.txt';
  fname2 = 'data2.txt';
end
%% Reading the data :
d1 = dlmread(fname1,' ');
d2 = dlmread(fname2,' ');
%% Preallocation:
out = union(d1(:,whichStamp+1), d2(:,whichStamp+1)) .* [NaN,1];
%% Modifying the data slightly to allow vectorization:
d1 = [d1(1), -Inf, -Inf; d1; d1(size(d1,1)), +Inf, +Inf];
d2 = [d2(1), -Inf, -Inf; d2; d2(size(d2,1)), +Inf, +Inf];
%% Find indices:
[~,I1] = min(d1(:,whichStamp+1) <= out(:,2).',[],1);
[~,I2] = min(d2(:,whichStamp+1) <= out(:,2).',[],1);
I1 = I1-1; I2 = I2-1;
%% Generate final output:
out(:,1) = d1(I1) + d2(I2);
</code>```

Body:
I have a series of text files containing data with two separate timestamps and would like to find out the sum of all values at a given time. The files may have different amounts of rows, but always three columns: value timestamp1 timestamp2, with entries such as

6.2 1 4
4.3 2 9
7.2 3 10

or

1.2 2 3
0.3 3 9
0.1 5 12

Below is an explanation of how the output is formed:

The timestamps from the two inputs are unified into a vector of unique values (so for the above example {1,2,3}∪{2,3,5} -> {1,2,3,5} or {4,9,10}∪{3,9,12} -> {3,4,9,10,12}).

For every unique timestamp a data point is selected from each of the inputs such that:

If the queried timestamp is lower than the smallest available one, the first data value is taken.

Otherwise, the data value having a lower or equal timestamp is taken.

The two values are summed and the next unique timestamp is processed (if available).

If I apply this algorithm on the example data above using timestamp1, I would get:

7.4 1  %6.2+1.2
5.5 2  %4.3+0.3
7.5 3  %7.2+0.3
7.3 5  %7.2+0.1

and for timestamp2:

7.4 3  %6.2+1.2
7.4 4  %6.2+1.2
4.6 9  %4.3+0.3
7.5 10 %7.2+0.3
7.3 12 %7.2+0.1

I think I need to do something with time series so for that I already have the following converter code:

logs = dir('log1/*.txt');
k=1
for log = logs'

    t{k}=timeseries(load(log.name))
    k=k+1
end

I guess the next step would be something like sum(t) but that doesn't work. Does anybody know how to combine them like the above?

For anyone interested these are cpu and realtime timestamps (since algorithm start), for measuring the performance of an algorithm.

Body:
I've been thinking about this quite some time, and finally came up with the solution below. Although it's not conceptually different from Steve's answer, at least it's vectorized :)

%% Preparations:
%{
In the same folder:

data1.txt:
6.2 1 4
4.3 2 9
7.2 3 10

data2.txt:
1.2 2 3
0.3 3 9
0.1 5 12
%}

function out = q47303825(fname1,fname2,whichStamp)
%% Input handling:
if nargin < 3
  whichStamp = 1;
end
if nargin == 0
  fname1 = 'data1.txt';
  fname2 = 'data2.txt';
end
%% Reading the data :
d1 = dlmread(fname1,' ');
d2 = dlmread(fname2,' ');
%% Preallocation:
out = union(d1(:,whichStamp+1), d2(:,whichStamp+1)) .* [NaN,1];
%% Modifying the data slightly to allow vectorization:
d1 = [d1(1), -Inf, -Inf; d1; d1(size(d1,1)), +Inf, +Inf];
d2 = [d2(1), -Inf, -Inf; d2; d2(size(d2,1)), +Inf, +Inf];
%% Find indices:
[~,I1] = min(d1(:,whichStamp+1) <= out(:,2).',[],1);
[~,I2] = min(d2(:,whichStamp+1) <= out(:,2).',[],1);
I1 = I1-1; I2 = I2-1;
%% Generate final output:
out(:,1) = d1(I1) + d2(I2);


问:
scipy.pdist() returns NaN values
I'm trying to cluster time series. The intra-cluster elements have same shapes but different scales. Therefore, I would like to use a correlation measure as metric for clustering. I'm trying correlation or pearson coefficient distance (any suggestion or alternative is welcome).
However, the following code returns error when I run Z = linkage(dist) because there are some NaN values in dist. There are not NaN values in time_series, this is confirmed by

```<code>np.any(isnan(time_series))
</code>```

which returns False

```<code>from scipy.spatial.distance import pdist
from scipy.cluster.hierarchy import dendrogram, linkage

dist = pdist(time_series, metric='correlation')
Z = linkage(dist)
fig = plt.figure()
dn = dendrogram(Z)
plt.show()
</code>```

As alternative, I will use pearson distance

```<code>from scipy.stats import pearsonr

def pearson_distance(a,b):
    return 1 - pearsonr(a,b)[0]

dist = pdist(time_series, pearson_distance)`
</code>```

but this generates some runtime warnings and takes a lot of time.

答:
```<code>scipy.pdist(time_series, metric='correlation')
</code>```

If you take a look at the manual, the correlation options divides by the difference. So it could be that you have two timestamps that are the same, and dividing zero by zero gives us NaN.

Title: scipy.pdist() returns NaN values

Body:
I'm trying to cluster time series. The intra-cluster elements have same shapes but different scales. Therefore, I would like to use a correlation measure as metric for clustering. I'm trying correlation or pearson coefficient distance (any suggestion or alternative is welcome).
However, the following code returns error when I run Z = linkage(dist) because there are some NaN values in dist. There are not NaN values in time_series, this is confirmed by

np.any(isnan(time_series))

which returns False

from scipy.spatial.distance import pdist
from scipy.cluster.hierarchy import dendrogram, linkage

dist = pdist(time_series, metric='correlation')
Z = linkage(dist)
fig = plt.figure()
dn = dendrogram(Z)
plt.show()

As alternative, I will use pearson distance

from scipy.stats import pearsonr

def pearson_distance(a,b):
    return 1 - pearsonr(a,b)[0]

dist = pdist(time_series, pearson_distance)`

but this generates some runtime warnings and takes a lot of time.

Body:
scipy.pdist(time_series, metric='correlation')

If you take a look at the manual, the correlation options divides by the difference. So it could be that you have two timestamps that are the same, and dividing zero by zero gives us NaN.


问:
How to efficiently convert baudrate from int to speed_t?
The functions cfsetospeed and cfsetispeed take baud rate as type speed_t:

```<code>int cfsetispeed(struct termios *termios_p, speed_t speed);
int cfsetospeed(struct termios *termios_p, speed_t speed);
</code>```

The type speed_t is basically an integer, but casting is not a solution, as can be seen from the baudrate definitions in termios.h:

```<code>#define B0  0x00000000
#define B50 0x00000001
#define B75 0x00000002
// ...
#define B9600   0x0000000d
#define B19200  0x0000000e
#define B38400  0x0000000f
</code>```

When I process user input (e.g. from file), I convert a string such as "9600" to integer 9600, and then to B9600. I'm basically looking for a generic way to convert the following:

```<code>// 0 -> B0
// 50 -> B50
// 75 -> B75
// ...
// 9600 -> B9600
// 19200 -> B19200
// 38400 -> B38400
</code>```

One way to convert from int (such as 9600) to speed_t (such as B9600) is a switch-case structure. Is there a better way to achieve this?

答:
You need a lookup table, but not a naive one:

```<code>#include <stdio.h>
#include <termios.h>

struct
{
  int rawrate;
  int termiosrate;
} conversiontable[] =
{
  {0, B0},
  {50, B50},
  {75, B75},
  // you need to complete the table with B110 to B38400
};

int convertbaudrate(int rawrate)
{
  for (int i = 0; i < sizeof(conversiontable) / sizeof(conversiontable[0]); i++)
  {
    if (conversiontable[i].rawrate == rawrate)
    {
      return conversiontable[i].termiosrate;
    }
  }

  return -1;    // invalid baud rate
}

int main()
{
  printf("%d -> %d\n", 50, convertbaudrate(50));
  printf("%d -> %d\n", 75, convertbaudrate(75));
}
</code>```

That should autoexplain. If not, please comment.

Body:
The functions cfsetospeed and cfsetispeed take baud rate as type speed_t:

int cfsetispeed(struct termios *termios_p, speed_t speed);
int cfsetospeed(struct termios *termios_p, speed_t speed);

The type speed_t is basically an integer, but casting is not a solution, as can be seen from the baudrate definitions in termios.h:

#define B0  0x00000000
#define B50 0x00000001
#define B75 0x00000002
// ...
#define B9600   0x0000000d
#define B19200  0x0000000e
#define B38400  0x0000000f

When I process user input (e.g. from file), I convert a string such as "9600" to integer 9600, and then to B9600. I'm basically looking for a generic way to convert the following:

// 0 -> B0
// 50 -> B50
// 75 -> B75
// ...
// 9600 -> B9600
// 19200 -> B19200
// 38400 -> B38400

One way to convert from int (such as 9600) to speed_t (such as B9600) is a switch-case structure. Is there a better way to achieve this?

Body:
You need a lookup table, but not a naive one:

#include <stdio.h>
#include <termios.h>

struct
{
  int rawrate;
  int termiosrate;
} conversiontable[] =
{
  {0, B0},
  {50, B50},
  {75, B75},
  // you need to complete the table with B110 to B38400
};

int convertbaudrate(int rawrate)
{
  for (int i = 0; i < sizeof(conversiontable) / sizeof(conversiontable[0]); i++)
  {
    if (conversiontable[i].rawrate == rawrate)
    {
      return conversiontable[i].termiosrate;
    }
  }

  return -1;    // invalid baud rate
}

int main()
{
  printf("%d -> %d\n", 50, convertbaudrate(50));
  printf("%d -> %d\n", 75, convertbaudrate(75));
}

That should autoexplain. If not, please comment.


问:
Twig error when try to format {$
Try to format that code in twig format:

```<code><textarea class="form-control" name="email_review_subject_<?php echo $language['language_id']; ?>" ><?php echo isset(${'email_review_subject_' . $language['language_id']}) ? ${'email_review_subject_' . $language['language_id']} : ''; ?></textarea>
</code>```

So i tried with that format:

```<code><textarea class="form-control" name="email_review_subject_{{ language['language_id'] }}" >{{ isset({'email_review_subject_' . language.language_id}) ? {'email_review_subject_' . language.language_id} : '' }}</textarea>
</code>```

Error:

Uncaught exception 'Twig_Error_Syntax' with message 'A hash key must
  be followed by a colon (:). Unexpected token "punctuation" of value
  "." ("punctuation" expected with value ":")

答:
There is no such thing as isset in twig. You also need to access the special variable _context if you want use dynamic variables in twig

Some possible solutions,

```<code><textarea class="form-control" name="email_review_subject_{{ language['language_id'] }}" >{{ attribute(_context, 'email_review_subject_'~language.language_id)|default('') }}</textarea>

<textarea class="form-control" name="email_review_subject_{{ language['language_id'] }}" >{{ attribute(_context, 'email_review_subject_'~language.language_id) is defined ? attribute(_context, 'email_review_subject_'~language.language_id) : '' }}</textarea>
</code>```

fiddle

Title: Twig error when try to format {$

Body:
Try to format that code in twig format:

<textarea class="form-control" name="email_review_subject_<?php echo $language['language_id']; ?>" ><?php echo isset(${'email_review_subject_' . $language['language_id']}) ? ${'email_review_subject_' . $language['language_id']} : ''; ?></textarea>

So i tried with that format:

<textarea class="form-control" name="email_review_subject_{{ language['language_id'] }}" >{{ isset({'email_review_subject_' . language.language_id}) ? {'email_review_subject_' . language.language_id} : '' }}</textarea>

Error:

Uncaught exception 'Twig_Error_Syntax' with message 'A hash key must
  be followed by a colon (:). Unexpected token "punctuation" of value
  "." ("punctuation" expected with value ":")

Body:
There is no such thing as isset in twig. You also need to access the special variable _context if you want use dynamic variables in twig

Some possible solutions,

<textarea class="form-control" name="email_review_subject_{{ language['language_id'] }}" >{{ attribute(_context, 'email_review_subject_'~language.language_id)|default('') }}</textarea>

<textarea class="form-control" name="email_review_subject_{{ language['language_id'] }}" >{{ attribute(_context, 'email_review_subject_'~language.language_id) is defined ? attribute(_context, 'email_review_subject_'~language.language_id) : '' }}</textarea>

fiddle


问:
How to reference variable names in a for loop in R?
I'm trying to reference variable names in for loop in R. For example, if I want to change each of the following variables to from numeric to a string

```<code>xtable<- tbl_df(cbind(x1=c(1,2,3), x2=c(3,4,5)))

for (varname in names(xtable)) {
 xtable$varname<- as.character(xtable$varname)
}
</code>```

or rename each variable by adding an 'a' after each variable name

```<code>for (varname in names(xtable)) {
 dplyr::rename(xtable, varname = paste0(varname,'a', sep='') )
}
</code>```

In general, I'm having trouble referencing the indexing variable "varname" within the for loop as the variable name it represents rather than as the word "varname".

答:
As others have mentioned, there is no need to use a for loop in both of your cases. There are two convenience functions in dplyr called mutate_all and mutate_if that will let you do the first case very easily:

```<code>library(dplyr)

# Convert all columns to character
xtable %>%
  mutate_all(as.character)

# Convert all numeric columns to character
xtable %>%
  mutate_if(is.numeric, as.character)
</code>```

Result:

```<code># A tibble: 3 x 2
     x1    x2
  <chr> <chr>
1     1     3
2     2     4
3     3     5
</code>```

For second case, you can also use setNames and chain it with the first case:

```<code>xtable %>%
  mutate_all(as.character) %>%
  setNames(paste0(names(xtable), "a"))
</code>```

Result:

```<code># A tibble: 3 x 2
    x1a   x2a
  <chr> <chr>
1     1     3
2     2     4
3     3     5
</code>```

Body:
I'm trying to reference variable names in for loop in R. For example, if I want to change each of the following variables to from numeric to a string

xtable<- tbl_df(cbind(x1=c(1,2,3), x2=c(3,4,5)))

for (varname in names(xtable)) {
 xtable$varname<- as.character(xtable$varname)
}

or rename each variable by adding an 'a' after each variable name

for (varname in names(xtable)) {
 dplyr::rename(xtable, varname = paste0(varname,'a', sep='') )
}

In general, I'm having trouble referencing the indexing variable "varname" within the for loop as the variable name it represents rather than as the word "varname".

Body:
As others have mentioned, there is no need to use a for loop in both of your cases. There are two convenience functions in dplyr called mutate_all and mutate_if that will let you do the first case very easily:

library(dplyr)

# Convert all columns to character
xtable %>%
  mutate_all(as.character)

# Convert all numeric columns to character
xtable %>%
  mutate_if(is.numeric, as.character)

Result:

# A tibble: 3 x 2
     x1    x2
  <chr> <chr>
1     1     3
2     2     4
3     3     5

For second case, you can also use setNames and chain it with the first case:

xtable %>%
  mutate_all(as.character) %>%
  setNames(paste0(names(xtable), "a"))

Result:

# A tibble: 3 x 2
    x1a   x2a
  <chr> <chr>
1     1     3
2     2     4
3     3     5


问:
Execute a callback method from a BroadcastReceiver
I've created a view that installs an alarm via AlarmManager, which will in turn execute a BroadcastReceiver subtype specified by me.

In this BroadcastReceiver, I would like to call a method of my view: I need to clean up after the alarm happened. Can I somehow call my view from the BroadcastReceiver?

I've tried to solve the issue by turning my BroadcastReceiver into an inner class, but I couldn't make it work with Context.registerReceiver(), plus I'd rather have it as a top level type for clarity.

答:
Can I somehow call my view from the BroadcastReceiver?

Probably not. Usually AlarmManager alarms invoke receivers registered in the manifest. Those receivers exist on their own, independent from any other Android components.

You can register a receiver via registerReceiver() from your activity, and that receiver could access a View in the activity, and you could possibly target that receiver with AlarmManager, but that will only work while the activity is in the foreground.

ContentLicense: CC BY-SA 2.5


问:
Unlock Aspect Ratio from Prompted Input
I'm getting a compile error on img.LockAspectRatio = msoFalse. All I'm trying to do is unlock the aspect ratio of the image that is being imported from the user. I would assume I'm not using the proper syntax, any help would be great

```<code>Sub ChangeImage()
    With Application.FileDialog(msoFileDialogFilePicker)
        .AllowMultiSelect = False
        .ButtonName = "Submit"
        .Title = "Select an image file"
        .Filters.Clear
        .Filters.Add "All Pictures", "*.*"

        If .Show = -1 Then
            Dim img As Object
            Set img = ActiveSheet.Pictures.Insert(.SelectedItems(1))

            img.LockAspectRatio = msoFalse

            img.Left = 141
            img.Top = 925

            img.Width = 600
            img.Height = 251
        Else
            Debug.Print "Prompt closed"
        End If
    End With
End Sub
</code>```

答:
As you are trying to insert picture, declare the type as Picture and not as Object. Use LockAspectRatio is available under the ShapeRange property.

```<code>Sub ChangeImage()
        With Application.FileDialog(msoFileDialogFilePicker)
            .AllowMultiSelect = False
            .ButtonName = "Submit"
            .Title = "Select an image file"
            .Filters.Clear
            .Filters.Add "All Pictures", "*.*"

            If .Show = -1 Then
                Dim img As Picture '/ Declare as Picture
                Set img = ActiveSheet.Pictures.Insert(.SelectedItems(1))

               '/ Use ShapeRange to toogle aspect ratio
               img.ShapeRange.LockAspectRatio = msoFalse

                img.Left = 141
                img.Top = 925

                img.Width = 600
                img.Height = 251
            Else
                Debug.Print "Prompt closed"
            End If
        End With
    End Sub
</code>```

Title: Unlock Aspect Ratio from Prompted Input

Body:
I'm getting a compile error on img.LockAspectRatio = msoFalse. All I'm trying to do is unlock the aspect ratio of the image that is being imported from the user. I would assume I'm not using the proper syntax, any help would be great

Sub ChangeImage()
    With Application.FileDialog(msoFileDialogFilePicker)
        .AllowMultiSelect = False
        .ButtonName = "Submit"
        .Title = "Select an image file"
        .Filters.Clear
        .Filters.Add "All Pictures", "*.*"

        If .Show = -1 Then
            Dim img As Object
            Set img = ActiveSheet.Pictures.Insert(.SelectedItems(1))

            img.LockAspectRatio = msoFalse

            img.Left = 141
            img.Top = 925

            img.Width = 600
            img.Height = 251
        Else
            Debug.Print "Prompt closed"
        End If
    End With
End Sub

Body:
As you are trying to insert picture, declare the type as Picture and not as Object. Use LockAspectRatio is available under the ShapeRange property.

Sub ChangeImage()
        With Application.FileDialog(msoFileDialogFilePicker)
            .AllowMultiSelect = False
            .ButtonName = "Submit"
            .Title = "Select an image file"
            .Filters.Clear
            .Filters.Add "All Pictures", "*.*"

            If .Show = -1 Then
                Dim img As Picture '/ Declare as Picture
                Set img = ActiveSheet.Pictures.Insert(.SelectedItems(1))

               '/ Use ShapeRange to toogle aspect ratio
               img.ShapeRange.LockAspectRatio = msoFalse

                img.Left = 141
                img.Top = 925

                img.Width = 600
                img.Height = 251
            Else
                Debug.Print "Prompt closed"
            End If
        End With
    End Sub


问:
Apache Ignite .NET Serializing delegates is not supported on this platform
Asked question about Sheduling jobs in ignite here.

Tested it with simple text output to console and with simple async web requests via HttpClient. Works fine.

Implemented real busines logic with lots of long running tasks and parallel computations.

Ignite .NET version: 2.3.0

App platform: dotnet core 2.0

But recieve exception on service registration with DeployClusterSingleton.

System.Runtime.Serialization.SerializationException: 'Serializing
  delegates is not supported on this platform.'

Source: System.Private.CoreLib

```<code>   at System.MulticastDelegate.GetObjectData(SerializationInfo info, StreamingContext context)
   at Apache.Ignite.Core.Impl.Binary.SerializableSerializer.WriteBinary[T](T obj, BinaryWriter writer)
   at Apache.Ignite.Core.Impl.Binary.BinaryWriter.Write[T](T obj)
   at Apache.Ignite.Core.Impl.Binary.BinaryReflectiveSerializerInternal.Apache.Ignite.Core.Impl.Binary.IBinarySerializerInternal.WriteBinary[T](T obj, BinaryWriter writer)
   at Apache.Ignite.Core.Impl.Binary.BinaryWriter.Write[T](T obj)
   at Apache.Ignite.Core.Impl.Binary.BinaryUtils.WriteArray(Array val, BinaryWriter ctx, Nullable`1 elemTypeId)
   at Apache.Ignite.Core.Impl.Binary.BinarySystemHandlers.WriteArray(BinaryWriter ctx, Object obj)
   at Apache.Ignite.Core.Impl.Binary.BinaryWriter.Write[T](T obj)
   at Apache.Ignite.Core.Impl.Binary.BinaryReflectiveSerializerInternal.Apache.Ignite.Core.Impl.Binary.IBinarySerializerInternal.WriteBinary[T](T obj, BinaryWriter writer)
   at Apache.Ignite.Core.Impl.Binary.BinaryWriter.Write[T](T obj)
   at Apache.Ignite.Core.Impl.Binary.BinaryReflectiveSerializerInternal.Apache.Ignite.Core.Impl.Binary.IBinarySerializerInternal.WriteBinary[T](T obj, BinaryWriter writer)
   at Apache.Ignite.Core.Impl.Binary.BinaryWriter.Write[T](T obj)
   at Apache.Ignite.Core.Impl.Binary.BinaryReflectiveSerializerInternal.Apache.Ignite.Core.Impl.Binary.IBinarySerializerInternal.WriteBinary[T](T obj, BinaryWriter writer)
   at Apache.Ignite.Core.Impl.Binary.BinaryWriter.Write[T](T obj)
   at Apache.Ignite.Core.Impl.Binary.BinaryReflectiveSerializerInternal.Apache.Ignite.Core.Impl.Binary.IBinarySerializerInternal.WriteBinary[T](T obj, BinaryWriter writer)
   at Apache.Ignite.Core.Impl.Binary.BinaryWriter.Write[T](T obj)
   at Apache.Ignite.Core.Impl.Services.Services.<>c__DisplayClass3.<DeployMultiple>b__2(BinaryWriter w)
   at Apache.Ignite.Core.Impl.PlatformTargetAdapter.WriteToStream(Action`1 action, IBinaryStream stream, Marshaller marsh)
   at Apache.Ignite.Core.Impl.PlatformJniTarget.InStreamOutStream[TR](Int32 type, Action`1 writeAction, Func`2 readAction)
   at Apache.Ignite.Core.Impl.Services.Services.DeployMultiple(String name, IService service, Int32 totalCount, Int32 maxPerNodeCount)
   at Apache.Ignite.Core.Impl.Services.Services.DeployClusterSingleton(String name, IService service)
</code>```

It is hard to guess, which part of code causing this. All i have to do is to replace code with stub part by part.

If more details is needed i can provide additional information.

After investigation:

It was IOptions<>, ILogger<>

Next one was: System.PlatformNotSupportedException: 'Operation is not supported on this platform.' from System.Reflection.RuntimePropertyInfo.GetObjectData(SerializationInfo info, StreamingContext context)

And another one was: Apache.Ignite.Core.Binary.BinaryObjectException: 'Conflicting field IDs [type=HttpClient, field1=_disposed, field2=_disposed, fieldId=375705476]'

sadly, I had to change the architecture because of this a lot;

答:
This exception is caused by .NET Core, which does not support delegate serialization. Ignite just calls standard GetObjectData method.

This would work under normal .NET 4+.

Does your service class contain any delegates?

Body:
Asked question about Sheduling jobs in ignite here.

Tested it with simple text output to console and with simple async web requests via HttpClient. Works fine.

Implemented real busines logic with lots of long running tasks and parallel computations.

Ignite .NET version: 2.3.0

App platform: dotnet core 2.0

But recieve exception on service registration with DeployClusterSingleton.

System.Runtime.Serialization.SerializationException: 'Serializing
  delegates is not supported on this platform.'

Source: System.Private.CoreLib

   at System.MulticastDelegate.GetObjectData(SerializationInfo info, StreamingContext context)
   at Apache.Ignite.Core.Impl.Binary.SerializableSerializer.WriteBinary[T](T obj, BinaryWriter writer)
   at Apache.Ignite.Core.Impl.Binary.BinaryWriter.Write[T](T obj)
   at Apache.Ignite.Core.Impl.Binary.BinaryReflectiveSerializerInternal.Apache.Ignite.Core.Impl.Binary.IBinarySerializerInternal.WriteBinary[T](T obj, BinaryWriter writer)
   at Apache.Ignite.Core.Impl.Binary.BinaryWriter.Write[T](T obj)
   at Apache.Ignite.Core.Impl.Binary.BinaryUtils.WriteArray(Array val, BinaryWriter ctx, Nullable`1 elemTypeId)
   at Apache.Ignite.Core.Impl.Binary.BinarySystemHandlers.WriteArray(BinaryWriter ctx, Object obj)
   at Apache.Ignite.Core.Impl.Binary.BinaryWriter.Write[T](T obj)
   at Apache.Ignite.Core.Impl.Binary.BinaryReflectiveSerializerInternal.Apache.Ignite.Core.Impl.Binary.IBinarySerializerInternal.WriteBinary[T](T obj, BinaryWriter writer)
   at Apache.Ignite.Core.Impl.Binary.BinaryWriter.Write[T](T obj)
   at Apache.Ignite.Core.Impl.Binary.BinaryReflectiveSerializerInternal.Apache.Ignite.Core.Impl.Binary.IBinarySerializerInternal.WriteBinary[T](T obj, BinaryWriter writer)
   at Apache.Ignite.Core.Impl.Binary.BinaryWriter.Write[T](T obj)
   at Apache.Ignite.Core.Impl.Binary.BinaryReflectiveSerializerInternal.Apache.Ignite.Core.Impl.Binary.IBinarySerializerInternal.WriteBinary[T](T obj, BinaryWriter writer)
   at Apache.Ignite.Core.Impl.Binary.BinaryWriter.Write[T](T obj)
   at Apache.Ignite.Core.Impl.Binary.BinaryReflectiveSerializerInternal.Apache.Ignite.Core.Impl.Binary.IBinarySerializerInternal.WriteBinary[T](T obj, BinaryWriter writer)
   at Apache.Ignite.Core.Impl.Binary.BinaryWriter.Write[T](T obj)
   at Apache.Ignite.Core.Impl.Services.Services.<>c__DisplayClass3.<DeployMultiple>b__2(BinaryWriter w)
   at Apache.Ignite.Core.Impl.PlatformTargetAdapter.WriteToStream(Action`1 action, IBinaryStream stream, Marshaller marsh)
   at Apache.Ignite.Core.Impl.PlatformJniTarget.InStreamOutStream[TR](Int32 type, Action`1 writeAction, Func`2 readAction)
   at Apache.Ignite.Core.Impl.Services.Services.DeployMultiple(String name, IService service, Int32 totalCount, Int32 maxPerNodeCount)
   at Apache.Ignite.Core.Impl.Services.Services.DeployClusterSingleton(String name, IService service)

It is hard to guess, which part of code causing this. All i have to do is to replace code with stub part by part.

If more details is needed i can provide additional information.

After investigation:

It was IOptions<>, ILogger<>

Next one was: System.PlatformNotSupportedException: 'Operation is not supported on this platform.' from System.Reflection.RuntimePropertyInfo.GetObjectData(SerializationInfo info, StreamingContext context)

And another one was: Apache.Ignite.Core.Binary.BinaryObjectException: 'Conflicting field IDs [type=HttpClient, field1=_disposed, field2=_disposed, fieldId=375705476]'

sadly, I had to change the architecture because of this a lot;


问:
Mixed precision not enabled with TF1.4 on Tesla V100
I was interested in testing my neural net (an Autoencoder that serves as a generator + a CNN as a discriminator) that uses 3dconv/deconv layers with the new Volta architecture and benefit from the Mixed-Precision training. I compiled the most recent source code of Tensorflow 1.4 with CUDA 9 and CudNN 7.0 and cast all the trainable variables used by my conv/deconv layers to tf.float16. Also, all my input and output tensors have sizes that are multiple of 8.

Unfortunately, I do not see any substantial speed improvement with this configuration, the training time is roughly similar to when using tf.float32. My understanding is that with the Volta architecture and cuDNN 7.0, Mixed Precision should be automatically detected by TF and hence enable the use of Tensor Core math. Am I wrong, or is there anything I should do to enable it?
I also tried the TF1.5 nighlty build, and it seems that it is even slower than my custom 1.4.

I would appreciate if any dev involved in Tensorflow could answer this.

EDIT: After talking with NVIDIA tech support, it seems that, while supporting float16,TF integrates mixed-precision acceleration for simple 2D conv Ops, but not for 3D conv Ops as of now.

答:
Based on NVIDIA documentation I run benchmark with FP16 (TensorCore). For that I modyfied alexnet_benchmark delivered by tensorflow:
https://gist.github.com/melgor/946b9643aa25dd3839a86804fc580741

Overall, AlexNet is only 35% faster, not so much. I was hoping to get ~2x faster. Also, maybe Resnet would make bigger differnce. The nice thing is that I can fit model with batch_size = 5120 (fp32 cannot), one FB pass take 0.653, so training ImageNet by 90 epochs take ~4h.

batch_size=512
alexnet_fp32: Forward-backward across 100 steps, 0.099 +/- 0.000 sec / batch
alexnet_fp16: Forward-backward across 100 steps, 0.064 +/- 0.000 sec / batch

Edit:

I manage to run ResNet models on FP16 (but without BatchNorm, for some reason BN does not work with fp16):

batch_size=256
resnet50_fp32: Forward-backward across 100 steps, 0.575 +/- 0.001 sec / batch
resnet50_fp16: Forward-backward across 100 steps, 0.504 +/- 0.001 sec / batch

batch_size=128
resnet152_fp32: Forward-backward across 100 steps, 0.757 +/- 0.001 sec / batch
resnet152_fp16: Forward-backward across 100 steps, 0.581 +/- 0.010 sec / batch

The gain at ResNet is even smaller. Look like FP16 does not have a lot of gain at V100, not sure why. Maybe the suppor of TensorCore is not fully intergrated currently.


问:
Read *.XLSX file from HDFS in PySpark
How is it possible to read xlsx files from HDFS in PySpark? One way is to convert it to csv file, but I have a lot of files and I am looking for other methods.</p>

答: I don't think you can do that using standard spark libraries. You might want to look into this as an alternative - https://github.com/crealytics/spark-excel</p>

Title: Read *.XLSX file from HDFS in PySpark


问:
Finding property value by string getting
Hey I am having an issue looking up strings in a class based on class properties in typescript.

```<code>export class EventName {
   public static LOGIN = "LOGIN";
   public static LOGOUT = "LOGOUT";
}
</code>```

I looked online and it says to just use something like eventName['LOGIN'];

However this returns the following error

Element implicitly has an 'any' type because type 'typeof EventName' has no index signature.

I then tried adding in
    [key: string]: any;
But this still gives me the same error. I was wondering could someone please point me to the issue here thanks?

答:
If you attempt your example eventName['LOGIN']; using an instance of the EventName class, you'll get that error (if you are using --noImplicitAny):

```<code>class EventName {
   public static LOGIN = "LOGIN";
   public static LOGOUT = "LOGOUT";
}

const eventName = new EventName();

// Element implicitly has an 'any' type because type 'EventName' has no index signature.
const logout = eventName['LOGOUT'];
</code>```

This is because the properties are static and don't belong to an instance - so you can use:

```<code>class EventName {
   public static LOGIN = "LOGIN";
   public static LOGOUT = "LOGOUT";
}

// login: string;
const login = EventName['LOGIN'];
</code>```

This might be a good example of why the --noImplicitAny flag is terribly useful.

Body:
Hey I am having an issue looking up strings in a class based on class properties in typescript.

export class EventName {
   public static LOGIN = "LOGIN";
   public static LOGOUT = "LOGOUT";
}

I looked online and it says to just use something like eventName['LOGIN'];

However this returns the following error

Element implicitly has an 'any' type because type 'typeof EventName' has no index signature.

I then tried adding in
    [key: string]: any;
But this still gives me the same error. I was wondering could someone please point me to the issue here thanks?

Body:
If you attempt your example eventName['LOGIN']; using an instance of the EventName class, you'll get that error (if you are using --noImplicitAny):

class EventName {
   public static LOGIN = "LOGIN";
   public static LOGOUT = "LOGOUT";
}

const eventName = new EventName();

// Element implicitly has an 'any' type because type 'EventName' has no index signature.
const logout = eventName['LOGOUT'];

This is because the properties are static and don't belong to an instance - so you can use:

class EventName {
   public static LOGIN = "LOGIN";
   public static LOGOUT = "LOGOUT";
}

// login: string;
const login = EventName['LOGIN'];

This might be a good example of why the --noImplicitAny flag is terribly useful.


问:
question about jredis performance
I want to use Redis RPUSH and LPOP as message queue in my project, and now I encountered a performance problem:

When I simply rpush a random Double nubmer using Jredis with a single thread from my java client, I notice that the throughout is just 4000 request/secs, which is much lower than what I expected.

Here is my redis Configuration:

timeout 300
save 900 1
save 300 10
save 60 10000

no memory limit with 4G memory.

and Java snippet:

```<code>    jredis = new JRedisClient(ip,6379);
    long bytesTransfered = 0;
    Date start = new Date();
    for(int i = 0; i < 100000 ; i ++){
        String s = Math.random()+"";
        jredis.lpush("testqueue", s);
        bytesTransfered += s.length();
    }
    Date end = new Date();
    double seconds = (end.getTime() - start.getTime())/1000f;
    System.out.println("REDIS:\t"+  (bytesTransfered/seconds)+"bytes/second,\t"+100000/seconds+"request/second");
</code>```

Is there any other java client better than jredis?  Thanks for your help!.

答:
A full list of Redis clients can be found at http://redis.io/clients

For your answer, there are two different clients (out of 3 total):

JDBC-Redis (http://code.google.com/p/jdbc-redis)

Jedis (http://github.com/xetorthio/jedis)

Title: question about jredis performance

Body:
I want to use Redis RPUSH and LPOP as message queue in my project, and now I encountered a performance problem:

When I simply rpush a random Double nubmer using Jredis with a single thread from my java client, I notice that the throughout is just 4000 request/secs, which is much lower than what I expected.

Here is my redis Configuration:

timeout 300
save 900 1
save 300 10
save 60 10000

no memory limit with 4G memory.

and Java snippet:

    jredis = new JRedisClient(ip,6379);
    long bytesTransfered = 0;
    Date start = new Date();
    for(int i = 0; i < 100000 ; i ++){
        String s = Math.random()+"";
        jredis.lpush("testqueue", s);
        bytesTransfered += s.length();
    }
    Date end = new Date();
    double seconds = (end.getTime() - start.getTime())/1000f;
    System.out.println("REDIS:\t"+  (bytesTransfered/seconds)+"bytes/second,\t"+100000/seconds+"request/second");

Is there any other java client better than jredis?  Thanks for your help!.


问:
jQuery toggle text and image not working
I am creating a dropdown accordion menu with jQuery.
I have worked on a few versions before and my script can work well before I add the image toggle.

But after I have added the image toggle script, the whole toggle is not functioning well.

$(function() {
  $('.showmore').click(
    function() {
      $(this).closest("div").next(".dropdown").toggle();
      $(this).find('i').toggleClass('arrow-down arrow-up');
      if ($(this).text() == "Show") {
        $(this).text("Hide");
      } else {
        $(this).text("Show");
      }
      $(this).closest("div").next(".dropdown").toggleClass('selected');
    }
  )
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.title {
  background-color: #CCCCCC;
}

.sprite {
  background-image: url(https://image.ibb.co/bHTF8R/pinkarrow.png);
  background-repeat: no-repeat;
  display: block;
}

.arrow-down {
  width: 9px;
  height: 6px;
  background-position: -9px 0;
}

.arrow-up {
  width: 9px;
  height: 6px;
  background-position: 0 0;
}

.arrow-down,
.arrow-up {
  display: inline-block;
  padding-left: 5px;
}

.dropdown {
  display: none;
}

.selected {
  border: 4px solid #CCCCCC;
}</code>```

    Show

    XXXXXXXXXX Content XXXXXXXXXX

```
</div>
</div>
</p>

<p>So what I want to do is that: Originally the content will be hidden, with a title "Show" with arrow down icon is shown. If I click on the title, the hidden content will be shown and the title will change to "Hide" and with arrow up icon. </p>

<p>Originally I can achieve the toggle with those text, however, after I have tried to add the image toggle script, it is not working.</p>

```$(this).find('i').toggleClass('arrow-down arrow-up');
```

Anyone can share with me your solution/opinion here? Thank you so much for your time of reading my question!

答:
When you do this:

```<code>$(this).text("any text");
</code>```

You remove the  element that you're using as an arrow.  The resulting markup becomes:

```<code><span class="showmore">any text</span>
</code>```

Since the  is now gone, there's nothing to toggle.  Instead of setting the text in the entire element, create a child element to hold the text:

```<code><span class="showmore">
    <span>Show</span>
    <i class="sprite arrow-down"></i>
</span>
</code>```

Then you can target that specific element to set the text:

```<code>$(this).find("span").text("any text");
</code>```

Demo:

$(function() {
  $('.showmore').click(
    function() {
      $(this).closest("div").next(".dropdown").toggle();
      $(this).find('i').toggleClass('arrow-down arrow-up');
      if ($(this).find("span").text() == "Show") {
        $(this).find("span").text("Hide");
      } else {
        $(this).find("span").text("Show");
      }
      $(this).closest("div").next(".dropdown").toggleClass('selected');
    }
  )
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.title {
  background-color: #CCCCCC;
}

.sprite {
  background-image: url(https://image.ibb.co/bHTF8R/pinkarrow.png);
  background-repeat: no-repeat;
  display: block;
}

.arrow-down {
  width: 9px;
  height: 6px;
  background-position: -9px 0;
}

.arrow-up {
  width: 9px;
  height: 6px;
  background-position: 0 0;
}

.arrow-down,
.arrow-up {
  display: inline-block;
  padding-left: 5px;
}

.dropdown {
  display: none;
}

.selected {
  border: 4px solid #CCCCCC;
}</code>```

      Show

    XXXXXXXXXX Content XXXXXXXXXX

```

(Note: In my browser the styling on the "up arrow" doesn't look quite right.  Probably needs some tweaking.)

Body:
I am creating a dropdown accordion menu with jQuery.
I have worked on a few versions before and my script can work well before I add the image toggle.

But after I have added the image toggle script, the whole toggle is not functioning well.

$(function() {
  $('.showmore').click(
    function() {
      $(this).closest("div").next(".dropdown").toggle();
      $(this).find('i').toggleClass('arrow-down arrow-up');
      if ($(this).text() == "Show") {
        $(this).text("Hide");
      } else {
        $(this).text("Show");
      }
      $(this).closest("div").next(".dropdown").toggleClass('selected');
    }
  )
})

.title {
  background-color: #CCCCCC;
}

.sprite {
  background-image: url(https://image.ibb.co/bHTF8R/pinkarrow.png);
  background-repeat: no-repeat;
  display: block;
}

.arrow-down {
  width: 9px;
  height: 6px;
  background-position: -9px 0;
}

.arrow-up {
  width: 9px;
  height: 6px;
  background-position: 0 0;
}

.arrow-down,
.arrow-up {
  display: inline-block;
  padding-left: 5px;
}

.dropdown {
  display: none;
}

.selected {
  border: 4px solid #CCCCCC;
}

    Show

    XXXXXXXXXX Content XXXXXXXXXX

So what I want to do is that: Originally the content will be hidden, with a title "Show" with arrow down icon is shown. If I click on the title, the hidden content will be shown and the title will change to "Hide" and with arrow up icon.

Originally I can achieve the toggle with those text, however, after I have tried to add the image toggle script, it is not working.

$(this).find('i').toggleClass('arrow-down arrow-up');

Anyone can share with me your solution/opinion here? Thank you so much for your time of reading my question!

Body:
When you do this:

$(this).text("any text");

You remove the <i> element that you're using as an arrow.  The resulting markup becomes:

<span class="showmore">any text</span>

Since the <i> is now gone, there's nothing to toggle.  Instead of setting the text in the entire element, create a child element to hold the text:

<span class="showmore">
    <span>Show</span>
    <i class="sprite arrow-down"></i>
</span>

Then you can target that specific element to set the text:

$(this).find("span").text("any text");

Demo:

$(function() {
  $('.showmore').click(
    function() {
      $(this).closest("div").next(".dropdown").toggle();
      $(this).find('i').toggleClass('arrow-down arrow-up');
      if ($(this).find("span").text() == "Show") {
        $(this).find("span").text("Hide");
      } else {
        $(this).find("span").text("Show");
      }
      $(this).closest("div").next(".dropdown").toggleClass('selected');
    }
  )
})

.title {
  background-color: #CCCCCC;
}

.sprite {
  background-image: url(https://image.ibb.co/bHTF8R/pinkarrow.png);
  background-repeat: no-repeat;
  display: block;
}

.arrow-down {
  width: 9px;
  height: 6px;
  background-position: -9px 0;
}

.arrow-up {
  width: 9px;
  height: 6px;
  background-position: 0 0;
}

.arrow-down,
.arrow-up {
  display: inline-block;
  padding-left: 5px;
}

.dropdown {
  display: none;
}

.selected {
  border: 4px solid #CCCCCC;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="content">
  <div class="title">
    <span class="showmore">
      <span>Show</span>
      <i class="sprite arrow-down"></i>
    </span>
  </div>
  <!--End of class Title-->

  <div class="dropdown">
    XXXXXXXXXX Content XXXXXXXXXX
  </div>
</div>

(Note: In my browser the styling on the "up arrow" doesn't look quite right.  Probably needs some tweaking.)


问:
Keeping track of points in simple console game
I'm having a hard time wrapping my mind around this. Every time the player makes a wrong guess, it should subtract his/her bet from the initial balance.
Since it is in a loop, it always takes the initial balance from the beginning spits out the same balance every time. (obviously)
I've tried assigning different variables and just can't seem to figure it out.

I've omitted the medium and hard difficulty methods as they are of no use right now, until I figure out this one.

My Main() only calls the setDifficulty(). Nothing else.

```<code>class Control
{
    int selectedNumber = 0;
    Random num = new Random();
    bool playAgain = true;
    int difficulty = 0;
    int bet = 0;
    int initialBalance = 20;
    int runningCredits = 0;
    int credits = 0;

    public Control()
    { }

    //sets game difficulty
    public void SetDifficulty()
    {

        Console.Clear();
        Console.WriteLine("Please select level of difficulty between 1 - 100");
        difficulty = int.Parse(Console.ReadLine());

        if (difficulty >= 1 && difficulty <= 20)
            LetsPlayEasy();

        else if (difficulty >= 21 && difficulty <= 50)
            LetsPlayMedium();

        else if (difficulty >= 51 && difficulty <= 100)
            LetsPlayHard();

        else
        {
            SetDifficulty();
        }

    }

    //easy level method
    public void LetsPlayEasy()
    {
        //variables
        int userGuess;
        int numGuesses = 0;
        selectedNumber = num.Next(1, 101);

        Console.BackgroundColor = ConsoleColor.DarkYellow;
        Console.Clear();
        Console.ForegroundColor = ConsoleColor.White;

        Console.WriteLine("Difficulty level = EASY");

        Console.WriteLine("\nBeggining credit balance = " + initialBalance);
        Console.WriteLine("\nPlease place a bet. You will lose those credits for every incorrect guess!");
        bet = int.Parse(Console.ReadLine());

        do
        {
            Console.WriteLine("\nGuess a number between 1 and 100.");
            userGuess = Convert.ToInt32(Console.ReadLine());
            numGuesses++;

            UI output = new UI();
            output.CompareNumbers(userGuess, ref selectedNumber, ref playAgain, ref numGuesses);

            runningCredits = (initialBalance - bet);
            Console.WriteLine("\nYou have " + runningCredits + " credits remaining.");

        } while (playAgain == true);
    }
</code>```

```<code>class UI
{
    Random num = new Random();
    int keepGoing;

    public UI()
    { }

    //compare user's guess to selected number
    public void CompareNumbers(int userGuess, ref int selectedNumber, ref bool playAgain, ref int numGuesses)
    {
        Control difficulty = new Control();
        Admin say = new Admin();

        if (userGuess > selectedNumber)
        {
            Console.Beep(600, 300);
            Console.WriteLine("\nToo High! Guess Again!");

        }

        else if (userGuess < selectedNumber)
        {
            Console.Beep(300, 300);
            Console.WriteLine("\nToo Low! Guess Again!");

        }
        else
        {
            Console.Beep(350, 300);
            Console.Beep(380, 200);
            Console.Beep(380, 100);
            Console.Beep(500, 1100);
            Console.WriteLine("\n\nCongrats! It took you " + numGuesses + " guesses to win.");
            numGuesses = 0;
            Console.WriteLine("Press 1 to play again or 2 to quit.");
            keepGoing = int.Parse(Console.ReadLine());

            while (keepGoing != 1 && keepGoing != 2)
            {
                Console.WriteLine("\n\nPlease type either 1 or 2 only!");
                keepGoing = int.Parse(Console.ReadLine());
            }

            if (keepGoing == 2)
            {
                playAgain = false;
                say.Goodbye();
            }

            else
            {
                Console.Clear();
                difficulty.SetDifficulty();
            }

        }

    }
}
</code>```

}

答:
```<code>runningCredits = (initialBalance - bet);
</code>```

You don't change initialBalance or bet in the loop, so every iteration has the same value of runningCredits.

Outside the loop, do this:

```<code>runningCredits = initialBalance;
</code>```

Inside the loop, do this:

```<code>runningCredits -= bet;
</code>```

Note: you don't have any code to check in the loop to see if the user guessed right or wrong (and as such, the user always loses and you always subtract out the bet).

Body:
I'm having a hard time wrapping my mind around this. Every time the player makes a wrong guess, it should subtract his/her bet from the initial balance.
Since it is in a loop, it always takes the initial balance from the beginning spits out the same balance every time. (obviously)
I've tried assigning different variables and just can't seem to figure it out.

I've omitted the medium and hard difficulty methods as they are of no use right now, until I figure out this one.

My Main() only calls the setDifficulty(). Nothing else.

class Control
{
    int selectedNumber = 0;
    Random num = new Random();
    bool playAgain = true;
    int difficulty = 0;
    int bet = 0;
    int initialBalance = 20;
    int runningCredits = 0;
    int credits = 0;

    public Control()
    { }

    //sets game difficulty
    public void SetDifficulty()
    {

        Console.Clear();
        Console.WriteLine("Please select level of difficulty between 1 - 100");
        difficulty = int.Parse(Console.ReadLine());

        if (difficulty >= 1 && difficulty <= 20)
            LetsPlayEasy();

        else if (difficulty >= 21 && difficulty <= 50)
            LetsPlayMedium();

        else if (difficulty >= 51 && difficulty <= 100)
            LetsPlayHard();

        else
        {
            SetDifficulty();
        }

    }

    //easy level method
    public void LetsPlayEasy()
    {
        //variables
        int userGuess;
        int numGuesses = 0;
        selectedNumber = num.Next(1, 101);

        Console.BackgroundColor = ConsoleColor.DarkYellow;
        Console.Clear();
        Console.ForegroundColor = ConsoleColor.White;

        Console.WriteLine("Difficulty level = EASY");

        Console.WriteLine("\nBeggining credit balance = " + initialBalance);
        Console.WriteLine("\nPlease place a bet. You will lose those credits for every incorrect guess!");
        bet = int.Parse(Console.ReadLine());

        do
        {
            Console.WriteLine("\nGuess a number between 1 and 100.");
            userGuess = Convert.ToInt32(Console.ReadLine());
            numGuesses++;

            UI output = new UI();
            output.CompareNumbers(userGuess, ref selectedNumber, ref playAgain, ref numGuesses);

            runningCredits = (initialBalance - bet);
            Console.WriteLine("\nYou have " + runningCredits + " credits remaining.");

        } while (playAgain == true);
    }

class UI
{
    Random num = new Random();
    int keepGoing;

    public UI()
    { }

    //compare user's guess to selected number
    public void CompareNumbers(int userGuess, ref int selectedNumber, ref bool playAgain, ref int numGuesses)
    {
        Control difficulty = new Control();
        Admin say = new Admin();

        if (userGuess > selectedNumber)
        {
            Console.Beep(600, 300);
            Console.WriteLine("\nToo High! Guess Again!");

        }

        else if (userGuess < selectedNumber)
        {
            Console.Beep(300, 300);
            Console.WriteLine("\nToo Low! Guess Again!");

        }
        else
        {
            Console.Beep(350, 300);
            Console.Beep(380, 200);
            Console.Beep(380, 100);
            Console.Beep(500, 1100);
            Console.WriteLine("\n\nCongrats! It took you " + numGuesses + " guesses to win.");
            numGuesses = 0;
            Console.WriteLine("Press 1 to play again or 2 to quit.");
            keepGoing = int.Parse(Console.ReadLine());

            while (keepGoing != 1 && keepGoing != 2)
            {
                Console.WriteLine("\n\nPlease type either 1 or 2 only!");
                keepGoing = int.Parse(Console.ReadLine());
            }

            if (keepGoing == 2)
            {
                playAgain = false;
                say.Goodbye();
            }

            else
            {
                Console.Clear();
                difficulty.SetDifficulty();
            }

        }

    }
}

}

Body:
runningCredits = (initialBalance - bet);

You don't change initialBalance or bet in the loop, so every iteration has the same value of runningCredits.

Outside the loop, do this:

runningCredits = initialBalance;

Inside the loop, do this:

runningCredits -= bet;

Note: you don't have any code to check in the loop to see if the user guessed right or wrong (and as such, the user always loses and you always subtract out the bet).


问:
Multiple AuthProvider Servicestack
I am having some issue to make work 2 auth provider at the same time for servicestack.
I am using the : JWT Tokens - Allowing users to authenticate with JWT Tokens I am my users get authenticate fine.

Still Now I would like to use the API Keys - Allowing users to authenticate with API Keys for a few external 3rd Parties user access.

Still when I Configure both my users allready authenticate by JWT Tokens doesnt work anymore.

Here is my configuration AuthProvider configuration :

```<code>        IAuthProvider[] providers = new IAuthProvider[]
        {
            new JwtAuthProviderReader(this.AppSettings)
            {
                HashAlgorithm = "RS256",
                PrivateKeyXml = this.AppSettings.GetString("TokenPrivateKeyXml"),
                PublicKeyXml = this.AppSettings.GetString("TokenPublicKeyXml"),
                RequireSecureConnection = this.AppSettings.Get<bool>("TokenUseHttps"),
                EncryptPayload = this.AppSettings.Get<bool>("TokenEncryptPayload"),
                PopulateSessionFilter = (session, obj, req) =>
                {
                    ApplicationUserSession customSession = session as ApplicationUserSession;
                    if (customSession != null)
                    {
                        customSession.TimeZoneName = obj["TimeZoneName"];
                        customSession.Type =  (FbEnums.UserType) (obj["UserType"].ToInt());
                        if (Guid.TryParse(obj["RefIdGuid"], out Guid result))
                        {
                            customSession.RefIdGuid = result;
                        }
                    }
                },
            },
            new ApiKeyAuthProvider(AppSettings)
            {
                RequireSecureConnection = false
            }

        };
</code>```

I am genereting fine the token with JwtAuth. Still It look like servicestack is not accepting my token as a valid session, because now whenever I do :

var session = httpReq.GetSession();

session.IsAuthenticated --> is always FALSE

If my remove ApiKeyAuthProvider from the configuration, token from JwtAuth working fine again.

How do I make both provider works together and tell servicestack tham some users will use JwtAuth and others ApiKeyAuth ?

答: You need to call a Service that requires Authentication, e.g. has the [Authenticate] attribute in order to trigger pre-Authentication for the IAuthWithRequest providers like JWT and API Key AuthProviders.

Title: Multiple AuthProvider Servicestack

Body:
I am having some issue to make work 2 auth provider at the same time for servicestack.
I am using the : JWT Tokens - Allowing users to authenticate with JWT Tokens I am my users get authenticate fine.

Still Now I would like to use the API Keys - Allowing users to authenticate with API Keys for a few external 3rd Parties user access.

Still when I Configure both my users allready authenticate by JWT Tokens doesnt work anymore.

Here is my configuration AuthProvider configuration :

        IAuthProvider[] providers = new IAuthProvider[]
        {
            new JwtAuthProviderReader(this.AppSettings)
            {
                HashAlgorithm = "RS256",
                PrivateKeyXml = this.AppSettings.GetString("TokenPrivateKeyXml"),
                PublicKeyXml = this.AppSettings.GetString("TokenPublicKeyXml"),
                RequireSecureConnection = this.AppSettings.Get<bool>("TokenUseHttps"),
                EncryptPayload = this.AppSettings.Get<bool>("TokenEncryptPayload"),
                PopulateSessionFilter = (session, obj, req) =>
                {
                    ApplicationUserSession customSession = session as ApplicationUserSession;
                    if (customSession != null)
                    {
                        customSession.TimeZoneName = obj["TimeZoneName"];
                        customSession.Type =  (FbEnums.UserType) (obj["UserType"].ToInt());
                        if (Guid.TryParse(obj["RefIdGuid"], out Guid result))
                        {
                            customSession.RefIdGuid = result;
                        }
                    }
                },
            },
            new ApiKeyAuthProvider(AppSettings)
            {
                RequireSecureConnection = false
            }

        };

I am genereting fine the token with JwtAuth. Still It look like servicestack is not accepting my token as a valid session, because now whenever I do :

var session = httpReq.GetSession();

session.IsAuthenticated --> is always FALSE

If my remove ApiKeyAuthProvider from the configuration, token from JwtAuth working fine again.

How do I make both provider works together and tell servicestack tham some users will use JwtAuth and others ApiKeyAuth ?