问:
how to set onChange handler to change the language in react i18next
-the select form that allow the user to change the language don't work with onclick how can I use onChange handler

am using react i18next.

*keep in mind that am not getting any errors or warnings.
this is my code

```<code>import i18n from 'i18next';

export default function Footer() {
const languages = [
    {
      code: "fr",
      name: "francais",
      countryCode:"fr"
    },
    {
      code: "en",
      name: "english",
      countryCode:"gb"
    },
    {
      code: "ar",
      name: "العربية",
      countryCode:"sa"
    }
  ]

return <Form.Select aria-label="Default select example" >
{languages.map(({code,name, countryCode})=>{
  return(
    <option key={countryCode} onClick={()=> i18n.changeLanguage(code)}>{name}</option>
  )
})}
</Form.Select>
}
</code>```

答:
The onChange handler to change the language needs to be set on the Form.Select component, like this: https://codesandbox.io/s/react-code-works-on-mozilla-but-but-dont-on-chrome-forked-1lkvw?file=/src/Footer.js:579-657</p>
```<code>import { useTranslation } from "react-i18next";
import { Container, Form } from "react-bootstrap";

export default function Footer() {
  const { i18n } = useTranslation();

  const languages = [
    {
      code: "fr",
      name: "francais",
      countryCode: "fr"
    },
    {
      code: "en",
      name: "english",
      countryCode: "gb"
    },
    {
      code: "ar",
      name: "العربية",
      countryCode: "sa"
    }
  ];

  return (
    <div className="section footer">
      <Container>
        <Form.Select
          defaultValue={i18n.resolvedLanguage}
          onChange={e => {
            i18n.changeLanguage(e.target.value);
          }}
        >
          {languages.map(({ code, name, countryCode }) => {
            return (
              <option
                key={countryCode}
                value={code}
              >
                {name}
              </option>
            );
          })}
        </Form.Select>
      </Container>
    </div>
  );
}
</code>```

Body:
-the select form that allow the user to change the language don't work with onclick how can I use onChange handler

am using react i18next.

*keep in mind that am not getting any errors or warnings.
this is my code

import i18n from 'i18next';

export default function Footer() {
const languages = [
    {
      code: "fr",
      name: "francais",
      countryCode:"fr"
    },
    {
      code: "en",
      name: "english",
      countryCode:"gb"
    },
    {
      code: "ar",
      name: "العربية",
      countryCode:"sa"
    }
  ]

return <Form.Select aria-label="Default select example" >
{languages.map(({code,name, countryCode})=>{
  return(
    <option key={countryCode} onClick={()=> i18n.changeLanguage(code)}>{name}</option>
  )
})}
</Form.Select>
}

Body:
The onChange handler to change the language needs to be set on the Form.Select component, like this: https://codesandbox.io/s/react-code-works-on-mozilla-but-but-dont-on-chrome-forked-1lkvw?file=/src/Footer.js:579-657

import { useTranslation } from "react-i18next";
import { Container, Form } from "react-bootstrap";

export default function Footer() {
  const { i18n } = useTranslation();

  const languages = [
    {
      code: "fr",
      name: "francais",
      countryCode: "fr"
    },
    {
      code: "en",
      name: "english",
      countryCode: "gb"
    },
    {
      code: "ar",
      name: "العربية",
      countryCode: "sa"
    }
  ];

  return (
    <div className="section footer">
      <Container>
        <Form.Select
          defaultValue={i18n.resolvedLanguage}
          onChange={e => {
            i18n.changeLanguage(e.target.value);
          }}
        >
          {languages.map(({ code, name, countryCode }) => {
            return (
              <option
                key={countryCode}
                value={code}
              >
                {name}
              </option>
            );
          })}
        </Form.Select>
      </Container>
    </div>
  );
}


来源: stackexchange

问:
Manipulating Nested JSON Arrays
i have bellow json array

```<code>var rowdataarray = [
                     {
                      "products": "Cars",
                      "solddate" : "2022-01-01",
                      "noofitems" : "7"
                     },
                     {
                      "products": "books",
                      "solddate" : "2022-01-01",
                      "noofitems" : "10"
                     },
                     {
                      "products": "Cars",
                      "solddate" : "2022-01-02",
                      "noofitems" : "2"
                     },
                     {
                      "products": "Table",
                      "solddate" : "2022-01-02",
                      "noofitems" : "5"
                     }
                   ];
</code>```

and then have category array

```<code>const category = ["Cars","books","Table"]
</code>```

based on these two array trying to create new array which will give me each day for each product how many items sold. above category must follow when creating data array. if the product is not sold on that day then it should insert as 0.

array expecting

```<code>var finalarray = [{
        date: '2022-01-01',
        data: [7,10,0]
    }, {
        date: '2022-01-02',
        data: [2,0,5]
    }]
</code>```

bellow code written not able to contiunue forward

```<code> $.when(
 $.each(category , function (key, val) {

        $.each(rowdataarray , function (key, x) {

                if(x.products == val){
                    finalarray .push({
                        "date" : x.solddate,
                        "data" : [x.noofitems]
                    })
                }
        })
 })
 ).then(function () {
    console.log(test)
   });
</code>```

答:
Collect the data by date and associate each count by product

Map over the entries and query each for your category

var rowdataarray = [{"products":"Cars","solddate":"2022-01-01","noofitems":"7"},{"products":"books","solddate":"2022-01-01","noofitems":"10"},{"products":"Cars","solddate":"2022-01-02","noofitems":"2"},{"products":"Table","solddate":"2022-01-02","noofitems":"5"}]
const category = ["Cars","books","Table"]

const byDate = rowdataarray.reduce((m, {
  solddate: d,
  products: p,
  noofitems: c
}) => ({
  ...m,
  [ d ]: { // the date is the top-level key
    ...m[d],
    [ p ]: (m[d]?.[p] ?? 0) + parseFloat(c) // add the count to any existing product count
  }
}), {})
console.log("byDate", byDate)

const finalarray = Object.entries(byDate).map(([ date, counts ]) => ({
  date,
  data: category.map(cat => counts[cat] ?? 0)
}))

console.info("finalarray", finalarray)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; }</code>```

ContentLicense: CC BY-SA 4.0

Title: Manipulating Nested JSON Arrays

Body:
i have bellow json array

var rowdataarray = [
                     {
                      "products": "Cars",
                      "solddate" : "2022-01-01",
                      "noofitems" : "7"
                     },
                     {
                      "products": "books",
                      "solddate" : "2022-01-01",
                      "noofitems" : "10"
                     },
                     {
                      "products": "Cars",
                      "solddate" : "2022-01-02",
                      "noofitems" : "2"
                     },
                     {
                      "products": "Table",
                      "solddate" : "2022-01-02",
                      "noofitems" : "5"
                     }
                   ];

and then have category array

const category = ["Cars","books","Table"]

based on these two array trying to create new array which will give me each day for each product how many items sold. above category must follow when creating data array. if the product is not sold on that day then it should insert as 0.

array expecting

var finalarray = [{
        date: '2022-01-01',
        data: [7,10,0]
    }, {
        date: '2022-01-02',
        data: [2,0,5]
    }]

bellow code written not able to contiunue forward

 $.when(
 $.each(category , function (key, val) {

        $.each(rowdataarray , function (key, x) {

                if(x.products == val){
                    finalarray .push({
                        "date" : x.solddate,
                        "data" : [x.noofitems]
                    })
                }
        })
 })
 ).then(function () {
    console.log(test)
   });

Body:
Collect the data by date and associate each count by product

Map over the entries and query each for your category

var rowdataarray = [{"products":"Cars","solddate":"2022-01-01","noofitems":"7"},{"products":"books","solddate":"2022-01-01","noofitems":"10"},{"products":"Cars","solddate":"2022-01-02","noofitems":"2"},{"products":"Table","solddate":"2022-01-02","noofitems":"5"}]
const category = ["Cars","books","Table"]

const byDate = rowdataarray.reduce((m, {
  solddate: d,
  products: p,
  noofitems: c
}) => ({
  ...m,
  [ d ]: { // the date is the top-level key
    ...m[d],
    [ p ]: (m[d]?.[p] ?? 0) + parseFloat(c) // add the count to any existing product count
  }
}), {})
console.log("byDate", byDate)

const finalarray = Object.entries(byDate).map(([ date, counts ]) => ({
  date,
  data: category.map(cat => counts[cat] ?? 0)
}))

console.info("finalarray", finalarray)

.as-console-wrapper { max-height: 100% !important; }


问:
sfdx force:apex:test:run include coverage for only those tests included in the sfdx command
I have an org that has approx 530 test classes .I am currently working on a nodejs project that uses the sfdx commands to run the tests in the org and then generate code coverage report, analyze and classify them so that I can use the classified data to find what apex class lines are covered by which test classes/methods.

Since the amount of test classes are very large and salesforce removes coverage data if the records exceed 10K (which happens because of such a large amount of classes, triggers and test classes), I have tried to implement batches of tests to be run.

lets say the batch consists of Test_1,Test_2,.....,Test_10.
The command I am using is given below.

```<code>sfdx force:apex:test:run --codecoverage -r json --classnames "Test_1,Test_2,.....,Test_10" -u testOrg --outputdir path/to/folder
</code>```

The problem here is

command blocks the script until the test are completed and overall coverage is calculated.

after completion testRunId is not returned.

with each subsequent run, previous test coverage data is also included in the output which is unrequired.

Is there anyway to run the command such that coverage data is only provided for the tests included in the batch?

答:
Don't know if it's still relevant or not, but there is a solution.

You can overwrite the SFDX_MAX_QUERY_LIMIT environment variable's value and retrieve all records that you need.

From https://developer.salesforce.com/docs/atlas.en-us.sfdx_setup.meta/sfdx_setup/sfdx_dev_cli_env_variables.htm:

SFDX_MAX_QUERY_LIMIT

The maximum number of Salesforce records returned by a CLI command.

Default value is 10,000.

Example:

SFDX_MAX_QUERY_LIMIT=200000

Body:
I have an org that has approx 530 test classes .I am currently working on a nodejs project that uses the sfdx commands to run the tests in the org and then generate code coverage report, analyze and classify them so that I can use the classified data to find what apex class lines are covered by which test classes/methods.

Since the amount of test classes are very large and salesforce removes coverage data if the records exceed 10K (which happens because of such a large amount of classes, triggers and test classes), I have tried to implement batches of tests to be run.

lets say the batch consists of Test_1,Test_2,.....,Test_10.
The command I am using is given below.

sfdx force:apex:test:run --codecoverage -r json --classnames "Test_1,Test_2,.....,Test_10" -u testOrg --outputdir path/to/folder

The problem here is

command blocks the script until the test are completed and overall coverage is calculated.

after completion testRunId is not returned.

with each subsequent run, previous test coverage data is also included in the output which is unrequired.

Is there anyway to run the command such that coverage data is only provided for the tests included in the batch?


问:
passing a string variable as and input to loc accessor in python
I am trying to pass a string variable (containing the parameter) to the .loc accessor but cannot get the syntax correct.

```<code>startenddate = "'2020-06':'2020-07'"
qf = cf.QuantFig(df = stock.data.loc[startenddate])
</code>```

I get the error

```<code>ParserError: Unknown string format: '2020-06':'2020-07'
</code>```

it works if I just plug in qf = cf.QuantFig(df = stock.data.loc['2020-06':'2020-07'])
but I want to convert this into a function and pass starenddate as a parameter that us used in the .loc.

答:
You can achieve the same by doing this:

```<code>start_date = '2020-06'
end_date = '2020-07'
data.loc[start_date:end_date]
</code>```

You're passing a string into the .loc[] and then you expect it to match with the index.

Body:
I am trying to pass a string variable (containing the parameter) to the .loc accessor but cannot get the syntax correct.

startenddate = "'2020-06':'2020-07'"
qf = cf.QuantFig(df = stock.data.loc[startenddate])

I get the error

ParserError: Unknown string format: '2020-06':'2020-07'

it works if I just plug in qf = cf.QuantFig(df = stock.data.loc['2020-06':'2020-07'])
but I want to convert this into a function and pass starenddate as a parameter that us used in the .loc.

Body:
You can achieve the same by doing this:

start_date = '2020-06'
end_date = '2020-07'
data.loc[start_date:end_date]

You're passing a string into the .loc[] and then you expect it to match with the index.


问:
Assigning values from data frame to vector in R
I have a data frame as below:

```<code>data <- data.frame(name = c("a", "b"),
                   value = c("apple", "ball"))
</code>```

Now from this data I want to create a vector as follows:

```<code>transformed_data <- c( a = "apple", b = "ball")
</code>```

How this is possible to do in R?

答:
There's a tidyverse approach given in the comment, so I'll include a base R approach here:

```<code>setNames(data[["value"]], data[["name"]])

      a       b
"apple"  "ball"
</code>```

Body:
I have a data frame as below:

data <- data.frame(name = c("a", "b"),
                   value = c("apple", "ball"))

Now from this data I want to create a vector as follows:

transformed_data <- c( a = "apple", b = "ball")

How this is possible to do in R?

Body:
There's a tidyverse approach given in the comment, so I'll include a base R approach here:

setNames(data[["value"]], data[["name"]])

      a       b
"apple"  "ball"


问:
Basic Question: I have media info app installed on my mac M1 but there's no CLI
as stated in the subject, I have purchased the mediainfo app from App Store but there's no CLI available. Please advise. I am on Apple M1</p>

答: The MediaInfo app on the Mac App Store is the graphical interface version. You can download the MediaInfo command line version on the dedicated download page.</p>


问:
How to get the first, second, third, and fourth week of the month?
I want to get all four weeks (first and last day date) on the current month with Monday as the start of the week.

I can only figure out how to get the current week's first and last date with this code:

```<code>var firstDayOfTheWeek =  DateTime.now().subtract(Duration(days: DateTime.now().weekday - 1));
var lastDayOfTheWeek =  DateTime.now().add(Duration(days: DateTime.daysPerWeek - DateTime.now().weekday));
</code>```

Thanks in advance!

答:
Below method return next weekday's DateTime what you want from now or specific day.

```<code>DateTime getNextWeekDay(int weekDay, {DateTime from}) {
  DateTime now = DateTime.now();

  if (from != null) {
    now = from;
  }

  int remainDays = weekDay - now.weekday + 7;

  return now.add(Duration(days: remainDays));
}
</code>```

The weekday parameter can be came like below DateTime const value or just int value.

```<code>class DateTime {
...
  static const int monday = 1;
  static const int tuesday = 2;
  static const int wednesday = 3;
  static const int thursday = 4;
  static const int friday = 5;
  static const int saturday = 6;
  static const int sunday = 7;
...
}
</code>```

If you want to get next Monday from now, call like below.

```<code>DateTime nextMonday = getNextWeekDay(DateTime.monday);
</code>```

If you want to get next next Monday from now, call like below.

Or you just add 7 days to 'nextMonday' variable.

```<code>DateTime nextMonday = getNextWeekDay(DateTime.monday);

DateTime nextNextMonday = getNextWeekDay(DateTime.monday, from: nextMonday);
or
DateTime nextNextMonday = nextMonday.add(Duration(days: 7));
</code>```

Body:
I want to get all four weeks (first and last day date) on the current month with Monday as the start of the week.

I can only figure out how to get the current week's first and last date with this code:

var firstDayOfTheWeek =  DateTime.now().subtract(Duration(days: DateTime.now().weekday - 1));
var lastDayOfTheWeek =  DateTime.now().add(Duration(days: DateTime.daysPerWeek - DateTime.now().weekday));

Thanks in advance!

Body:
Below method return next weekday's DateTime what you want from now or specific day.

DateTime getNextWeekDay(int weekDay, {DateTime from}) {
  DateTime now = DateTime.now();

  if (from != null) {
    now = from;
  }

  int remainDays = weekDay - now.weekday + 7;

  return now.add(Duration(days: remainDays));
}

The weekday parameter can be came like below DateTime const value or just int value.

class DateTime {
...
  static const int monday = 1;
  static const int tuesday = 2;
  static const int wednesday = 3;
  static const int thursday = 4;
  static const int friday = 5;
  static const int saturday = 6;
  static const int sunday = 7;
...
}

If you want to get next Monday from now, call like below.

DateTime nextMonday = getNextWeekDay(DateTime.monday);

If you want to get next next Monday from now, call like below.

Or you just add 7 days to 'nextMonday' variable.

DateTime nextMonday = getNextWeekDay(DateTime.monday);

DateTime nextNextMonday = getNextWeekDay(DateTime.monday, from: nextMonday);
or
DateTime nextNextMonday = nextMonday.add(Duration(days: 7));


问:
Modify all values in a dictionary
Code goes below:

```<code>d = {'a':0, 'b':0, 'c':0, 'd':0}  #at the beginning, all the values are 0.
s = 'cbad'  #a string
indices = map(s.index, d.keys())  #get every key's index in s, i.e., a-2, b-1, c-0, d-3
#then set the values to keys' index
d = dict(zip(d.keys(), indices))  #this is how I do it, any better way?
print d  #{'a':2, 'c':0, 'b':1, 'd':3}
</code>```

Any other way to do that?

PS. the code above is just a simple one to demonstrate my question.

答:
```<code>for k in d.iterkeys():
    d[k] = s.index[k]
</code>```

Or, if you don't already know the letters in the string:

```<code>d = {}
for i in range(len(s)):
    d[s[i]]=i
</code>```

Title: Modify all values in a dictionary

Body:
Code goes below:

d = {'a':0, 'b':0, 'c':0, 'd':0}  #at the beginning, all the values are 0.
s = 'cbad'  #a string
indices = map(s.index, d.keys())  #get every key's index in s, i.e., a-2, b-1, c-0, d-3
#then set the values to keys' index
d = dict(zip(d.keys(), indices))  #this is how I do it, any better way?
print d  #{'a':2, 'c':0, 'b':1, 'd':3}

Any other way to do that?

PS. the code above is just a simple one to demonstrate my question.

Body:
for k in d.iterkeys():
    d[k] = s.index[k]

Or, if you don't already know the letters in the string:

d = {}
for i in range(len(s)):
    d[s[i]]=i

ContentLicense: CC BY-SA 3.0


问:
JavaScript object related question that what will be the output of below code?

var x = 3;
var one = {
  x:2,
  two: {
    x:1,
    three:function(){
        return this.x;

    }
  }
}

var go = one.two.three;

 console.log(one.two.three() + "" + go());
 ```

Anyone can explain to me why output coming 13 why not 1-undefined?

答:
this keyword has a different binding that can change during runtime, depending on how the function was invoked.

When a function is on an object, and is accessed through that object, it's this context will be that object (unless explicitly bound otherwise, but I'll add notes on that later). This means this.x is referencing the same variable as one.two.x

When you reference that same function into a global variable, the this context becomes the global space (e.g. the window object on browsers, or globalThis in NodeJS). When this happens, this.x is now referencing global variable x.

There are other situations where this context rules are different, such as function closures or class functions.

Functions also have .bind method that returns a new function with an explicitly bound this variable.

e.g:

var x = 3;
var one = {
  x:2,
  two: {
    x:1,
    three:function(){
        return this.x;

    }
  }
}

one.two.three = one.two.three.bind(one);

var go = one.two.three;

console.log(one.two.three() + "" + go()); // prints 22
```
<p>There are also arrow functions, which implicitly have the <code>this</code> context bound to it's lexical scope... e.g:</p>
<pre class="lang-js prettyprint-override"><code>var x = 3;
var one = {
  x:2,
  two: {
    x:1,
    three: () => {
        return this.x;

    }
  }
}

var go = one.two.three;

console.log(one.two.three() + "" + go()); // prints 33
</code>```

This above example prints 33, because the lexical scope is the global scope, thus this.x is referencing global variable x.

Hope this answers your question without creating more questions.

Further Reading:

this keyword

Body:
var x = 3;
var one = {
  x:2,
  two: {
    x:1,
    three:function(){
        return this.x;

    }
  }
}

var go = one.two.three;

 console.log(one.two.three() + "" + go());

Anyone can explain to me why output coming 13 why not 1-undefined?

Body:
this keyword has a different binding that can change during runtime, depending on how the function was invoked.

When a function is on an object, and is accessed through that object, it's this context will be that object (unless explicitly bound otherwise, but I'll add notes on that later). This means this.x is referencing the same variable as one.two.x

When you reference that same function into a global variable, the this context becomes the global space (e.g. the window object on browsers, or globalThis in NodeJS). When this happens, this.x is now referencing global variable x.

There are other situations where this context rules are different, such as function closures or class functions.

Functions also have .bind method that returns a new function with an explicitly bound this variable.

e.g:

var x = 3;
var one = {
  x:2,
  two: {
    x:1,
    three:function(){
        return this.x;

    }
  }
}

one.two.three = one.two.three.bind(one);

var go = one.two.three;

console.log(one.two.three() + "" + go()); // prints 22

There are also arrow functions, which implicitly have the this context bound to it's lexical scope... e.g:

var x = 3;
var one = {
  x:2,
  two: {
    x:1,
    three: () => {
        return this.x;

    }
  }
}

var go = one.two.three;

console.log(one.two.three() + "" + go()); // prints 33

This above example prints 33, because the lexical scope is the global scope, thus this.x is referencing global variable x.

Hope this answers your question without creating more questions.

Further Reading:

this keyword


问:
Set Width based on other control Width
I am trying to set the Width of an image of 600px width, based on the Width of another control in the same Grid column (Grid.Column="0"). Is there a way where I can capture the Width of that element (MenuControl) and put that number in the image Width to get a lower value than 600px?

```<code><DockPanel Grid.Row="1" Grid.Column="0">
      <Image Source="/Assets/combanc.png" Margin="10" Width="{Binding ElementName=MenuControl, Path=ActualWidth}" />
</DockPanel>
</code>```

答:
If I understand your question correctly, you want to bind the size of another control, but the image should not exceed a maximum size of 600, regardless of the size of the other control. You can create a value converter that returns the minimum of the bound size and a parametrized maximum.

```<code>public class MaximumSizeConverter : IValueConverter
{
   public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
   {
      if (!(value is double size) ||
          !(parameter is string maximumText) ||
          !double.TryParse(maximumText, out var maximum))
         return Binding.DoNothing;

      return Math.Min(size, maximum);
   }

   public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
   {
      throw new InvalidOperationException();
   }
}
</code>```

Then you can create an instance of the converter in a resource dictionary in scope, e.g. Grid.Resources and use it in the Width binding of Image. Specify the converter by referencing it in the Converter property and set the maximum as ConverterParameter.

```<code><Grid>
   <Grid.Resources>
      <local:MaximumSizeConverter x:Key="MaximumSizeConverter"/>
   </Grid.Resources>
   <!-- ...your other markup. -->
   <DockPanel Grid.Row="1" Grid.Column="0">
      <Image Source="/Assets/combanc.png" Margin="10" Width="{Binding ElementName=MenuControl, Path=ActualWidth, Converter={StaticResource MaximumSizeConverter}, ConverterParameter=600}" />
   </DockPanel>
</Grid>
</code>```

Title: Set Width based on other control Width

Body:
I am trying to set the Width of an image of 600px width, based on the Width of another control in the same Grid column (Grid.Column="0"). Is there a way where I can capture the Width of that element (MenuControl) and put that number in the image Width to get a lower value than 600px?

<DockPanel Grid.Row="1" Grid.Column="0">
      <Image Source="/Assets/combanc.png" Margin="10" Width="{Binding ElementName=MenuControl, Path=ActualWidth}" />
</DockPanel>

Body:
If I understand your question correctly, you want to bind the size of another control, but the image should not exceed a maximum size of 600, regardless of the size of the other control. You can create a value converter that returns the minimum of the bound size and a parametrized maximum.

public class MaximumSizeConverter : IValueConverter
{
   public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
   {
      if (!(value is double size) ||
          !(parameter is string maximumText) ||
          !double.TryParse(maximumText, out var maximum))
         return Binding.DoNothing;

      return Math.Min(size, maximum);
   }

   public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
   {
      throw new InvalidOperationException();
   }
}

Then you can create an instance of the converter in a resource dictionary in scope, e.g. Grid.Resources and use it in the Width binding of Image. Specify the converter by referencing it in the Converter property and set the maximum as ConverterParameter.

<Grid>
   <Grid.Resources>
      <local:MaximumSizeConverter x:Key="MaximumSizeConverter"/>
   </Grid.Resources>
   <!-- ...your other markup. -->
   <DockPanel Grid.Row="1" Grid.Column="0">
      <Image Source="/Assets/combanc.png" Margin="10" Width="{Binding ElementName=MenuControl, Path=ActualWidth, Converter={StaticResource MaximumSizeConverter}, ConverterParameter=600}" />
   </DockPanel>
</Grid>


问:
WebMvcTest not ignoring custom redis configuration
The main class is like so:

```<code>@SpringBootApplication
@EnableCaching
@ComponentScan({"com.sample", "com.sample.lib"})
public class Application extends SpringBootServletInitializer {

    /**
     * The main method.
     *
     * @param args the arguments
     */
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    /**
     * Configure.
     *
     * @param builder the builder
     * @return the spring application builder
     */
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(Application.class);
    }
}
</code>```

The custom config

```<code>@Configuration
public class RedissonSpringDataConfig {

    @Bean
    public RedissonConnectionFactory redissonConnectionFactory(RedissonClient redisson) {
        return new RedissonConnectionFactory(redisson);
    }
   .....
</code>```

Test class:

```<code>@RunWith(SpringRunner.class)
@WebMvcTest(controllers = ConfigController.class ,excludeAutoConfiguration = { RedissonConfiguration.class,
        RedisAutoConfiguration.class, RedisRepositoriesAutoConfiguration.class, RedissonSpringDataConfig.class })
@AutoConfigureMockMvc
//@TestPropertySource(properties="spring.data.redis.repositories.enabled=false")
class ConfigControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private RestTemplate restTemplate;
</code>```

This throws

org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.redisson.api.RedissonClient]: Factory method 'redisson' threw exception; nested exception is java.net.UnknownHostException: failed to resolve 'redis' after 4 queries

I tried a bunch of options with TestPropertySource annotation. I read a couple of answers that ComponentScan would be the source of this error but couldn't fix with a couple of what I thought would be workarounds. Can someone help to ignore the custom redis client config class?

I commented out the @Configuration on custom configuration class but this would not be a graceful workaround.

答:
M. Deinum has given the correct answer. Sine you want use slice test, you need to simplify you @SpringBootApplication class, move the custom directive to a separate class

Please refer to: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#features.testing.spring-boot-applications.user-configuration-and-slicing

Body:
The main class is like so:

@SpringBootApplication
@EnableCaching
@ComponentScan({"com.sample", "com.sample.lib"})
public class Application extends SpringBootServletInitializer {

    /**
     * The main method.
     *
     * @param args the arguments
     */
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    /**
     * Configure.
     *
     * @param builder the builder
     * @return the spring application builder
     */
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(Application.class);
    }
}

The custom config

@Configuration
public class RedissonSpringDataConfig {

    @Bean
    public RedissonConnectionFactory redissonConnectionFactory(RedissonClient redisson) {
        return new RedissonConnectionFactory(redisson);
    }
   .....

Test class:

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = ConfigController.class ,excludeAutoConfiguration = { RedissonConfiguration.class,
        RedisAutoConfiguration.class, RedisRepositoriesAutoConfiguration.class, RedissonSpringDataConfig.class })
@AutoConfigureMockMvc
//@TestPropertySource(properties="spring.data.redis.repositories.enabled=false")
class ConfigControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private RestTemplate restTemplate;

This throws

org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.redisson.api.RedissonClient]: Factory method 'redisson' threw exception; nested exception is java.net.UnknownHostException: failed to resolve 'redis' after 4 queries

I tried a bunch of options with TestPropertySource annotation. I read a couple of answers that ComponentScan would be the source of this error but couldn't fix with a couple of what I thought would be workarounds. Can someone help to ignore the custom redis client config class?

I commented out the @Configuration on custom configuration class but this would not be a graceful workaround.


问:
How do i run 'tagged' scenarios with Cucumber tags in WebdriverIO
Hi _ if anyone can help here- I am trying to run a specific scenario by using Cucumber tags- this is the expression i am using to run the tests built with Webdriver- Cucumber framework-

npx wdio run wdio.conf.js --cucumberOpts.tagExpression='@Tag

When I use the above, nothing happens - i have defined the tag - '@Tag' at the feature level- so am expecting that all the scenarios within the feature file will get executed, however when i run the above command- nothing happens. Can someone please help?

答:
use as below

"test-imagesave": "wdio run 'config/wdio.conf.ts' --cucumberOpts.tagExpression '@tag'",


问:
I am trying to make "Game of Set" but don't know how to correctly check the set
Hi so I just started to learn coding and ruby is my first language. I am trying to make a game called "Game of Set" the rules can be checked in here or wikipedia

I am able to get users cards and enter them in different arrays. However, I have been spending a lot of time trying to figure out how to validate the set. I tried to compare the arrays index by index but the result is not what I wanted.
Example:

```<code>first = ['two', 'purple', 'stripe', 'diamond']
second = ['one', 'purple', 'solid', 'diamond']
third = ['three', 'purple', 'empty', 'diamond']
</code>```

this should be correct because all are purple, all are diamond, different number, and different filters.

```<code>first = ['one', 'green', 'stripe', 'squiggle']
second = ['one', 'purple', 'solid', 'diamond']
third = ['two', 'green', 'empty', 'oval']
</code>```

This is wrong because because two have the same number and one does not, similarly with the color.

This is the game of set that I want to achieve here

Please help thank you!

答:
We are given

```<code>first =  ['two',   'purple', 'stripe', 'diamond']
second = ['one',   'purple', 'solid',  'diamond']
third =  ['three', 'purple', 'empty',  'diamond']
</code>```

Let

```<code>arr = [first, second, third]
  #=> [["two",   "purple", "stripe", "diamond"],
  #    ["one",   "purple", "solid",  "diamond"],
  #    ["three", "purple", "empty",  "diamond"]]
</code>```

We wish to check if every "column" of arr contains either the same string for every "row" or a different string in each row.

Ruby doesn't have a concept of array "columns" and "rows", only elements. arr has three elements, namely the arrays first, second and third. We can, however, send the method Array#transpose1 to the object arr to obtain something we can use:

```<code>a = arr.transpose
  #=> [["two", "one", "three"],
  #    ["purple", "purple", "purple"],
  #    ["stripe", "solid", "empty"],
  #    ["diamond", "diamond", "diamond"]]
</code>```

We now just have to see if all four elements of a pass the test.

For one, we wish to know if

```<code>b = a[1]
  #=> ["purple", "purple", "purple"]
</code>```

satisfies the required property. A convenient way of doing that is to compute the unique elements of the array b with the method Array#uniq:

```<code>c = b.uniq
  #=> ["purple"]
</code>```

b meets the requirement if the number of elements in c equals either 1 or the number of elements in b, which is b.size #=> 3. As c.size #=> 1, c meets the requirement.

Notice that b.size is the same as arr.size.

We can put this together in a method:

```<code>def valid?(arr)
  nbr_elements = arr.size
  a = arr.transpose
  a.all? do |b|
    sz = b.uniq.size
    sz == 1 || sz == nbr_elements
  end
end
</code>```

See Enumerable#all?2

Let's try it.

```<code>valid?(arr)
  #=> true
</code>```

To illustrate the calculations performed by valid? I will run it again after salting the method with puts statements.

```<code>def valid?(arr)
  nbr_elements = arr.size
  puts "nbr_elements = #{nbr_elements}"
  a = arr.transpose
  a.all? do |b|
    sz = b.uniq.size
    puts "b = #{b}"
    puts "  sz = #{sz}"
    puts "  #{sz == 1} || #{sz == nbr_elements} => #{sz == 1 || sz == nbr_elements}"
    sz == 1 || sz == nbr_elements
  end
end
</code>```

```<code>valid?(arr)
  #=> true
</code>```

```<code>nbr_elements = 3
b = ["two", "one", "three"]
  sz = 3
  false || true => true
b = ["purple", "purple", "purple"]
  sz = 1
  true || false => true
b = ["stripe", "solid", "empty"]
  sz = 3
  false || true => true
b = ["diamond", "diamond", "diamond"]
  sz = 1
  true || false => true
</code>```

Let's also try the second example.

```<code>arr = [first, second, third]
  #=> [["two",   "purple", "stripe", "diamond"],
  #    ["one",   "purple", "solid",  "diamond"],
  #    ["three", "purple", "empty",  "diamond"]]
</code>```0

```<code>arr = [first, second, third]
  #=> [["two",   "purple", "stripe", "diamond"],
  #    ["one",   "purple", "solid",  "diamond"],
  #    ["three", "purple", "empty",  "diamond"]]
</code>```1

```<code>arr = [first, second, third]
  #=> [["two",   "purple", "stripe", "diamond"],
  #    ["one",   "purple", "solid",  "diamond"],
  #    ["three", "purple", "empty",  "diamond"]]
</code>```2

In practice we probably would not have the statement a = arr.transpose but instead would chain arr.transpose to all?:

```<code>def valid?(arr)
  nbr_elements = arr.size
  arr.transpose.all? do |b|
    sz = b.uniq.size
    sz.zero? || sz == nbr_elements
  end
end
</code>```

1 When all elements of an array are arrays having the same number of elements, the methods transpose and Array#zip can be used more-or-less interchangeably. @spickerman has used zip in his answer.

2 Enumerable is a module containing instance methods. Any class that includes that module (don't worry about the details now) has use of all of Enumerable's methods, more or less as  though they had been defined in the including class.

Body:
Hi so I just started to learn coding and ruby is my first language. I am trying to make a game called "Game of Set" the rules can be checked in here or wikipedia

I am able to get users cards and enter them in different arrays. However, I have been spending a lot of time trying to figure out how to validate the set. I tried to compare the arrays index by index but the result is not what I wanted.
Example:

first = ['two', 'purple', 'stripe', 'diamond']
second = ['one', 'purple', 'solid', 'diamond']
third = ['three', 'purple', 'empty', 'diamond']

this should be correct because all are purple, all are diamond, different number, and different filters.

first = ['one', 'green', 'stripe', 'squiggle']
second = ['one', 'purple', 'solid', 'diamond']
third = ['two', 'green', 'empty', 'oval']

This is wrong because because two have the same number and one does not, similarly with the color.

This is the game of set that I want to achieve here

Please help thank you!

Body:
We are given

first =  ['two',   'purple', 'stripe', 'diamond']
second = ['one',   'purple', 'solid',  'diamond']
third =  ['three', 'purple', 'empty',  'diamond']

Let

arr = [first, second, third]
  #=> [["two",   "purple", "stripe", "diamond"],
  #    ["one",   "purple", "solid",  "diamond"],
  #    ["three", "purple", "empty",  "diamond"]]

We wish to check if every "column" of arr contains either the same string for every "row" or a different string in each row.

Ruby doesn't have a concept of array "columns" and "rows", only elements. arr has three elements, namely the arrays first, second and third. We can, however, send the method Array#transpose1 to the object arr to obtain something we can use:

a = arr.transpose
  #=> [["two", "one", "three"],
  #    ["purple", "purple", "purple"],
  #    ["stripe", "solid", "empty"],
  #    ["diamond", "diamond", "diamond"]]

We now just have to see if all four elements of a pass the test.

For one, we wish to know if

b = a[1]
  #=> ["purple", "purple", "purple"]

satisfies the required property. A convenient way of doing that is to compute the unique elements of the array b with the method Array#uniq:

c = b.uniq
  #=> ["purple"]

b meets the requirement if the number of elements in c equals either 1 or the number of elements in b, which is b.size #=> 3. As c.size #=> 1, c meets the requirement.

Notice that b.size is the same as arr.size.

We can put this together in a method:

def valid?(arr)
  nbr_elements = arr.size
  a = arr.transpose
  a.all? do |b|
    sz = b.uniq.size
    sz == 1 || sz == nbr_elements
  end
end

See Enumerable#all?2

Let's try it.

valid?(arr)
  #=> true

To illustrate the calculations performed by valid? I will run it again after salting the method with puts statements.

def valid?(arr)
  nbr_elements = arr.size
  puts "nbr_elements = #{nbr_elements}"
  a = arr.transpose
  a.all? do |b|
    sz = b.uniq.size
    puts "b = #{b}"
    puts "  sz = #{sz}"
    puts "  #{sz == 1} || #{sz == nbr_elements} => #{sz == 1 || sz == nbr_elements}"
    sz == 1 || sz == nbr_elements
  end
end

valid?(arr)
  #=> true

nbr_elements = 3
b = ["two", "one", "three"]
  sz = 3
  false || true => true
b = ["purple", "purple", "purple"]
  sz = 1
  true || false => true
b = ["stripe", "solid", "empty"]
  sz = 3
  false || true => true
b = ["diamond", "diamond", "diamond"]
  sz = 1
  true || false => true

Let's also try the second example.

arr = [["one", "green",  "stripe", "squiggle"],
       ["one", "purple", "solid",  "diamond" ],
       ["two", "green",  "empty",  "oval"    ]]

valid?(arr)
  #=> false

nbr_elements = 3
b = ["one", "one", "two"]
  sz = 2
  false || false => false

In practice we probably would not have the statement a = arr.transpose but instead would chain arr.transpose to all?:

def valid?(arr)
  nbr_elements = arr.size
  arr.transpose.all? do |b|
    sz = b.uniq.size
    sz.zero? || sz == nbr_elements
  end
end

1 When all elements of an array are arrays having the same number of elements, the methods transpose and Array#zip can be used more-or-less interchangeably. @spickerman has used zip in his answer.

2 Enumerable is a module containing instance methods. Any class that includes that module (don't worry about the details now) has use of all of Enumerable's methods, more or less as  though they had been defined in the including class.


问:
Azure Powershell - Problem with assigning private IP address to an NIC
Here is my script

```<code>$my_vnet = Get-AzVirtualNetwork -Name <vnet_name>
$my_subnet = Get-AzVirtualNetworkSubnetConfig -Name <subnet_name> -VirtualNetwork $my_vnet
Add-AzNetworkInterfaceIpConfig -Name ext-ipconfig6 -NetworkInterface $my_nic -
Subnet $my_subnet -PrivateIpAddress 10.0.0.6
</code>```

There is no error when running the script. If I use the following command to check, I do see the  IP object created.

```<code>Get-AzNetworkInterfaceIpConfig -Name ext-ipconfig6 -NetworkInterface $my_nic
...
{
  "Name": "ext-ipconfig6",
  "PrivateIpAddress": "10.0.0.6",
  "PrivateIpAllocationMethod": "Static",
  "Subnet": {
    "Id": "blabla"
  },
  "Primary": false
}
</code>```

However, I don't see it created on the portal.

Comparing with others created in the portal, I see other properties like Etag, Id, ProvisioningState, ...etc. Where did I do wrong...?
Thanks!

答:
You are just creating the Network Interface IP configuration and not setting it to the existing Network interface itself.

I tested the same script which resulted as below :

To fix the above you will have to add | Set-AzNetworkInterface after the Add-AzNetworkInterfaceIpConfig command like below :

```<code>$vnet = Get-AzVirtualNetwork -Name "ansuman-vnet" -ResourceGroupName "ansumantest"
$nic= Get-AzNetworkInterface -Name "ansumannic01" -ResourceGroupName "ansumantest"
Add-AzNetworkInterfaceIpConfig -Name "IPConfig2" -NetworkInterface $nic -Subnet $vnet.Subnets[0]  -PrivateIpAddress "10.0.0.7" | Set-AzNetworkInterface
</code>```

Output:

Body:
Here is my script

$my_vnet = Get-AzVirtualNetwork -Name <vnet_name>
$my_subnet = Get-AzVirtualNetworkSubnetConfig -Name <subnet_name> -VirtualNetwork $my_vnet
Add-AzNetworkInterfaceIpConfig -Name ext-ipconfig6 -NetworkInterface $my_nic -
Subnet $my_subnet -PrivateIpAddress 10.0.0.6

There is no error when running the script. If I use the following command to check, I do see the  IP object created.

Get-AzNetworkInterfaceIpConfig -Name ext-ipconfig6 -NetworkInterface $my_nic
...
{
  "Name": "ext-ipconfig6",
  "PrivateIpAddress": "10.0.0.6",
  "PrivateIpAllocationMethod": "Static",
  "Subnet": {
    "Id": "blabla"
  },
  "Primary": false
}

However, I don't see it created on the portal.

Comparing with others created in the portal, I see other properties like Etag, Id, ProvisioningState, ...etc. Where did I do wrong...?
Thanks!

Body:
You are just creating the Network Interface IP configuration and not setting it to the existing Network interface itself.

I tested the same script which resulted as below :

To fix the above you will have to add | Set-AzNetworkInterface after the Add-AzNetworkInterfaceIpConfig command like below :

$vnet = Get-AzVirtualNetwork -Name "ansuman-vnet" -ResourceGroupName "ansumantest"
$nic= Get-AzNetworkInterface -Name "ansumannic01" -ResourceGroupName "ansumantest"
Add-AzNetworkInterfaceIpConfig -Name "IPConfig2" -NetworkInterface $nic -Subnet $vnet.Subnets[0]  -PrivateIpAddress "10.0.0.7" | Set-AzNetworkInterface

Output:


问:
How to show documentation on hover for custom API in VSCode?
I have a custom API for use where I am looking to show the documentation when I hover over the method. For example:

```<code>class A:

       // What foo does
       foo() { }
</code>```

So, if I am using an instance of class A where when I call the method foo on A for example:

```<code>A.foo()
</code>```

I want see what foo does when I hover over it. I am quite unsure where to look for in order to implement such custom behavior in vs code and I have been going through the documentation but cant seem to find anything that could be beneficial to build such behavior and use it as an extension. If anyone can guide me which part of the documentation in vs code API I should be looking at then I can start with that. Please let me know if I can further clarify on any aspect I went vaguely.

答:
You can add multi-line comments and it will show on hover:</p>
```<code>  class A {

  /**
  * @name foo
  * @param { string } text - text parameter
  * @returns { object }
  * @description Does this and that.
  * The `RequestBodySearch` object provides methods generating an elasticsearch
    search request body. The search request can be executed with a search DSL,
    which includes the Query DSL, within its body.
  */
   foo(){

  }
}
</code>```

Body:
I have a custom API for use where I am looking to show the documentation when I hover over the method. For example:

class A:

       // What foo does
       foo() { }

So, if I am using an instance of class A where when I call the method foo on A for example:

A.foo()

I want see what foo does when I hover over it. I am quite unsure where to look for in order to implement such custom behavior in vs code and I have been going through the documentation but cant seem to find anything that could be beneficial to build such behavior and use it as an extension. If anyone can guide me which part of the documentation in vs code API I should be looking at then I can start with that. Please let me know if I can further clarify on any aspect I went vaguely.

Body:
You can add multi-line comments and it will show on hover:

  class A {

  /**
  * @name foo
  * @param { string } text - text parameter
  * @returns { object }
  * @description Does this and that.
  * The `RequestBodySearch` object provides methods generating an elasticsearch
    search request body. The search request can be executed with a search DSL,
    which includes the Query DSL, within its body.
  */
   foo(){

  }
}


问:
TrackedPropertiesEvaluationFailed error in logic app
I have a really frustrating issue with a logic app

All I am trying to do is to parse the Json of my http request that comes into the logic app and add 2 properties as tracked properties

I get the totally useless error

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

I dont understand why the error message cannot be more descriptive as this is totally useless

I have tried loads of different ways and nothing works

My body is

```<code>{
   "eventType":"order.statusChanged",
   "resource":{
      "status":"Committed",
   }
}
</code>```

I think the correct syntax is

```<code>"@triggerBody()?['status']"
</code>```

which I put onto a tracked property called paymentStatus but I just get this error

What am I doing wrong?

Paul

答:
Seems like you are receiving this error due to syntatic error.

Post removing the syntatical error here is the JSON

```<code>{
    "properties": {
        "eventType": {
            "type": "string"
        },
        "resource": {
            "properties": {
                "status": {
                    "type": "string"
                }
            },
            "type": "object"
        }
    },
    "type": "object"
}
</code>```

Here is the tracker properties expression we have used to pull the payment status

```<code>"@body('Parse_JSON')?['resource']?['status']"
</code>```

Here is the sample output for reference:

Body:
I have a really frustrating issue with a logic app

All I am trying to do is to parse the Json of my http request that comes into the logic app and add 2 properties as tracked properties

I get the totally useless error

TrackedPropertiesEvaluationFailed

I dont understand why the error message cannot be more descriptive as this is totally useless

I have tried loads of different ways and nothing works

My body is

{
   "eventType":"order.statusChanged",
   "resource":{
      "status":"Committed",
   }
}

I think the correct syntax is

"@triggerBody()?['status']"

which I put onto a tracked property called paymentStatus but I just get this error

What am I doing wrong?

Paul

Body:
Seems like you are receiving this error due to syntatic error.

Post removing the syntatical error here is the JSON

{
    "properties": {
        "eventType": {
            "type": "string"
        },
        "resource": {
            "properties": {
                "status": {
                    "type": "string"
                }
            },
            "type": "object"
        }
    },
    "type": "object"
}

Here is the tracker properties expression we have used to pull the payment status

"@body('Parse_JSON')?['resource']?['status']"

Here is the sample output for reference:


问:
How to sign JSON responses in Express
I'm developing an Express.js server; since it manages sensible data, I'd like to add a cryptographic signature to every response, using a private key. The signature part is already OK, the problem is catching the JSON string just before is sent to the client to sign it.

Ideally I'd like to add a custom response header, e.g. X-signature, so clients could verify the received payload against the public key exposed by the service.

In Express, how can I intercept the response body after the JSON.stringify() call but before the headers are sent?

答:
I've copied what is done in the compression() middleware, replacing the send() method of Response with my own and calling the original one after I calculate the signature. Here's a simplified solution just to show the concept, in the real word I've taken care of body's possible types. The fact that calculateSignature() is an async function is a little troublesome, but everything seems to work well now.

Any comment is appreciated!

import express, { RequestHandler } from 'express';

declare const calculateSignature = (payload: string) => Promise<string>;

const responseSignature = (): RequestHandler => (_, res, next) => {
    const _send = res.send;
    res.send = (body) => {
        if (isPlaintextType(body)) {
            calculateSignature(body)
                .then((signature) => res.setHeader('X-Signature', signature))
                .catch((e) => console.error(e))
                .finally(() => _send.call(res, body));
            return res;
        } else {
            return _send.call(res, body);
        }
    };
    next();
};

const app = express();
app.use(responseSignature());
app.listen(3000);
```

Title: How to sign JSON responses in Express


问:
Readiness fails in the Eclipse Hono pods of the Cloud2Edge package
I am a bit desperate and I hope someone can help me. A few months ago I installed the eclipse cloud2edge package on a kubernetes cluster by following the installation instructions, creating a persistentVolume and running the helm install command with these options.

```<code>helm install -n $NS --wait --timeout 15m $RELEASE eclipse-iot/cloud2edge --set hono.prometheus.createInstance=false --set hono.grafana.enabled=false --dependency-update --debug
</code>```

The yaml of the persistentVolume is the following and I create it in the same namespace that I install the package.

```<code>apiVersion: v1
kind: PersistentVolume
metadata:
  name: pv-device-registry
spec:
  accessModes:
    - ReadWriteOnce
capacity:
  storage: 1Mi
hostPath:
  path: /mnt/
  type: Directory
</code>```

Everything works perfectly, all pods were ready and running, until the other day when the cluster crashed and some pods stopped working.

The kubectl get pods -n $NS output is as follows:

```<code>NAME                                          READY   STATUS    RESTARTS   AGE
ditto-mongodb-7b78b468fb-8kshj                1/1     Running   0          50m
dt-adapter-amqp-vertx-6699ccf495-fc8nx        0/1     Running   0          50m
dt-adapter-http-vertx-545564ff9f-gx5fp        0/1     Running   0          50m
dt-adapter-mqtt-vertx-58c8975678-k5n49        0/1     Running   0          50m
dt-artemis-6759fb6cb8-5rq8p                   1/1     Running   1          50m
dt-dispatch-router-5bc7586f76-57dwb           1/1     Running   0          50m
dt-ditto-concierge-f6d5f6f9c-pfmcw            1/1     Running   0          50m
dt-ditto-connectivity-f556db698-q89bw         1/1     Running   0          50m
dt-ditto-gateway-589d8f5596-59c5b             1/1     Running   0          50m
dt-ditto-nginx-897b5bc76-cx2dr                1/1     Running   0          50m
dt-ditto-policies-75cb5c6557-j5zdg            1/1     Running   0          50m
dt-ditto-swaggerui-6f6f989ccd-jkhsk           1/1     Running   0          50m
dt-ditto-things-79ff869bc9-l9lct              1/1     Running   0          50m
dt-ditto-thingssearch-58c5578bb9-pwd9k        1/1     Running   0          50m
dt-service-auth-698d4cdfff-ch5wp              1/1     Running   0          50m
dt-service-command-router-59d6556b5f-4nfcj    0/1     Running   0          50m
dt-service-device-registry-7cf75d794f-pk9ct   0/1     Running   0          50m
</code>```

The pods that fail all have the same error when running kubectl describe pod POD_NAME -n $NS.

```<code>Events:
Type     Reason     Age                    From               Message
----     ------     ----                   ----               -------
Normal   Scheduled  53m                    default-scheduler  Successfully assigned digitaltwins/dt-service-command-router-59d6556b5f-4nfcj to node1
Normal   Pulled     53m                    kubelet            Container image "index.docker.io/eclipse/hono-service-command-router:1.8.0" already present on machine
Normal   Created    53m                    kubelet            Created container service-command-router
Normal   Started    53m                    kubelet            Started container service-command-router
Warning  Unhealthy  52m                    kubelet            Readiness probe failed: Get "https://10.244.1.89:8088/readiness": net/http: request canceled (Client.Timeout exceeded while awaiting headers)
Warning  Unhealthy  2m58s (x295 over 51m)  kubelet            Readiness probe failed: HTTP probe failed with statuscode: 503
</code>```

According to this, the readinessProbe fails. In the yalm definition of the affected deployments, the readinessProbe is defined:

```<code>readinessProbe:
  failureThreshold: 3
  httpGet:
     path: /readiness
     port: health
     scheme: HTTPS
  initialDelaySeconds: 45
  periodSeconds: 10
  successThreshold: 1
  timeoutSeconds: 1
</code>```

I have tried increasing these values, increasing the delay to 600 and the timeout to 10. Also i have tried uninstalling the package and installing it again, but nothing changes: the installation fails because the pods are never ready and the timeout pops up. I have also exposed port 8088 (health) and called /readiness with wget and the result is still 503. On the other hand, I have tested if livenessProbe works and it works fine. I have also tried resetting the cluster. First I manually deleted everything in it and then used the following commands:

```<code>sudo kubeadm reset
sudo iptables -F && sudo iptables -t nat -F && sudo iptables -t mangle -F && sudo iptables -X
sudo systemctl stop kubelet
sudo systemctl stop docker
sudo rm -rf /var/lib/cni/
sudo rm -rf /var/lib/kubelet/*
sudo rm -rf /etc/cni/
sudo ifconfig cni0 down
sudo ifconfig flannel.1 down
sudo ifconfig docker0 down
sudo ip link set cni0 down
sudo brctl delbr cni0
sudo systemctl start docker
sudo kubeadm init --apiserver-advertise-address=192.168.44.11 --pod-network-cidr=10.244.0.0/16
mkdir -p $HOME/.kube
sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
sudo chown $(id -u):$(id -g) $HOME/.kube/config
kubectl --kubeconfig $HOME/.kube/config apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml
</code>```

The cluster seems to work fine because the Eclipse Ditto part has no problem, it's just the Eclipse Hono part. I add a little more information in case it may be useful.

The kubectl logs dt-service-command-router-b654c8dcb-s2g6t -n $NS output:

```<code>12:30:06.340 [vert.x-eventloop-thread-1] ERROR io.vertx.core.net.impl.NetServerImpl - Client from origin /10.244.1.101:44142 failed to connect over ssl: javax.net.ssl.SSLHandshakeException: Received fatal alert: certificate_unknown
12:30:06.756 [vert.x-eventloop-thread-1] ERROR io.vertx.core.net.impl.NetServerImpl - Client from origin /10.244.1.100:46550 failed to connect over ssl: javax.net.ssl.SSLHandshakeException: Received fatal alert: certificate_unknown
12:30:07.876 [vert.x-eventloop-thread-1] ERROR io.vertx.core.net.impl.NetServerImpl - Client from origin /10.244.1.102:40706 failed to connect over ssl: javax.net.ssl.SSLHandshakeException: Received fatal alert: certificate_unknown
12:30:08.315 [vert.x-eventloop-thread-1] DEBUG o.e.h.client.impl.HonoConnectionImpl - starting attempt [#258] to connect to server [dt-service-device-registry:5671, role: Device Registration]
12:30:08.315 [vert.x-eventloop-thread-1] DEBUG o.e.h.c.impl.ConnectionFactoryImpl - OpenSSL [available: false, supports KeyManagerFactory: false]
12:30:08.315 [vert.x-eventloop-thread-1] DEBUG o.e.h.c.impl.ConnectionFactoryImpl - using JDK's default SSL engine
12:30:08.315 [vert.x-eventloop-thread-1] DEBUG o.e.h.c.impl.ConnectionFactoryImpl - enabling secure protocol [TLSv1.3]
12:30:08.315 [vert.x-eventloop-thread-1] DEBUG o.e.h.c.impl.ConnectionFactoryImpl - enabling secure protocol [TLSv1.2]
12:30:08.315 [vert.x-eventloop-thread-1] DEBUG o.e.h.c.impl.ConnectionFactoryImpl - connecting to AMQP 1.0 container [amqps://dt-service-device-registry:5671, role: Device Registration]
12:30:08.339 [vert.x-eventloop-thread-1] DEBUG o.e.h.c.impl.ConnectionFactoryImpl - can't connect to AMQP 1.0 container [amqps://dt-service-device-registry:5671, role: Device Registration]: Failed to create SSL connection
12:30:08.339 [vert.x-eventloop-thread-1] WARN  o.e.h.client.impl.HonoConnectionImpl - attempt [#258] to connect to server [dt-service-device-registry:5671, role: Device Registration] failed
javax.net.ssl.SSLHandshakeException: Failed to create SSL connection
</code>```

The kubectl logs dt-adapter-amqp-vertx-74d69cbc44-7kmdq -n $NS output:

```<code>12:19:36.686 [vert.x-eventloop-thread-0] DEBUG o.e.h.client.impl.HonoConnectionImpl - starting attempt [#19] to connect to server [dt-service-device-registry:5671, role: Credentials]
12:19:36.686 [vert.x-eventloop-thread-0] DEBUG o.e.h.c.impl.ConnectionFactoryImpl - OpenSSL [available: false, supports KeyManagerFactory: false]
12:19:36.686 [vert.x-eventloop-thread-0] DEBUG o.e.h.c.impl.ConnectionFactoryImpl - using JDK's default SSL engine
12:19:36.686 [vert.x-eventloop-thread-0] DEBUG o.e.h.c.impl.ConnectionFactoryImpl - enabling secure protocol [TLSv1.3]
12:19:36.686 [vert.x-eventloop-thread-0] DEBUG o.e.h.c.impl.ConnectionFactoryImpl - enabling secure protocol [TLSv1.2]
12:19:36.686 [vert.x-eventloop-thread-0] DEBUG o.e.h.c.impl.ConnectionFactoryImpl - connecting to AMQP 1.0 container [amqps://dt-service-device-registry:5671, role: Credentials]
12:19:36.711 [vert.x-eventloop-thread-0] DEBUG o.e.h.c.impl.ConnectionFactoryImpl - can't connect to AMQP 1.0 container [amqps://dt-service-device-registry:5671, role: Credentials]: Failed to create SSL connection
12:19:36.712 [vert.x-eventloop-thread-0] WARN  o.e.h.client.impl.HonoConnectionImpl - attempt [#19] to connect to server [dt-service-device-registry:5671, role: Credentials] failed
javax.net.ssl.SSLHandshakeException: Failed to create SSL connection
</code>```

The kubectl version output is as follows:

```<code>Client Version: version.Info{Major:"1", Minor:"19", GitVersion:"v1.19.3", GitCommit:"1e11e4a2108024935ecfcb2912226cedeafd99df", GitTreeState:"clean", BuildDate:"2020-10-14T12:50:19Z", GoVersion:"go1.15.2", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"19", GitVersion:"v1.19.16", GitCommit:"e37e4ab4cc8dcda84f1344dda47a97bb1927d074", GitTreeState:"clean", BuildDate:"2021-10-27T16:20:18Z", GoVersion:"go1.15.15", Compiler:"gc", Platform:"linux/amd64"}
</code>```

Thanks in advance!

答:
based on the iconic Failed to create SSL Connection output in the logs, I assume that you have run into the dreaded The demo certificates included in the Hono chart have expired problem.

The Cloud2Edge package chart is being updated currently (https://github.com/eclipse/packages/pull/337) with the most recent version of the Ditto and Hono charts (which includes fresh certificates that are valid for two more years to come). As soon as that PR is merged and the Eclipse Packages chart repository has been rebuilt, you should be able to do a helm repo update and then (hopefully) succesfully install the c2e package.

Body:
I am a bit desperate and I hope someone can help me. A few months ago I installed the eclipse cloud2edge package on a kubernetes cluster by following the installation instructions, creating a persistentVolume and running the helm install command with these options.

helm install -n $NS --wait --timeout 15m $RELEASE eclipse-iot/cloud2edge --set hono.prometheus.createInstance=false --set hono.grafana.enabled=false --dependency-update --debug

The yaml of the persistentVolume is the following and I create it in the same namespace that I install the package.

apiVersion: v1
kind: PersistentVolume
metadata:
  name: pv-device-registry
spec:
  accessModes:
    - ReadWriteOnce
capacity:
  storage: 1Mi
hostPath:
  path: /mnt/
  type: Directory

Everything works perfectly, all pods were ready and running, until the other day when the cluster crashed and some pods stopped working.

The kubectl get pods -n $NS output is as follows:

NAME                                          READY   STATUS    RESTARTS   AGE
ditto-mongodb-7b78b468fb-8kshj                1/1     Running   0          50m
dt-adapter-amqp-vertx-6699ccf495-fc8nx        0/1     Running   0          50m
dt-adapter-http-vertx-545564ff9f-gx5fp        0/1     Running   0          50m
dt-adapter-mqtt-vertx-58c8975678-k5n49        0/1     Running   0          50m
dt-artemis-6759fb6cb8-5rq8p                   1/1     Running   1          50m
dt-dispatch-router-5bc7586f76-57dwb           1/1     Running   0          50m
dt-ditto-concierge-f6d5f6f9c-pfmcw            1/1     Running   0          50m
dt-ditto-connectivity-f556db698-q89bw         1/1     Running   0          50m
dt-ditto-gateway-589d8f5596-59c5b             1/1     Running   0          50m
dt-ditto-nginx-897b5bc76-cx2dr                1/1     Running   0          50m
dt-ditto-policies-75cb5c6557-j5zdg            1/1     Running   0          50m
dt-ditto-swaggerui-6f6f989ccd-jkhsk           1/1     Running   0          50m
dt-ditto-things-79ff869bc9-l9lct              1/1     Running   0          50m
dt-ditto-thingssearch-58c5578bb9-pwd9k        1/1     Running   0          50m
dt-service-auth-698d4cdfff-ch5wp              1/1     Running   0          50m
dt-service-command-router-59d6556b5f-4nfcj    0/1     Running   0          50m
dt-service-device-registry-7cf75d794f-pk9ct   0/1     Running   0          50m

The pods that fail all have the same error when running kubectl describe pod POD_NAME -n $NS.

Events:
Type     Reason     Age                    From               Message
----     ------     ----                   ----               -------
Normal   Scheduled  53m                    default-scheduler  Successfully assigned digitaltwins/dt-service-command-router-59d6556b5f-4nfcj to node1
Normal   Pulled     53m                    kubelet            Container image "index.docker.io/eclipse/hono-service-command-router:1.8.0" already present on machine
Normal   Created    53m                    kubelet            Created container service-command-router
Normal   Started    53m                    kubelet            Started container service-command-router
Warning  Unhealthy  52m                    kubelet            Readiness probe failed: Get "https://10.244.1.89:8088/readiness": net/http: request canceled (Client.Timeout exceeded while awaiting headers)
Warning  Unhealthy  2m58s (x295 over 51m)  kubelet            Readiness probe failed: HTTP probe failed with statuscode: 503

According to this, the readinessProbe fails. In the yalm definition of the affected deployments, the readinessProbe is defined:

readinessProbe:
  failureThreshold: 3
  httpGet:
     path: /readiness
     port: health
     scheme: HTTPS
  initialDelaySeconds: 45
  periodSeconds: 10
  successThreshold: 1
  timeoutSeconds: 1

I have tried increasing these values, increasing the delay to 600 and the timeout to 10. Also i have tried uninstalling the package and installing it again, but nothing changes: the installation fails because the pods are never ready and the timeout pops up. I have also exposed port 8088 (health) and called /readiness with wget and the result is still 503. On the other hand, I have tested if livenessProbe works and it works fine. I have also tried resetting the cluster. First I manually deleted everything in it and then used the following commands:

sudo kubeadm reset
sudo iptables -F && sudo iptables -t nat -F && sudo iptables -t mangle -F && sudo iptables -X
sudo systemctl stop kubelet
sudo systemctl stop docker
sudo rm -rf /var/lib/cni/
sudo rm -rf /var/lib/kubelet/*
sudo rm -rf /etc/cni/
sudo ifconfig cni0 down
sudo ifconfig flannel.1 down
sudo ifconfig docker0 down
sudo ip link set cni0 down
sudo brctl delbr cni0
sudo systemctl start docker
sudo kubeadm init --apiserver-advertise-address=192.168.44.11 --pod-network-cidr=10.244.0.0/16
mkdir -p $HOME/.kube
sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
sudo chown $(id -u):$(id -g) $HOME/.kube/config
kubectl --kubeconfig $HOME/.kube/config apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml

The cluster seems to work fine because the Eclipse Ditto part has no problem, it's just the Eclipse Hono part. I add a little more information in case it may be useful.

The kubectl logs dt-service-command-router-b654c8dcb-s2g6t -n $NS output:

12:30:06.340 [vert.x-eventloop-thread-1] ERROR io.vertx.core.net.impl.NetServerImpl - Client from origin /10.244.1.101:44142 failed to connect over ssl: javax.net.ssl.SSLHandshakeException: Received fatal alert: certificate_unknown
12:30:06.756 [vert.x-eventloop-thread-1] ERROR io.vertx.core.net.impl.NetServerImpl - Client from origin /10.244.1.100:46550 failed to connect over ssl: javax.net.ssl.SSLHandshakeException: Received fatal alert: certificate_unknown
12:30:07.876 [vert.x-eventloop-thread-1] ERROR io.vertx.core.net.impl.NetServerImpl - Client from origin /10.244.1.102:40706 failed to connect over ssl: javax.net.ssl.SSLHandshakeException: Received fatal alert: certificate_unknown
12:30:08.315 [vert.x-eventloop-thread-1] DEBUG o.e.h.client.impl.HonoConnectionImpl - starting attempt [#258] to connect to server [dt-service-device-registry:5671, role: Device Registration]
12:30:08.315 [vert.x-eventloop-thread-1] DEBUG o.e.h.c.impl.ConnectionFactoryImpl - OpenSSL [available: false, supports KeyManagerFactory: false]
12:30:08.315 [vert.x-eventloop-thread-1] DEBUG o.e.h.c.impl.ConnectionFactoryImpl - using JDK's default SSL engine
12:30:08.315 [vert.x-eventloop-thread-1] DEBUG o.e.h.c.impl.ConnectionFactoryImpl - enabling secure protocol [TLSv1.3]
12:30:08.315 [vert.x-eventloop-thread-1] DEBUG o.e.h.c.impl.ConnectionFactoryImpl - enabling secure protocol [TLSv1.2]
12:30:08.315 [vert.x-eventloop-thread-1] DEBUG o.e.h.c.impl.ConnectionFactoryImpl - connecting to AMQP 1.0 container [amqps://dt-service-device-registry:5671, role: Device Registration]
12:30:08.339 [vert.x-eventloop-thread-1] DEBUG o.e.h.c.impl.ConnectionFactoryImpl - can't connect to AMQP 1.0 container [amqps://dt-service-device-registry:5671, role: Device Registration]: Failed to create SSL connection
12:30:08.339 [vert.x-eventloop-thread-1] WARN  o.e.h.client.impl.HonoConnectionImpl - attempt [#258] to connect to server [dt-service-device-registry:5671, role: Device Registration] failed
javax.net.ssl.SSLHandshakeException: Failed to create SSL connection

The kubectl logs dt-adapter-amqp-vertx-74d69cbc44-7kmdq -n $NS output:

12:19:36.686 [vert.x-eventloop-thread-0] DEBUG o.e.h.client.impl.HonoConnectionImpl - starting attempt [#19] to connect to server [dt-service-device-registry:5671, role: Credentials]
12:19:36.686 [vert.x-eventloop-thread-0] DEBUG o.e.h.c.impl.ConnectionFactoryImpl - OpenSSL [available: false, supports KeyManagerFactory: false]
12:19:36.686 [vert.x-eventloop-thread-0] DEBUG o.e.h.c.impl.ConnectionFactoryImpl - using JDK's default SSL engine
12:19:36.686 [vert.x-eventloop-thread-0] DEBUG o.e.h.c.impl.ConnectionFactoryImpl - enabling secure protocol [TLSv1.3]
12:19:36.686 [vert.x-eventloop-thread-0] DEBUG o.e.h.c.impl.ConnectionFactoryImpl - enabling secure protocol [TLSv1.2]
12:19:36.686 [vert.x-eventloop-thread-0] DEBUG o.e.h.c.impl.ConnectionFactoryImpl - connecting to AMQP 1.0 container [amqps://dt-service-device-registry:5671, role: Credentials]
12:19:36.711 [vert.x-eventloop-thread-0] DEBUG o.e.h.c.impl.ConnectionFactoryImpl - can't connect to AMQP 1.0 container [amqps://dt-service-device-registry:5671, role: Credentials]: Failed to create SSL connection
12:19:36.712 [vert.x-eventloop-thread-0] WARN  o.e.h.client.impl.HonoConnectionImpl - attempt [#19] to connect to server [dt-service-device-registry:5671, role: Credentials] failed
javax.net.ssl.SSLHandshakeException: Failed to create SSL connection

The kubectl version output is as follows:

Client Version: version.Info{Major:"1", Minor:"19", GitVersion:"v1.19.3", GitCommit:"1e11e4a2108024935ecfcb2912226cedeafd99df", GitTreeState:"clean", BuildDate:"2020-10-14T12:50:19Z", GoVersion:"go1.15.2", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"19", GitVersion:"v1.19.16", GitCommit:"e37e4ab4cc8dcda84f1344dda47a97bb1927d074", GitTreeState:"clean", BuildDate:"2021-10-27T16:20:18Z", GoVersion:"go1.15.15", Compiler:"gc", Platform:"linux/amd64"}

Thanks in advance!


问:
TextMate source.java comment block folding
How do I modify the java language definition bundle foldingStartMarker and foldingStopMarker entries to allow for folding of these types of comment blocks?

This is the comment style:

```
/**
 * This is a comment...
 * Yet another comment...
 */
```

I've tried this:

```
foldingStartMarker = '(\{\s*(//.*)?$|^\s*// \{\{\{|^\s*\/\*\*)';
foldingStopMarker = '^\s*(\}|// \}\}\}$|\*\/)';
```

I get the first match for '/**' characters, but I can't get it to find the StopMarker '*/'.

Thanks!

答: It's not ideal but I found that if you end your comment with **/ instead of */ in a C++ source file, it recognizes them for folding.</p>

OwnerDisplayName: Evan

ContentLicense: CC BY-SA 2.5

Body:
How do I modify the java language definition bundle foldingStartMarker and foldingStopMarker entries to allow for folding of these types of comment blocks?

This is the comment style:

/**
 * This is a comment...
 * Yet another comment...
 */

I've tried this:

foldingStartMarker = '(\{\s*(//.*)?$|^\s*// \{\{\{|^\s*\/\*\*)';
foldingStopMarker = '^\s*(\}|// \}\}\}$|\*\/)';

I get the first match for '/**' characters, but I can't get it to find the StopMarker '*/'.

Thanks!


问:
Multiple time allocation and release
I am creating a quiz app for iPhone/iPad(universal app).It is working fine on simulator but on real device there are some problem i am facing..

I am creating UILabels and UIButtons programmatically and i am using them so many times for displaying questions and answers one by one.

problem is when i reach around question 20 to 22 the application crashes. I don't know why. there is no memory leak i found. I release all the labels and buttons at the -dealloc function.

may be it happens because 22 questions takes some memory and not release till dealloc function call.

What i want is , Is there any way to release labels and buttons after every question and then it will allocate again? or any way in which i can use less memory for allocation labels and buttons??

I am using this code :

```<code>//lbl ref to btn1
ans1 = [[[UILabel alloc] initWithFrame:CGRectMake(36, 292, 697, 100)] autorelease];
ans1.numberOfLines = 0;
ans1.font = [UIFont systemFontOfSize:26];
ans1.text = [theQuiz objectAtIndex:row+1];
ans1.lineBreakMode = UILineBreakModeWordWrap;
[ans1 sizeToFit];
//[self.view addSubview:ans1];
//lbl ref to btn2
ans2 = [[[UILabel alloc] initWithFrame:CGRectMake(36, 312 + ans1.frame.size.height , 697, 100)] autorelease];
ans2.numberOfLines = 0;
ans2.font = [UIFont systemFontOfSize:26];
ans2.text = [theQuiz objectAtIndex:row+2];
ans2.lineBreakMode = UILineBreakModeWordWrap;
[ans2 sizeToFit];
// [self.view addSubview:ans2];
//lbl ref to btn3
ans3 = [[[UILabel alloc] initWithFrame:CGRectMake(36 ,332 + ans1.frame.size.height + ans2.frame.size.height , 697 , 100)] autorelease];
ans3.numberOfLines = 0;
ans3.font = [UIFont systemFontOfSize:26];
ans3.text = [theQuiz objectAtIndex:row+3] ;
ans3.lineBreakMode = UILineBreakModeWordWrap;
[ans3 sizeToFit];
// [self.view addSubview:ans3];
//lbl ref to btn4
ans4 = [[[UILabel alloc] initWithFrame:CGRectMake(36, 352 + ans1.frame.size.height + ans2.frame.size.height + ans3.frame.size.height, 697, 100)] autorelease];
ans4.numberOfLines = 0;
ans4.font = [UIFont systemFontOfSize:26];
ans4.text = [theQuiz objectAtIndex:row+4];
ans4.lineBreakMode = UILineBreakModeWordWrap;
[ans4 sizeToFit];
// [self.view addSubview:ans4];

rightAnswer = [[theQuiz objectAtIndex:row+5] intValue];

Question = [[[UILabel alloc] initWithFrame:CGRectMake(22, 130, 725, 160)] autorelease];
Question.numberOfLines = 0;
//Question.font = [UIFont systemFontOfSize:27];
Question.text = [NSString stringWithFormat:@"%@" ,selected1];
Question.lineBreakMode = UILineBreakModeWordWrap;
[Question setFont:[UIFont fontWithName:@"Futura" size:26]];
Question.backgroundColor = [UIColor clearColor];
[Question sizeToFit];
[self.view addSubview:Question];

//For 1st Option.
button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self
           action:@selector(buttonOne)
 forControlEvents:UIControlEventTouchDown];
button.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button.titleLabel.font = [UIFont systemFontOfSize:24];
[button setTitle:[theQuiz objectAtIndex:row+1] forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button.frame = CGRectMake(34, 200 + Question.frame.size.height , 700, ans1.frame.size.height + 20) ;
[self.view addSubview:button];
button.layer.borderWidth = 3;
button.layer.borderColor = [[UIColor purpleColor ] CGColor];
button.layer.cornerRadius = 10.0;
[button setBackgroundImage:[UIImage imageNamed:@"buttun.png"] forState:UIControlStateNormal];
button.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);

//For 2nd Option.
button2 = [UIButton buttonWithType:UIButtonTypeCustom];
[button2 addTarget:self
            action:@selector(buttonTwo)
  forControlEvents:UIControlEventTouchDown];
[button2 setTitle:[theQuiz objectAtIndex:row+2] forState:UIControlStateNormal];
[button2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button2.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button2.titleLabel.font = [UIFont systemFontOfSize:24];
button2.frame = CGRectMake(34, 230 + Question.frame.size.height + button.frame.size.height , 700, ans2.frame.size.height + 20);
button2.layer.borderWidth = 3;
button2.layer.borderColor = [[UIColor darkGrayColor ] CGColor];
button2.layer.cornerRadius = 10.0;
[self.view addSubview:button2];
[button2 setBackgroundImage:[UIImage imageNamed:@"buttun2.png"] forState:UIControlStateNormal];
button2.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);

//For 3rd Option.
button3 = [UIButton buttonWithType:UIButtonTypeCustom];
[button3 addTarget:self
            action:@selector(buttonThree)
  forControlEvents:UIControlEventTouchDown];
[button3 setTitle:[theQuiz objectAtIndex:row+3] forState:UIControlStateNormal];
[button3 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button3.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button3.titleLabel.font = [UIFont systemFontOfSize:24];
button3.frame = CGRectMake(34, 260 + Question.frame.size.height + button.frame.size.height + button2.frame.size.height , 700, ans3.frame.size.height + 20);
button3.layer.borderWidth = 3;
button3.layer.borderColor = [[UIColor purpleColor ] CGColor];
button3.layer.cornerRadius = 10.0;

[self.view addSubview:button3];
[button3 setBackgroundImage:[UIImage imageNamed:@"buttun.png"] forState:UIControlStateNormal];
button3.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);

//For 4th Option.
button4 = [UIButton buttonWithType:UIButtonTypeCustom];
[button4 addTarget:self
            action:@selector(buttonFour)
  forControlEvents:UIControlEventTouchDown];
[button4 setTitle:[theQuiz objectAtIndex:row+4] forState:UIControlStateNormal];
[button4 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button4.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button4.titleLabel.font = [UIFont systemFontOfSize:24];
button4.frame = CGRectMake(34, 290 + Question.frame.size.height + button.frame.size.height + button2.frame.size.height + button3.frame.size.height , 700, ans4.frame.size.height + 20);
button4.layer.borderWidth = 3;
button4.layer.borderColor = [[UIColor darkGrayColor ] CGColor];
button4.layer.cornerRadius = 10.0;
[self.view addSubview:button4];
[button4 setBackgroundImage:[UIImage imageNamed:@"buttun2.png"] forState:UIControlStateNormal];
button4.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);

NSString *strright = [theQuiz objectAtIndex:row+7];
//NSString *strtext = [[NSString alloc] initWithFormat:@"%@" , strright];

rightans = [[[UILabel alloc] initWithFrame:CGRectMake(50, 330, 650, 150)]autorelease];
rightans.numberOfLines = 0;
rightans.text = [NSString stringWithFormat:@"%@" , strright];
rightans.backgroundColor = [UIColor clearColor];
rightans.font = [UIFont systemFontOfSize:26];
[self.view addSubview:rightans];
[rightans sizeToFit];
[rightans setHidden:YES];

//Description.
NSString *des = [theQuiz objectAtIndex:row+6];
//  NSString *destext = [[NSString alloc] initWithFormat:@"\n> Explanation :\n%@\n\n" , des];

Description = [[[UILabel alloc] initWithFrame:CGRectMake(40, 400 + rightans.frame.size.height , 690, 150)] autorelease];
Description.numberOfLines = 0;
// Description.font = [UIFont systemFontOfSize:13.5];
Description.text = [NSString stringWithFormat:@"\n> Explanation :\n%@\n\n" , des];
[Description setFont:[UIFont fontWithName:@"Futura" size:26]];
Description.lineBreakMode = UILineBreakModeWordWrap;
Description.backgroundColor = [UIColor clearColor];
[Description sizeToFit];
[self.view addSubview:Description];
[Description setHidden:YES];

ContainerView = [[UIView alloc] initWithFrame:CGRectMake(30, 400 + rightans.frame.size.height , 700 ,Description.frame.size.height)];
ContainerView.backgroundColor = [UIColor clearColor];
ContainerView.layer.cornerRadius = 10.0;
ContainerView.layer.borderColor = [[UIColor grayColor] CGColor];
ContainerView.layer.borderWidth = 3;
// [ContainerView addSubview:Description];
[self.view addSubview:ContainerView];
[ContainerView setHidden:YES];
</code>```

Any help??

Thank you.

答:
Firstly, you should release an object as soon as you add it to a view using [self.view addSubview: myObj]. When you add an object like this, its retain count is incremented by the parent view & you should release it (to decrement its retain count) to allow its garbage collection. Your code should be like-

```<code>[self.view addSubview: myObj];
[myObj release];
</code>```

Secondly, do you have the crash log?

HTH,

Akshay

Title: Multiple time allocation and release

Body:
I am creating a quiz app for iPhone/iPad(universal app).It is working fine on simulator but on real device there are some problem i am facing..

I am creating UILabels and UIButtons programmatically and i am using them so many times for displaying questions and answers one by one.

problem is when i reach around question 20 to 22 the application crashes. I don't know why. there is no memory leak i found. I release all the labels and buttons at the -dealloc function.

may be it happens because 22 questions takes some memory and not release till dealloc function call.

What i want is , Is there any way to release labels and buttons after every question and then it will allocate again? or any way in which i can use less memory for allocation labels and buttons??

I am using this code :

//lbl ref to btn1
ans1 = [[[UILabel alloc] initWithFrame:CGRectMake(36, 292, 697, 100)] autorelease];
ans1.numberOfLines = 0;
ans1.font = [UIFont systemFontOfSize:26];
ans1.text = [theQuiz objectAtIndex:row+1];
ans1.lineBreakMode = UILineBreakModeWordWrap;
[ans1 sizeToFit];
//[self.view addSubview:ans1];
//lbl ref to btn2
ans2 = [[[UILabel alloc] initWithFrame:CGRectMake(36, 312 + ans1.frame.size.height , 697, 100)] autorelease];
ans2.numberOfLines = 0;
ans2.font = [UIFont systemFontOfSize:26];
ans2.text = [theQuiz objectAtIndex:row+2];
ans2.lineBreakMode = UILineBreakModeWordWrap;
[ans2 sizeToFit];
// [self.view addSubview:ans2];
//lbl ref to btn3
ans3 = [[[UILabel alloc] initWithFrame:CGRectMake(36 ,332 + ans1.frame.size.height + ans2.frame.size.height , 697 , 100)] autorelease];
ans3.numberOfLines = 0;
ans3.font = [UIFont systemFontOfSize:26];
ans3.text = [theQuiz objectAtIndex:row+3] ;
ans3.lineBreakMode = UILineBreakModeWordWrap;
[ans3 sizeToFit];
// [self.view addSubview:ans3];
//lbl ref to btn4
ans4 = [[[UILabel alloc] initWithFrame:CGRectMake(36, 352 + ans1.frame.size.height + ans2.frame.size.height + ans3.frame.size.height, 697, 100)] autorelease];
ans4.numberOfLines = 0;
ans4.font = [UIFont systemFontOfSize:26];
ans4.text = [theQuiz objectAtIndex:row+4];
ans4.lineBreakMode = UILineBreakModeWordWrap;
[ans4 sizeToFit];
// [self.view addSubview:ans4];

rightAnswer = [[theQuiz objectAtIndex:row+5] intValue];

Question = [[[UILabel alloc] initWithFrame:CGRectMake(22, 130, 725, 160)] autorelease];
Question.numberOfLines = 0;
//Question.font = [UIFont systemFontOfSize:27];
Question.text = [NSString stringWithFormat:@"%@" ,selected1];
Question.lineBreakMode = UILineBreakModeWordWrap;
[Question setFont:[UIFont fontWithName:@"Futura" size:26]];
Question.backgroundColor = [UIColor clearColor];
[Question sizeToFit];
[self.view addSubview:Question];

//For 1st Option.
button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self
           action:@selector(buttonOne)
 forControlEvents:UIControlEventTouchDown];
button.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button.titleLabel.font = [UIFont systemFontOfSize:24];
[button setTitle:[theQuiz objectAtIndex:row+1] forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button.frame = CGRectMake(34, 200 + Question.frame.size.height , 700, ans1.frame.size.height + 20) ;
[self.view addSubview:button];
button.layer.borderWidth = 3;
button.layer.borderColor = [[UIColor purpleColor ] CGColor];
button.layer.cornerRadius = 10.0;
[button setBackgroundImage:[UIImage imageNamed:@"buttun.png"] forState:UIControlStateNormal];
button.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);

//For 2nd Option.
button2 = [UIButton buttonWithType:UIButtonTypeCustom];
[button2 addTarget:self
            action:@selector(buttonTwo)
  forControlEvents:UIControlEventTouchDown];
[button2 setTitle:[theQuiz objectAtIndex:row+2] forState:UIControlStateNormal];
[button2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button2.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button2.titleLabel.font = [UIFont systemFontOfSize:24];
button2.frame = CGRectMake(34, 230 + Question.frame.size.height + button.frame.size.height , 700, ans2.frame.size.height + 20);
button2.layer.borderWidth = 3;
button2.layer.borderColor = [[UIColor darkGrayColor ] CGColor];
button2.layer.cornerRadius = 10.0;
[self.view addSubview:button2];
[button2 setBackgroundImage:[UIImage imageNamed:@"buttun2.png"] forState:UIControlStateNormal];
button2.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);

//For 3rd Option.
button3 = [UIButton buttonWithType:UIButtonTypeCustom];
[button3 addTarget:self
            action:@selector(buttonThree)
  forControlEvents:UIControlEventTouchDown];
[button3 setTitle:[theQuiz objectAtIndex:row+3] forState:UIControlStateNormal];
[button3 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button3.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button3.titleLabel.font = [UIFont systemFontOfSize:24];
button3.frame = CGRectMake(34, 260 + Question.frame.size.height + button.frame.size.height + button2.frame.size.height , 700, ans3.frame.size.height + 20);
button3.layer.borderWidth = 3;
button3.layer.borderColor = [[UIColor purpleColor ] CGColor];
button3.layer.cornerRadius = 10.0;

[self.view addSubview:button3];
[button3 setBackgroundImage:[UIImage imageNamed:@"buttun.png"] forState:UIControlStateNormal];
button3.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);

//For 4th Option.
button4 = [UIButton buttonWithType:UIButtonTypeCustom];
[button4 addTarget:self
            action:@selector(buttonFour)
  forControlEvents:UIControlEventTouchDown];
[button4 setTitle:[theQuiz objectAtIndex:row+4] forState:UIControlStateNormal];
[button4 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button4.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button4.titleLabel.font = [UIFont systemFontOfSize:24];
button4.frame = CGRectMake(34, 290 + Question.frame.size.height + button.frame.size.height + button2.frame.size.height + button3.frame.size.height , 700, ans4.frame.size.height + 20);
button4.layer.borderWidth = 3;
button4.layer.borderColor = [[UIColor darkGrayColor ] CGColor];
button4.layer.cornerRadius = 10.0;
[self.view addSubview:button4];
[button4 setBackgroundImage:[UIImage imageNamed:@"buttun2.png"] forState:UIControlStateNormal];
button4.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);

NSString *strright = [theQuiz objectAtIndex:row+7];
//NSString *strtext = [[NSString alloc] initWithFormat:@"%@" , strright];

rightans = [[[UILabel alloc] initWithFrame:CGRectMake(50, 330, 650, 150)]autorelease];
rightans.numberOfLines = 0;
rightans.text = [NSString stringWithFormat:@"%@" , strright];
rightans.backgroundColor = [UIColor clearColor];
rightans.font = [UIFont systemFontOfSize:26];
[self.view addSubview:rightans];
[rightans sizeToFit];
[rightans setHidden:YES];

//Description.
NSString *des = [theQuiz objectAtIndex:row+6];
//  NSString *destext = [[NSString alloc] initWithFormat:@"\n> Explanation :\n%@\n\n" , des];

Description = [[[UILabel alloc] initWithFrame:CGRectMake(40, 400 + rightans.frame.size.height , 690, 150)] autorelease];
Description.numberOfLines = 0;
// Description.font = [UIFont systemFontOfSize:13.5];
Description.text = [NSString stringWithFormat:@"\n> Explanation :\n%@\n\n" , des];
[Description setFont:[UIFont fontWithName:@"Futura" size:26]];
Description.lineBreakMode = UILineBreakModeWordWrap;
Description.backgroundColor = [UIColor clearColor];
[Description sizeToFit];
[self.view addSubview:Description];
[Description setHidden:YES];

ContainerView = [[UIView alloc] initWithFrame:CGRectMake(30, 400 + rightans.frame.size.height , 700 ,Description.frame.size.height)];
ContainerView.backgroundColor = [UIColor clearColor];
ContainerView.layer.cornerRadius = 10.0;
ContainerView.layer.borderColor = [[UIColor grayColor] CGColor];
ContainerView.layer.borderWidth = 3;
// [ContainerView addSubview:Description];
[self.view addSubview:ContainerView];
[ContainerView setHidden:YES];

Any help??

Thank you.

Body:
Firstly, you should release an object as soon as you add it to a view using [self.view addSubview: myObj]. When you add an object like this, its retain count is incremented by the parent view & you should release it (to decrement its retain count) to allow its garbage collection. Your code should be like-

[self.view addSubview: myObj];
[myObj release];

Secondly, do you have the crash log?

HTH,

Akshay


问:
Writing a formula program with a dataset
I am trying to make a simple formula calculator in Python as a personal project because all of the Pokemon EXP gain calculators are outdated.

```<code>p = input("Enter the defeated Pokemon's species number: ")
le = input("Level of the defeated Pokemon: ")
lp = input("Level of the victorious Pokemon: ")
f = input("Was the Pokemon obtained from a trade? (Y/N) ");
p = int(p)
le = int(le)
lp = int(lp)
f = int(f1)

p * le
le * lp
lp * f

Y = 1.2
N = 1

n1 = 64
n2 = 142
n3 = 263
n4 = 62
n5 = 142
n6 = 267
n7 = 63
</code>```

Error I get:

```<code>ValueError                                Traceback (most recent call last)
<ipython-input-34-3b00b90525d0> in <module>()
      6 le = int(le)
      7 lp = int(lp)
----> 8 f = int(f)
      9
     10 p * le

ValueError: invalid literal for int() with base 10: 'Y'
</code>```

I am having trouble defining the input to integers, and linking those integers to a dataset that contains the entire Pokedex. If someone could help me with this, it'd be much appreciated.

答:
It's because you're trying to call int() on a string. You are having the user enter either Y or N, and then trying to convert that to an int. From the code, it looks like you are trying to have f equal to 1.2 if the answer is Y, and equal to 1 if the answer is N. You can do this in one line with an if else statement:

p = input("Enter the defeated Pokemon's species number: ")
le = input("Level of the defeated Pokemon: ")
lp = input("Level of the victorious Pokemon: ")
f = input("Was the Pokemon obtained from a trade? (Y/N) ");
p = int(p)
le = int(le)
lp = int(lp)
f = 1.2 if f == "Y" else 1

p * le
le * lp
lp * f

Y = 1.2
N = 1

n1 = 64
n2 = 142
n3 = 263
n4 = 62
n5 = 142
n6 = 267
n7 = 63
```

Body:
I am trying to make a simple formula calculator in Python as a personal project because all of the Pokemon EXP gain calculators are outdated.

p = input("Enter the defeated Pokemon's species number: ")
le = input("Level of the defeated Pokemon: ")
lp = input("Level of the victorious Pokemon: ")
f = input("Was the Pokemon obtained from a trade? (Y/N) ");
p = int(p)
le = int(le)
lp = int(lp)
f = int(f1)

p * le
le * lp
lp * f

Y = 1.2
N = 1

n1 = 64
n2 = 142
n3 = 263
n4 = 62
n5 = 142
n6 = 267
n7 = 63

Error I get:

ValueError                                Traceback (most recent call last)
<ipython-input-34-3b00b90525d0> in <module>()
      6 le = int(le)
      7 lp = int(lp)
----> 8 f = int(f)
      9
     10 p * le

ValueError: invalid literal for int() with base 10: 'Y'

I am having trouble defining the input to integers, and linking those integers to a dataset that contains the entire Pokedex. If someone could help me with this, it'd be much appreciated.