问:
VBA copy values from one array and store them into another
I am hoping to find help with this current VBA problem. I have looked throughout Stack Overflow and other Google searches, but can't seem to find what I'm looking for.

Essentially, I have a user pasted value on my page which I am delimiting on a comma, and then storing that into an array. What I am aiming to do is then loop through that array and eliminate any extra spaces, and then also delete any values that AREN'T a number.

Copy user values

Store into an array

Erase whitespace

So far, I have not been able to:

Copy items that ARE a number to new array

Currently, my code looks like:

```<code>Sub grabText()

' This macro was written as a test macro to grab and filter data entered in a textbox

    Application.ScreenUpdating = False

    Dim enteredValue As String ' Value taken from page
    Dim vals() As String ' Array once it is split
    Dim goodvals() As String 'Formatted array
    Dim i As Integer 'Index

    enteredValue = ActiveSheet.myTxt.Text
   ' MsgBox enteredValue

    vals() = Split(enteredValue, ",")

    lastitem = UBound(vals)
   ' MsgBox lastitem

    'Formats array
    For i = LBound(vals) To UBound(vals)
        i = TRIM(vals(i))
        '
        '   If (ISNUMBER(vals(i)) == TRUE) Then
        '       enter i into goodvals()
        '
    Next i

    Application.ScreenUpdating = True
</code>```

Any help or advice would be greatly appreciated. I was thinking about ways to do this in other languages (Java, Python) and I was thinking about Linked-Lists.

Thanks in advance!

答:
Some issues:

Don't assign the result of Split to vals(), but to vals

Don't re-use the variable i for the result of the Trim. It is better to use a separate variable for that, which you can then type as a String

You can capture the desired result if you

First reserve enough room for your target array: it can never be longer than the Split result, so use that as the initial size

Use a separate index variable for referencing the target array index, and only increment it when you have stored a number in it

Finally reduce the size of the target array to the size that was actually used

Code:

```<code>Dim enteredValue As String ' Value taken from page
Dim vals() As String ' Array once it is split
Dim goodvals() As String  'Formatted array
Dim i As Long 'Index in vals
Dim j As Long 'Index in goodvals
Dim s As String 'Individual string

enteredValue = ActiveSheet.myTxt.Text

vals = Split(enteredValue, ",")
' Reserve as many entries in the target array
ReDim goodvals(UBound(vals))

j = LBound(goodvals)
For i = LBound(vals) To UBound(vals)
    s = Trim(vals(i))
    If IsNumeric(s) Then
        goodvals(j) = CDbl(s)
        MsgBox goodvals(j)
        j = j + 1
    End If
Next

' Shorten the array size to the part that is used
If j Then
    ReDim Preserve goodvals(j - 1)
Else ' There were no numericals at all, so erase the array:
    Erase goodvals
End If
</code>```

Body:
I am hoping to find help with this current VBA problem. I have looked throughout Stack Overflow and other Google searches, but can't seem to find what I'm looking for.

Essentially, I have a user pasted value on my page which I am delimiting on a comma, and then storing that into an array. What I am aiming to do is then loop through that array and eliminate any extra spaces, and then also delete any values that AREN'T a number.

Copy user values

Store into an array

Erase whitespace

So far, I have not been able to:

Copy items that ARE a number to new array

Currently, my code looks like:

Sub grabText()

' This macro was written as a test macro to grab and filter data entered in a textbox

    Application.ScreenUpdating = False

    Dim enteredValue As String ' Value taken from page
    Dim vals() As String ' Array once it is split
    Dim goodvals() As String 'Formatted array
    Dim i As Integer 'Index

    enteredValue = ActiveSheet.myTxt.Text
   ' MsgBox enteredValue

    vals() = Split(enteredValue, ",")

    lastitem = UBound(vals)
   ' MsgBox lastitem

    'Formats array
    For i = LBound(vals) To UBound(vals)
        i = TRIM(vals(i))
        '
        '   If (ISNUMBER(vals(i)) == TRUE) Then
        '       enter i into goodvals()
        '
    Next i

    Application.ScreenUpdating = True

Any help or advice would be greatly appreciated. I was thinking about ways to do this in other languages (Java, Python) and I was thinking about Linked-Lists.

Thanks in advance!

Body:
Some issues:

Don't assign the result of Split to vals(), but to vals

Don't re-use the variable i for the result of the Trim. It is better to use a separate variable for that, which you can then type as a String

You can capture the desired result if you

First reserve enough room for your target array: it can never be longer than the Split result, so use that as the initial size

Use a separate index variable for referencing the target array index, and only increment it when you have stored a number in it

Finally reduce the size of the target array to the size that was actually used

Code:

Dim enteredValue As String ' Value taken from page
Dim vals() As String ' Array once it is split
Dim goodvals() As String  'Formatted array
Dim i As Long 'Index in vals
Dim j As Long 'Index in goodvals
Dim s As String 'Individual string

enteredValue = ActiveSheet.myTxt.Text

vals = Split(enteredValue, ",")
' Reserve as many entries in the target array
ReDim goodvals(UBound(vals))

j = LBound(goodvals)
For i = LBound(vals) To UBound(vals)
    s = Trim(vals(i))
    If IsNumeric(s) Then
        goodvals(j) = CDbl(s)
        MsgBox goodvals(j)
        j = j + 1
    End If
Next

' Shorten the array size to the part that is used
If j Then
    ReDim Preserve goodvals(j - 1)
Else ' There were no numericals at all, so erase the array:
    Erase goodvals
End If


来源: stackexchange

问:
Treating 1D array (pointer) as 3D matrix at run time in C++
I receive some image data as unsigned char *image = load_image(…);

This data is a 3D matrix: x (char),y (char) and channel (RGB) (char).

How can I access each element as image[x][y][channel] by overloading []? E.g. row 999, column 10000, green channel: image[999][10000][1]

Clarifications:

I'd like to use C multi-dimensional array syntax: array[x][y][z], not array[x * height * channels + y * channels + z]

I can access a 1D array as a 2D array:

```<code>unsigned char (*imageMatrix)[height] = (unsigned char (*)[height])image
imageMatrix[x][y] = 100
</code>```

I already asked how to do it in pure C. Here I want to know how it can be better achieved in C++.

答:
How can I access each element as image[x][y][channel] by overloading []?

When you overload an array operator for the image class, it can only support the syntax image[x] in its interface.

In order to be able to support image[x][y], image[x] needs to return an object or a reference to an object that needs to support the array operator.

In order to be able to support image[x][y][z], image[x][y] needs to return an object or a reference to an object that needs to support the array operator.

Here's a sample program that demonstrates how it can be done.

Disclaimer Please note that this is not production ready code.

```<code>#include <iostream>
#include <cassert>

struct Image
{
   Image(unsigned int x,
         unsigned int y,
         unsigned int z) : x_(x), y_(y), z_(z), data(new unsigned char [x*y*z]) {}

   // Need appropriate copy constructor and destructor.

   // Helper classes to support the 3D array operator syntax.

   struct image_2
   {
      image_2(Image& im, unsigned i, unsigned j) : im_(im), i_(i), j_(j) {}
      unsigned char& operator[](unsigned k)
      {
         assert( k < im_.z_ );
         unsigned int index = i_*im_.y_*im_.z_ + j_*im_.z_ + k;
         return im_.data[index];
      }

      Image& im_;
      unsigned int i_;
      unsigned int j_;
   };

   struct image_1
   {
      image_1(Image& im, unsigned i) : im_(im), i_(i) {}

      image_2 operator[](unsigned int j)
      {
         assert( j < im_.y_ );
         return image_2(im_, i_, j);
      }

      Image& im_;
      unsigned int i_;
   };

   // The toplevel array operator
   image_1 operator[](unsigned i)
   {
      assert( i < x_ );
      return image_1(*this, i);
   }

   unsigned x_;
   unsigned y_;
   unsigned z_;
   unsigned char* data;
};

int main()
{
   unsigned int x = 5;
   unsigned int y = 5;
   unsigned int z = 3;
   Image im(5, 5, 3);

   for ( unsigned int i = 0; i < x; ++i )
   {
      for ( unsigned int j = 0; j < y; ++j )
      {
         for ( unsigned int k = 0; k < z; ++k )
         {
            // Set some arbitrary value
            im[i][j][k] = (i+1) + (j+1)*5 + (k+1)*5;

            // Get the value
            std::cout << (int)im[i][j][k] << " ";
         }
         std::cout << std::endl;
      }
   }
}
</code>```

Output:

11 16 21
16 21 26
21 26 31
26 31 36
31 36 41
12 17 22
17 22 27
22 27 32
27 32 37
32 37 42
13 18 23
18 23 28
23 28 33
28 33 38
33 38 43
14 19 24
19 24 29
24 29 34
29 34 39
34 39 44
15 20 25
20 25 30
25 30 35
30 35 40
35 40 45
```

ContentLicense: CC BY-SA 3.0

Body:
I receive some image data as unsigned char *image = load_image(…);

This data is a 3D matrix: x (char),y (char) and channel (RGB) (char).

How can I access each element as image[x][y][channel] by overloading []? E.g. row 999, column 10000, green channel: image[999][10000][1]

Clarifications:

I'd like to use C multi-dimensional array syntax: array[x][y][z], not array[x * height * channels + y * channels + z]

I can access a 1D array as a 2D array:

unsigned char (*imageMatrix)[height] = (unsigned char (*)[height])image
imageMatrix[x][y] = 100

I already asked how to do it in pure C. Here I want to know how it can be better achieved in C++.

Body:
How can I access each element as image[x][y][channel] by overloading []?

When you overload an array operator for the image class, it can only support the syntax image[x] in its interface.

In order to be able to support image[x][y], image[x] needs to return an object or a reference to an object that needs to support the array operator.

In order to be able to support image[x][y][z], image[x][y] needs to return an object or a reference to an object that needs to support the array operator.

Here's a sample program that demonstrates how it can be done.

Disclaimer Please note that this is not production ready code.

#include <iostream>
#include <cassert>

struct Image
{
   Image(unsigned int x,
         unsigned int y,
         unsigned int z) : x_(x), y_(y), z_(z), data(new unsigned char [x*y*z]) {}

   // Need appropriate copy constructor and destructor.

   // Helper classes to support the 3D array operator syntax.

   struct image_2
   {
      image_2(Image& im, unsigned i, unsigned j) : im_(im), i_(i), j_(j) {}
      unsigned char& operator[](unsigned k)
      {
         assert( k < im_.z_ );
         unsigned int index = i_*im_.y_*im_.z_ + j_*im_.z_ + k;
         return im_.data[index];
      }

      Image& im_;
      unsigned int i_;
      unsigned int j_;
   };

   struct image_1
   {
      image_1(Image& im, unsigned i) : im_(im), i_(i) {}

      image_2 operator[](unsigned int j)
      {
         assert( j < im_.y_ );
         return image_2(im_, i_, j);
      }

      Image& im_;
      unsigned int i_;
   };

   // The toplevel array operator
   image_1 operator[](unsigned i)
   {
      assert( i < x_ );
      return image_1(*this, i);
   }

   unsigned x_;
   unsigned y_;
   unsigned z_;
   unsigned char* data;
};

int main()
{
   unsigned int x = 5;
   unsigned int y = 5;
   unsigned int z = 3;
   Image im(5, 5, 3);

   for ( unsigned int i = 0; i < x; ++i )
   {
      for ( unsigned int j = 0; j < y; ++j )
      {
         for ( unsigned int k = 0; k < z; ++k )
         {
            // Set some arbitrary value
            im[i][j][k] = (i+1) + (j+1)*5 + (k+1)*5;

            // Get the value
            std::cout << (int)im[i][j][k] << " ";
         }
         std::cout << std::endl;
      }
   }
}

Output:

11 16 21
16 21 26
21 26 31
26 31 36
31 36 41
12 17 22
17 22 27
22 27 32
27 32 37
32 37 42
13 18 23
18 23 28
23 28 33
28 33 38
33 38 43
14 19 24
19 24 29
24 29 34
29 34 39
34 39 44
15 20 25
20 25 30
25 30 35
30 35 40
35 40 45


问:
Laravel: How to get custom sorted eloquent collection using whereIn method
I have an array of product ids against which I need to retrieve the model collection. The array is something like this:

```<code>$ids = array(9, 2, 16, 11, 8, 1, 18);
</code>```

Right now, I'm using the following line of code to get the collection.

```<code>$products = Product::whereIn('id', $ids)->get();
</code>```

But it sorts the products against their ids. such as: 1, 2, 8, 9, 11, 16, 18. What I need is the same order as in the $ids array i.e 9, 2, 16, 11, 8, 1, 18.

What should I do to get the same order as in the array?

答:
Use Field() function of mysql (If you are using mysql database) with DB::raw() of laravel something like

```<code>$products = Product::whereIn('id', $ids)
    ->orderBy(DB::raw("FIELD(id,".join(',',$ids).")"))
    ->get();
</code>```

Field() returns the index position of a comma-delimited list

Body:
I have an array of product ids against which I need to retrieve the model collection. The array is something like this:

$ids = array(9, 2, 16, 11, 8, 1, 18);

Right now, I'm using the following line of code to get the collection.

$products = Product::whereIn('id', $ids)->get();

But it sorts the products against their ids. such as: 1, 2, 8, 9, 11, 16, 18. What I need is the same order as in the $ids array i.e 9, 2, 16, 11, 8, 1, 18.

What should I do to get the same order as in the array?

Body:
Use Field() function of mysql (If you are using mysql database) with DB::raw() of laravel something like

$products = Product::whereIn('id', $ids)
    ->orderBy(DB::raw("FIELD(id,".join(',',$ids).")"))
    ->get();

Field() returns the index position of a comma-delimited list


问:
Change each json object key(fn) value with number multiplied with 2
Hello I want to change each json object key value. JSON -

```<code>abc='[{"fn": 1,"name":"raimonds"},{"fn": 2,"name":"john"}]'
</code>```

Now using some filter in jq -

```<code>res=$(echo "$abc" | jq 'map(if .fn then . + {"fn":22222} else . end)')
</code>```

Now if I'm echoing $res it retuns -

```<code>'[{"fn": 22222,"name":"raimonds"},{"fn": 22222,"name":"john"}]'
</code>```

I want to multiply each fn by 2 and output it like this -

```<code>abc='[{"fn": 22222,"name":"raimonds"},{"fn": 44444,"name":"john"}]'
</code>```

How can i do that? Thank you!

答:
Given:

```<code>res='[{"fn": 22222,"name":"raimonds"},{"fn": 22222,"name":"john"}]'
</code>```

As @chepner pointed out,
you could modify the object in a filter:

```<code>echo "$res" | jq '.[].fn *= 2'
</code>```

Output:

```<code>[
  {
    "fn": 44444,
    "name": "raimonds"
  },
  {
    "fn": 44444,
    "name": "john"
  }
]
</code>```

My original suggestion was to construct objects with the modified property,
which would quickly get tedious, and has no advantages whatsoever:

```<code>echo "$res" | jq '[ .[] | {fn: (.fn * 2), name: .name} ]'
</code>```

Body:
Hello I want to change each json object key value. JSON -

abc='[{"fn": 1,"name":"raimonds"},{"fn": 2,"name":"john"}]'

Now using some filter in jq -

res=$(echo "$abc" | jq 'map(if .fn then . + {"fn":22222} else . end)')

Now if I'm echoing $res it retuns -

'[{"fn": 22222,"name":"raimonds"},{"fn": 22222,"name":"john"}]'

I want to multiply each fn by 2 and output it like this -

abc='[{"fn": 22222,"name":"raimonds"},{"fn": 44444,"name":"john"}]'

How can i do that? Thank you!

Body:
Given:

res='[{"fn": 22222,"name":"raimonds"},{"fn": 22222,"name":"john"}]'

As @chepner pointed out,
you could modify the object in a filter:

echo "$res" | jq '.[].fn *= 2'

Output:

[
  {
    "fn": 44444,
    "name": "raimonds"
  },
  {
    "fn": 44444,
    "name": "john"
  }
]

My original suggestion was to construct objects with the modified property,
which would quickly get tedious, and has no advantages whatsoever:

echo "$res" | jq '[ .[] | {fn: (.fn * 2), name: .name} ]'


问:
Spring Amqp Hibernate vs Rabbit Transaction Manager
I have a spring-amqp consumer using a transactional SimpleMessageListenerContainer. The TransactionManager set on the container is a RabbitTransactionManager. My MessageListener calls a service method that has the @Transactional annotation on it. In spring I have a HibernateTransactionManager with the @Primary annotation on the bean declaration that I intend to be used for my repositories and services.

My Question

In the case described above, does the HibernateTransactionManager get used for the service method call that happens within my MessageListener?

Why I'm asking

I'm investigating a bug with our system where some data did not get persisted and I'm trying to rule out a faulty TransactionManager configuration.

How I would like it to work

I would prefer to have the message requeued if a database rollback occurs. Could I just remove the RabbitTransactionManager altogether and use the HibernateTransactionManager instead?

I'll be happy to provide my spring configuration if there is any confusion about what I'm asking.

答:
Right, if you have fully blown PlatformTransactionManager, you should use it for the Spring AMQP MessageListenerContainer as well.

Since RabbitMQ doesn't support transactions in its nature like JMS, the RabbitTransactionManager isn't not requirement and must be replaced by the existing transactional resource support.

The Spring AMQP components are participating in the transaction synchronization properly.

https://docs.spring.io/spring-amqp/docs/2.0.0.RELEASE/reference/html/_reference.html#_using_the_rabbittransactionmanager


问:
how to load data website in value input html
I am having this piece of code, to load data form PHP in hosting. Then I am displaying received data to value input :

```<code>$("#MerekDagang").load("http://jiyo-hotel.com/bpom/data.php?id=1&act=Get_MerekDagang").value;
</code>```

The question is how to load data and insert as a input value here:

```<code><input type='text' class='form-control' name='Merek_Dagang' placeholder='Merek Dagang' id='MerekDagang' value=''>
</code>```

答:
That's not the right way to use the .load method in jquery. It's trying to load the data result into that element tag (which is not a wrapping element, it's a singular input element).

You should use this instead:

```<code>$(document).ready(function(){
    $.get("http://jiyo-hotel.com/bpom/data.php?id=1&act=Get_MerekDagang",function(data){
        $("#MerekDagang").val(data);
    });
});
</code>```

This explicitly tells where that data should go (into the val of the element selected).

P.S.: I'm not sure why you would want to immediately load data in through ajax like this though... seems inefficient, where you could have put that data in during the php output build.

Body:
I am having this piece of code, to load data form PHP in hosting. Then I am displaying received data to value input :

$("#MerekDagang").load("http://jiyo-hotel.com/bpom/data.php?id=1&act=Get_MerekDagang").value;

The question is how to load data and insert as a input value here:

<input type='text' class='form-control' name='Merek_Dagang' placeholder='Merek Dagang' id='MerekDagang' value=''>

Body:
That's not the right way to use the .load method in jquery. It's trying to load the data result into that element tag (which is not a wrapping element, it's a singular input element).

You should use this instead:

$(document).ready(function(){
    $.get("http://jiyo-hotel.com/bpom/data.php?id=1&act=Get_MerekDagang",function(data){
        $("#MerekDagang").val(data);
    });
});

This explicitly tells where that data should go (into the val of the element selected).

P.S.: I'm not sure why you would want to immediately load data in through ajax like this though... seems inefficient, where you could have put that data in during the php output build.


问:
How to read character with scanf in C? Getting "spurious trailing ‘%’ in format [-Wformat=]"
When I try to compile I get the following warnings:

warning: spurious trailing ‘%’ in format [-Wformat=]

warning: too many arguments for format [-Wformat-extra-args]

Here's the bit that's causing problems:

char drop, sub;

printf("Please enter a character to be dropped.\n");

scanf(" c%", &drop);

printf("Please enter a character to be subbed.\n");

scanf(" c%", &sub);

Any and all help would be greatly appreciated!

答:
```<code>scanf("%c", &drop);//---> correct usage
</code>```

You are reading a character.

Passing the address of the character variable to the scanf function with proper format speicifier.

Body:
scanf("%c", &drop);//---> correct usage

You are reading a character.

Passing the address of the character variable to the scanf function with proper format speicifier.


问:
How to make footer stick to the bottom
I am having a problem with my footer. I am trying to force it to the bottom, but it always looks ugly.

Here is the code:

```<code><div id="footer">
<div class="container">
    <div class="row">
        <h3 class="footertext">About Us:</h3>
        <br>
          <div class="col-md-4">
            <center>
              <img src="http://oi60.tinypic.com/w8lycl.jpg" class="img-circle" alt="the-brains">
              <br>
              <h4 class="footertext">Programmer</h4>
              <p class="footertext">You can thank all the crazy programming here to this guy.<br>
            </center>
          </div>
          <div class="col-md-4">
            <center>
              <img src="http://oi60.tinypic.com/2z7enpc.jpg" class="img-circle" alt="...">
              <br>
              <h4 class="footertext">Artist</h4>
              <p class="footertext">All the images here are hand drawn by this man.<br>
            </center>
          </div>
          <div class="col-md-4">
            <center>
              <img src="http://oi61.tinypic.com/307n6ux.jpg" class="img-circle" alt="...">
              <br>
              <h4 class="footertext">Designer</h4>
              <p class="footertext">This pretty site and the copy it holds are all thanks to this guy.<br>
            </center>
          </div>
        </div>
        <div class="row">

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

I tried to use

```<code><div class="footer navbar-fixed-bottom">
</code>```

but in that case my text ,which is located over the footer, get overlapped by footer

Here is css I used:

```<code>    #footer {
padding-top: 100px
  position: absolute;
  bottom: 0;
  width: 100%;
  /* Sets the fixed height of the footer here */
  height: 280px;
  background:
  /* color overlay */
    linear-gradient(
      rgba(240, 212, 0, 0.45),
      rgba(0, 0, 0, 0.45)
    ),
    /* image to overlay */
    url(222.png);
}
.footertext {
  color: #ffffff;
}
</code>```

Here is what I mean by ugly. I did try to set html and body height as 100% in css

答:
I think you only have to change position: absolute; to position: relative; or position: fixed; for the div to stay at the bottom (depending on what behaviour you exactly expect).

Side note, don't use the tag  because it's now deprecated, use CSS instead (text-align: center).

Title: How to make footer stick to the bottom

Body:
I am having a problem with my footer. I am trying to force it to the bottom, but it always looks ugly.

Here is the code:

About Us:

Programmer

You can thank all the crazy programming here to this guy.

Artist

All the images here are hand drawn by this man.

Designer

This pretty site and the copy it holds are all thanks to this guy.

I tried to use

but in that case my text ,which is located over the footer, get overlapped by footer

Here is css I used:

    #footer {
padding-top: 100px
  position: absolute;
  bottom: 0;
  width: 100%;
  /* Sets the fixed height of the footer here */
  height: 280px;
  background:
  /* color overlay */
    linear-gradient(
      rgba(240, 212, 0, 0.45),
      rgba(0, 0, 0, 0.45)
    ),
    /* image to overlay */
    url(222.png);
}
.footertext {
  color: #ffffff;
}

Here is what I mean by ugly. I did try to set html and body height as 100% in css

Body:
I think you only have to change position: absolute; to position: relative; or position: fixed; for the div to stay at the bottom (depending on what behaviour you exactly expect).

Side note, don't use the tag <center> because it's now deprecated, use CSS instead (text-align: center).


问:
html button, the value="submit" is not showing up?
I am looking for the value="submit" to show up in the middle of the button.  I am not seeing any text, not sure why?    </p>

```<code><button type="button" class="button btn_big_blue" value="Submit"></button>

.button{
    display: block;
    width: 137px;
    height:    44px;
    text-align:center;
    line-height: 40px;
    font-size: 18px;
    font-weight: bold;
    text-decoration: none;
    color:#fff;
    border:none;
    cursor: pointer;
}

.button.btn_big_blue {
    background: url(/img/btn_big_blue.png) no-repeat;
    color: #fff;
}
</code>```

答:
The <button> tag doesn't use the value attribute.

You should either switch to an <input type="submit" value="..." /> or move the caption to the content of the tag.

ContentLicense: CC BY-SA 2.5

Body:
I am looking for the value="submit" to show up in the middle of the button.  I am not seeing any text, not sure why?

<button type="button" class="button btn_big_blue" value="Submit"></button>

.button{
    display: block;
    width: 137px;
    height:    44px;
    text-align:center;
    line-height: 40px;
    font-size: 18px;
    font-weight: bold;
    text-decoration: none;
    color:#fff;
    border:none;
    cursor: pointer;
}

.button.btn_big_blue {
    background: url(/img/btn_big_blue.png) no-repeat;
    color: #fff;
}


问:
Animating a view inside a collectionviewcell
I am a little stuck with animating a progressView (using this subclass: Linear Progress View).

Just a little bit of background so the code posted below makes sense. I have created a subclass of UICollectionViewCellwith some basic functions. Mainly the reason for this was to reduce boilerplate code. In my collection view I set the cell to my subclass and pass it the model object. All the data is shown correctly, however the progress view doesn't animate. I have tried things like viewWillDisplay on the collection view, but to no avail.

Any suggestions would be greatly appreciated. (Code below)

CollectionViewCell class:

```<code>import UIKit
import ChameleonFramework
import Material

class MacrocycleCell: Cell {

var macrocycle:Macrocycle? = nil {
    didSet{
        if let macro = macrocycle, let start = macrocycle?.start, let completion = macrocycle?.completion {

            title.text = macro.title
            let percentage = Date().calculatePercentageComplete(startDate: start, completionDate: completion)
            progress.setProgress(percentage, animated: true)

            let difference = Date.calculateDifferenceInMonthsAndDaysBetween(start: start, end: completion)
            if let monthDiff = difference.month, let dayDiff = difference.day {
                if monthDiff > 0 {
                    detail.text = monthDiff > 1 ? "\(monthDiff) months left" : "\(monthDiff) month left"
                }else{
                    detail.text = dayDiff > 1 ? "\(dayDiff) days left" : "\(dayDiff) day left"
                }
            }

        }

    }
}

let dropView:View = {
    let view = View()
    view.backgroundColor = .white
    view.translatesAutoresizingMaskIntoConstraints = false
    view.depthPreset = DepthPreset.depth2
    return view
}()

let title:UILabel = {
    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    label.textAlignment = .center
    label.font = UIFont.boldSystemFont(ofSize: 18)
    label.textColor = UIColor.flatBlack()
    return label
}()

let progress:LinearProgressView = {
    let progress = LinearProgressView()
    progress.isCornersRounded = true
    progress.barColor = UIColor.flatWhiteColorDark()
    progress.trackColor = UIColor.flatGreen()
    progress.barInset = 0
    progress.minimumValue = 0
    progress.maximumValue = 1
    progress.animationDuration = 1
    progress.translatesAutoresizingMaskIntoConstraints = false
    return progress
}()

let detail:UILabel = {
    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    label.textAlignment = .center
    label.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.light)
    label.textColor = UIColor.flatGray()
    return label
}()

override func drawView() {
    addSubview(dropView)
    dropView.addSubview(title)
    dropView.addSubview(progress)
    dropView.addSubview(detail)

    dropView.topAnchor.constraint(equalTo: topAnchor).isActive = true
    dropView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
    dropView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
    dropView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -2).isActive = true

    progress.centerXAnchor.constraint(equalTo: dropView.centerXAnchor).isActive = true
    progress.centerYAnchor.constraint(equalTo: dropView.centerYAnchor).isActive = true
    progress.heightAnchor.constraint(equalToConstant: 10).isActive = true
    progress.widthAnchor.constraint(equalTo: dropView.widthAnchor, multiplier: 0.8).isActive = true

    title.topAnchor.constraint(equalTo: dropView.topAnchor).isActive = true
    title.leftAnchor.constraint(equalTo: dropView.safeAreaLayoutGuide.leftAnchor).isActive = true
    title.rightAnchor.constraint(equalTo: dropView.safeAreaLayoutGuide.rightAnchor).isActive = true
    title.bottomAnchor.constraint(equalTo: progress.topAnchor, constant: 6).isActive = true

    detail.topAnchor.constraint(equalTo: progress.bottomAnchor, constant: 14).isActive = true
    detail.leftAnchor.constraint(equalTo: dropView.leftAnchor).isActive = true
    detail.rightAnchor.constraint(equalTo: dropView.rightAnchor).isActive = true
    detail.heightAnchor.constraint(equalToConstant: 14).isActive = true
}
}
</code>```

CollectionViewController Class:

```<code>import UIKit

private let reuseIdentifier = "Cell"

class MacrocycleController: UICollectionViewController, UICollectionViewDelegateFlowLayout {

var athlete:Athlete? = nil {
    didSet{
       self.title = athlete?.name

    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    collectionView?.backgroundColor = .flatWhiteColorDark()

    self.collectionView!.register(MacrocycleCell.self, forCellWithReuseIdentifier: reuseIdentifier)

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: UICollectionViewDataSource

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: collectionView.frame.width, height: 90)
}

override func numberOfSections(in collectionView: UICollectionView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of items
    return athlete?.macrocycles?.count ?? 0
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! MacrocycleCell
    cell.macrocycle = athlete?.macrocycles?[indexPath.item]

    return cell
}

}
</code>```

I am sure it is something simple, that I have forgotten to implement.

Thanks, you beautiful people!

答:
Here is another answer, which keeps all of the logic in the cell class and doesn't use the WillDisplayCell delegate method of the collection controller.

```<code>var progress: Float = 0.0
@IBOutlet var progressBar: LinearProgressView!
var drawnAtLeastOnce = false

func animateIfNeeded() {
    if progressBar.progress != self.progress {
        progressBar.setProgress(progress, animated: true)
    }
}
override func layoutSubviews() {
    super.layoutSubviews()
    if drawnAtLeastOnce {
        animateIfNeeded()
    }
}

override func draw(_ rect: CGRect) {
    super.draw(rect)
    if !drawnAtLeastOnce {
        drawnAtLeastOnce = true
        setNeedsLayout()
    }
}
</code>```

The key to this answer is detecting the end of the first drawing pass and suppressing animation until that time.

This works pretty well for the first screenful of cells. Cells that scroll into view may be pre-drawn, so you won't see animation on those cells. (at least that's what I observed when testing with a tableview).

Body:
I am a little stuck with animating a progressView (using this subclass: Linear Progress View).

Just a little bit of background so the code posted below makes sense. I have created a subclass of UICollectionViewCellwith some basic functions. Mainly the reason for this was to reduce boilerplate code. In my collection view I set the cell to my subclass and pass it the model object. All the data is shown correctly, however the progress view doesn't animate. I have tried things like viewWillDisplay on the collection view, but to no avail.

Any suggestions would be greatly appreciated. (Code below)

CollectionViewCell class:

import UIKit
import ChameleonFramework
import Material

class MacrocycleCell: Cell {

var macrocycle:Macrocycle? = nil {
    didSet{
        if let macro = macrocycle, let start = macrocycle?.start, let completion = macrocycle?.completion {

            title.text = macro.title
            let percentage = Date().calculatePercentageComplete(startDate: start, completionDate: completion)
            progress.setProgress(percentage, animated: true)

            let difference = Date.calculateDifferenceInMonthsAndDaysBetween(start: start, end: completion)
            if let monthDiff = difference.month, let dayDiff = difference.day {
                if monthDiff > 0 {
                    detail.text = monthDiff > 1 ? "\(monthDiff) months left" : "\(monthDiff) month left"
                }else{
                    detail.text = dayDiff > 1 ? "\(dayDiff) days left" : "\(dayDiff) day left"
                }
            }

        }

    }
}

let dropView:View = {
    let view = View()
    view.backgroundColor = .white
    view.translatesAutoresizingMaskIntoConstraints = false
    view.depthPreset = DepthPreset.depth2
    return view
}()

let title:UILabel = {
    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    label.textAlignment = .center
    label.font = UIFont.boldSystemFont(ofSize: 18)
    label.textColor = UIColor.flatBlack()
    return label
}()

let progress:LinearProgressView = {
    let progress = LinearProgressView()
    progress.isCornersRounded = true
    progress.barColor = UIColor.flatWhiteColorDark()
    progress.trackColor = UIColor.flatGreen()
    progress.barInset = 0
    progress.minimumValue = 0
    progress.maximumValue = 1
    progress.animationDuration = 1
    progress.translatesAutoresizingMaskIntoConstraints = false
    return progress
}()

let detail:UILabel = {
    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    label.textAlignment = .center
    label.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.light)
    label.textColor = UIColor.flatGray()
    return label
}()

override func drawView() {
    addSubview(dropView)
    dropView.addSubview(title)
    dropView.addSubview(progress)
    dropView.addSubview(detail)

    dropView.topAnchor.constraint(equalTo: topAnchor).isActive = true
    dropView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
    dropView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
    dropView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -2).isActive = true

    progress.centerXAnchor.constraint(equalTo: dropView.centerXAnchor).isActive = true
    progress.centerYAnchor.constraint(equalTo: dropView.centerYAnchor).isActive = true
    progress.heightAnchor.constraint(equalToConstant: 10).isActive = true
    progress.widthAnchor.constraint(equalTo: dropView.widthAnchor, multiplier: 0.8).isActive = true

    title.topAnchor.constraint(equalTo: dropView.topAnchor).isActive = true
    title.leftAnchor.constraint(equalTo: dropView.safeAreaLayoutGuide.leftAnchor).isActive = true
    title.rightAnchor.constraint(equalTo: dropView.safeAreaLayoutGuide.rightAnchor).isActive = true
    title.bottomAnchor.constraint(equalTo: progress.topAnchor, constant: 6).isActive = true

    detail.topAnchor.constraint(equalTo: progress.bottomAnchor, constant: 14).isActive = true
    detail.leftAnchor.constraint(equalTo: dropView.leftAnchor).isActive = true
    detail.rightAnchor.constraint(equalTo: dropView.rightAnchor).isActive = true
    detail.heightAnchor.constraint(equalToConstant: 14).isActive = true
}
}

CollectionViewController Class:

import UIKit

private let reuseIdentifier = "Cell"

class MacrocycleController: UICollectionViewController, UICollectionViewDelegateFlowLayout {

var athlete:Athlete? = nil {
    didSet{
       self.title = athlete?.name

    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    collectionView?.backgroundColor = .flatWhiteColorDark()

    self.collectionView!.register(MacrocycleCell.self, forCellWithReuseIdentifier: reuseIdentifier)

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: UICollectionViewDataSource

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: collectionView.frame.width, height: 90)
}

override func numberOfSections(in collectionView: UICollectionView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of items
    return athlete?.macrocycles?.count ?? 0
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! MacrocycleCell
    cell.macrocycle = athlete?.macrocycles?[indexPath.item]

    return cell
}

}

I am sure it is something simple, that I have forgotten to implement.

Thanks, you beautiful people!

Body:
Here is another answer, which keeps all of the logic in the cell class and doesn't use the WillDisplayCell delegate method of the collection controller.

var progress: Float = 0.0
@IBOutlet var progressBar: LinearProgressView!
var drawnAtLeastOnce = false

func animateIfNeeded() {
    if progressBar.progress != self.progress {
        progressBar.setProgress(progress, animated: true)
    }
}
override func layoutSubviews() {
    super.layoutSubviews()
    if drawnAtLeastOnce {
        animateIfNeeded()
    }
}

override func draw(_ rect: CGRect) {
    super.draw(rect)
    if !drawnAtLeastOnce {
        drawnAtLeastOnce = true
        setNeedsLayout()
    }
}

The key to this answer is detecting the end of the first drawing pass and suppressing animation until that time.

This works pretty well for the first screenful of cells. Cells that scroll into view may be pre-drawn, so you won't see animation on those cells. (at least that's what I observed when testing with a tableview).


问:
Background image displays wrong, don't know what to do
i'm pretty new to CSS but I made something in illustrator (web)and wanted to put this as background-image in css. I've put the image in a
 and CSS in I just put background-image: url(berg.jpg), i'm sure the url is correct, but it doesn't display anything. I've put height: 100% in css after that and it showed up but it was all zoomed in and only displays a small corner of the picture because of the zoom. How can I display this correctly? The image size is width: 1366px; height:768px.

Sorry if this is already asked but I couldn't seem to find it. Thx on advance.

答: You can try to put bakcground-size: cover; in your CSS code and this will ocupe all background of your div independent of width or height.


问:
Bootstrap 4 beta how to add image after text
I have an issue with adding an image in "menu" section at the last item "Kava so sebou" after the text. (the picture should be center vertically and the row should look like the other items above. Any suggestions? Thank you for your help. I just learn bootstrap and I'm a girl. (hilarious combination)

Custom css

.menu {
  padding: 70px 0px;
}
.menu .block > p {
  color: #9D9D9D;
  font-size: 16px;
  line-height: 26px;
  padding: 40px 133px 0;
  text-align: center;
}
.menu .block .pricing-list {
  padding-top: 5px;
}
.menu .block .pricing-list ul {
  list-style-type: none;
  padding: 0 0 30px;
  margin: 0;
}
.menu .block .pricing-list ul li {
  padding: 21px 0px;
}
.menu .block .pricing-list ul li .item .item-title {
  position: relative;
}
.menu .block .pricing-list ul li .item .item-title h2 {
  display: inline-block;
  position: relative;
  z-index: 99;
  background: #fff;
}
.menu .block .pricing-list ul li .item .item-title .border-bottom {
  position: absolute;
  top: 0;
  width: 100%;
  height: 1px;
  border: 1px dotted #C9C9C9;
  margin-top: 40px;
}
.menu .block .pricing-list ul li .item .item-title .border-bottom-coffee {
  position: absolute;
  top: 50px;
  width: 100%;
  height: 1px;
  border: 1px dotted #C9C9C9;
  margin-top: 30px;
}
.menu .block .pricing-list ul li .item .item-title span {
  float: right;
  color: #938463;
}
.menu .block .pricing-list ul li .item .item-title span {
  float: right;
  color: #938463;
}
.menu .block .pricing-list ul li .item .item-title img {
 padding-bottom: 20px;
}
.menu .block .pricing-list ul li .item p {
  padding: 12px 0 0px;
  color: #949494;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <!-- Start Menu list -->
    <section id="menu" class="menu">
     <div class="container">
            <div class="row">
                <div class="col-md-12">
                    <div class="block">
                        <div class="pricing-list">
                            <div class="title">
                             <div class="container">
                             <ul>
                                <li class="wow fadeInUp" data-wow-duration="300ms" data-wow-delay="1100ms" style="visibility: visible; animation-duration: 300ms; animation-delay: 1100ms; animation-name: fadeInUp;">
                                    <div class="item">
                                        <div class="item-title">
                                            <h2>Pivo 10 0.5L</h2>
                                            <div class="border-bottom"></div>
                                            <span>€ 1.20</span>
                                        </div>
                                        <p>Zlatý Bažant, Staropramen</p>
                                    </div>
                                </li>
                                <li class="wow fadeInUp" data-wow-duration="300ms" data-wow-delay="1200ms" style="visibility: visible; animation-duration: 300ms; animation-delay: 1200ms; animation-name: fadeInUp;">
                                    <div class="item">
                                        <div class="item-title">
                                            <h2>Káva so sebou </h2>
                                            <div class="border-bottom"></div>
                                            <span>€ 1.20</span>
                                        </div>
                                        <p>Štrbské Presso</p>
                                    </div>
                                </li>
                            </ul>
                        </div>
                    </div><!-- block close -->
                </div><!-- .col-md-12 close -->
            </div><!-- .row close -->
        </div><!-- .containe close -->
    </section><!-- #price close --></code>```

答:
You should read this part of bootstrap docs, it will be very helpful for tasks like this: http://getbootstrap.com/docs/4.0/layout/media-object/

In this case, you should set your container div class to media, cover your text to div with class media-body and add media-object to div with your image.

Then, you only need to make some changes in your css, and it will look perfect.

It is the fast-made code I've made:

```<code><div class="item">
        <div class="item-title media">
                <div class="media-body" style="white-space: nowrap;padding-top: 50px;">
                       <h2>Káva so sebou</h2>
                </div>
                <div class="media-object">
                       <img class="align-self-center mx-auto=" d-inline-block="" text-nowrap="" src="./images/coffee.jpg">
                </div>
                <div class="border-bottom-coffee" style="position:relative;"></div>
                <span>€ 1.20</span>
        </div>
</div>
</code>```

Body:
I have an issue with adding an image in "menu" section at the last item "Kava so sebou" after the text. (the picture should be center vertically and the row should look like the other items above. Any suggestions? Thank you for your help. I just learn bootstrap and I'm a girl. (hilarious combination)

Custom css

.menu {
  padding: 70px 0px;
}
.menu .block > p {
  color: #9D9D9D;
  font-size: 16px;
  line-height: 26px;
  padding: 40px 133px 0;
  text-align: center;
}
.menu .block .pricing-list {
  padding-top: 5px;
}
.menu .block .pricing-list ul {
  list-style-type: none;
  padding: 0 0 30px;
  margin: 0;
}
.menu .block .pricing-list ul li {
  padding: 21px 0px;
}
.menu .block .pricing-list ul li .item .item-title {
  position: relative;
}
.menu .block .pricing-list ul li .item .item-title h2 {
  display: inline-block;
  position: relative;
  z-index: 99;
  background: #fff;
}
.menu .block .pricing-list ul li .item .item-title .border-bottom {
  position: absolute;
  top: 0;
  width: 100%;
  height: 1px;
  border: 1px dotted #C9C9C9;
  margin-top: 40px;
}
.menu .block .pricing-list ul li .item .item-title .border-bottom-coffee {
  position: absolute;
  top: 50px;
  width: 100%;
  height: 1px;
  border: 1px dotted #C9C9C9;
  margin-top: 30px;
}
.menu .block .pricing-list ul li .item .item-title span {
  float: right;
  color: #938463;
}
.menu .block .pricing-list ul li .item .item-title span {
  float: right;
  color: #938463;
}
.menu .block .pricing-list ul li .item .item-title img {
 padding-bottom: 20px;
}
.menu .block .pricing-list ul li .item p {
  padding: 12px 0 0px;
  color: #949494;
}

Pivo 10 0.5L

                                            € 1.20

Zlatý Bažant, Staropramen

Káva so sebou

                                            € 1.20

Štrbské Presso

Body:
You should read this part of bootstrap docs, it will be very helpful for tasks like this: http://getbootstrap.com/docs/4.0/layout/media-object/

In this case, you should set your container div class to media, cover your text to div with class media-body and add media-object to div with your image.

Then, you only need to make some changes in your css, and it will look perfect.

It is the fast-made code I've made:

<div class="item">
        <div class="item-title media">
                <div class="media-body" style="white-space: nowrap;padding-top: 50px;">
                       <h2>Káva so sebou</h2>
                </div>
                <div class="media-object">
                       <img class="align-self-center mx-auto=" d-inline-block="" text-nowrap="" src="./images/coffee.jpg">
                </div>
                <div class="border-bottom-coffee" style="position:relative;"></div>
                <span>€ 1.20</span>
        </div>
</div>


问:
Mercurial: Indicating that a branch has passed testing?
I am working on establishing a workflow at my company if we were to migrate to DVCS (most likely Mercurial).  One of the things I would like to do is to have a repository for QA.  The idea being that each developer works on a branch and when they are done the branch is pushed to QA.  From there the test team can do their testing and report back any bugs.  Once the branch is fully tested and acceptable it will be pushed to a staging repository where the merge back to the mainline will happen before pushing to the central repository.

This can work quite easily if everyone just communicates the status of their work in some way, but I know this doesn't always happen as you would want it to.  What I am worried about is branches in the QA repo waiting around but nobody knows if it is waiting to be tested, currently being tested, waiting for fixes, waiting to be pushed to the staging area etc.  So what I am looking for are ideas of how a status can be added to a branch?  What would also be good would be to do it in a way that we could use hooks to also notify people of changes in the status.

Any ideas would be appreciated.

答: Joel Spolsky, one of the founders of this site, produces a program called FogBugz that is integrated with Mercurial and makes it easy to keep track of everyone's status.</p>


问:
How do you configure Gitlab CI dockers to test different requirements (Language env, database, etc.)?
I am creating an API that uses Python, Mongo, and Redis and I wanted to use Gitlab CI.

Do I have to build a Dockerfile with all these requirements? Or is there a way to just write some instructions in the .gitlab-ci.yml and call the different images in Dockerhub?

答:
Yes you should. Although this is not a Gitlab specific question (and thus answer) it is considered a best-practice to separate tasks and functions (in Docker terms; One concern per container). I don't want to call it a micro-service approach but you should consider splitting all processes.

Some fundamental concepts to help you:

The Twelve-Factor App (Splitting processes)

Best practices for writing Dockerfiles (One concern)

Since you mention Python and API I suppose your application is writen in Python and you use MongoDB and Redis as persistent data stores?

Take a look at the official Docker images and how to use them, this should make your life splitting concerns a lot easier:

MongoDB

Redis

There is also an official Python image to help you on your way. Just add your app code and get going!


问:
linux firewall rule - iptables –A INPUT rule that will accept any packet that comes in over ports 43,53 or 67
I need an linux firewall rule that will accomplish the following:  iptables –A INPUT rule that will accept any packet that comes in over ports 43,53 or 67.

I am new to this.  Do you have to have -p "protocol" before --dport 43,53,67 or can you take out the -p "protocol" and just have the --dport 43,53,67.  How would you have accept any packet that could come over multiple protocols?

答:
You have to use it for all protocols you want to allow

```<code>iptables -A INPUT -p tcp -m multiport --dports 43,53,67 -j ACCEPT
iptables -A INPUT -p udp -m multiport --dports 43,53,67 -j ACCEPT
</code>```

--dport is not a flag for general iptables rules. It's a flag for one of it's extended packet matching modules. These are loaded when you use -p protocol or -m. Unless you specify -m <protocol> or -p <protocol> with a specific protocol you can't use --dport

Body:
You have to use it for all protocols you want to allow

iptables -A INPUT -p tcp -m multiport --dports 43,53,67 -j ACCEPT
iptables -A INPUT -p udp -m multiport --dports 43,53,67 -j ACCEPT

--dport is not a flag for general iptables rules. It's a flag for one of it's extended packet matching modules. These are loaded when you use -p protocol or -m. Unless you specify -m <protocol> or -p <protocol> with a specific protocol you can't use --dport


问:
PHP Function to create div which will be called x amount of times
I am attempting to make an html element that contains x amount of other divs created by a function where x is dependent on the number of elements $allposts contains.

```<code><div id="postings">
    <?php
    foreach($allposts as $key => $value){
        createPost($key, $value);
    }
    ?>
 </div>
</code>```

This html and php code above is my attempt to create a "posting" for each item that is found in the $allposts array.

```<code><?php
    function createPost($author, $input)
    {
        $data = [];
        $i = 0;
        foreach($input as $key => $value){
            $data[$i] = $value;
            $i++;
        }
        echo "<div>
                <span class='post-title'>$data[0]</span>
                <span class='post-author'>$author</span>
                <span class='post-date'>$data[1]</span>
                <p class='post-desc'>$data[2]</span>
            </div>";
     }
?>
</code>```

This is the php document that contains the function createPost($author, $input).

The function works but it seems that each time the function is being called, the previous post is overridden leaving only one post visible which ends up being the last one in the array.

答:
Get the $data array declaration outside of foreach and the other change needs to be done is, do not use $i as key of $data array because everytime, it will be declared with 0 (zero) and so, all new values replace the previos one. So instead of using $i keep it $data[] so it will automatically add numeric indexes.

```<code><?php
    $data = [];    // I took it out of the loop.
    function createPost($author, $input)
    {
        foreach($input as $key => $value){
        $data[] = $value;
    }
    echo "<div>
                <span class='post-title'>$data[0]</span>
                <span class='post-author'>$author</span>
                <span class='post-date'>$data[1]</span>
                <p class='post-desc'>$data[2]</span>
           </div>";
     }
?>
</code>```

Body:
I am attempting to make an html element that contains x amount of other divs created by a function where x is dependent on the number of elements $allposts contains.

    <?php
    foreach($allposts as $key => $value){
        createPost($key, $value);
    }
    ?>

This html and php code above is my attempt to create a "posting" for each item that is found in the $allposts array.

<?php
    function createPost($author, $input)
    {
        $data = [];
        $i = 0;
        foreach($input as $key => $value){
            $data[$i] = $value;
            $i++;
        }
        echo "

                $data[0]
                $author
                $data[1]

$data[2]

";
     }
?>

This is the php document that contains the function createPost($author, $input).

The function works but it seems that each time the function is being called, the previous post is overridden leaving only one post visible which ends up being the last one in the array.

Body:
Get the $data array declaration outside of foreach and the other change needs to be done is, do not use $i as key of $data array because everytime, it will be declared with 0 (zero) and so, all new values replace the previos one. So instead of using $i keep it $data[] so it will automatically add numeric indexes.

<?php
    $data = [];    // I took it out of the loop.
    function createPost($author, $input)
    {
        foreach($input as $key => $value){
        $data[] = $value;
    }
    echo "<div>
                <span class='post-title'>$data[0]</span>
                <span class='post-author'>$author</span>
                <span class='post-date'>$data[1]</span>
                <p class='post-desc'>$data[2]</span>
           </div>";
     }
?>


问:
Jackson cannot access com.fasterxml.jackson.core.ObjectCodec
This question is a follow up to this one. I can't seem to be able to access the jackson library in the following code:

```<code>import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.ObjectWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ServerConfiguration {
    public String info = null;
    public String idlURL = null;
    public String idlContents = null;
    public List<ServerInfo> servers = new ArrayList<>();

    public final void clear() {
        info = null;
        idlURL = null;
        idlContents = null;
        if (servers != null)
            servers.clear();
    }

    private final static ObjectReader jsonReader;
    private final static ObjectWriter jsonWriter;

    static {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); // <== Error:(52, 15) java: cannot access com.fasterxml.jackson.core.JsonGenerator class file for com.fasterxml.jackson.core.JsonGenerator not found
        //mapper.configure(SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED, true);
        jsonWriter = mapper.writer();
        jsonReader = mapper.reader(ServerConfiguration.class);
    }

    public static ServerConfiguration fromJson(String json) throws IOException {
        return jsonReader.<ServerConfiguration>readValue(json); // <== Error:(59, 26) java: cannot access com.fasterxml.jackson.core.JsonProcessingException class file for com.fasterxml.jackson.core.JsonProcessingException not found
    }

    public String toJson() throws IOException {
        return jsonWriter.writeValueAsString(this);
    }

}
</code>```

eventhough the jar files are in the classpath(autocomplete shows the method declaration in Intellij).

What am I missing?

答:
I had also encountered the same problem, turns out, I had "jackson-core-asl.jar" instead of "jackson-core.jar"

So, check whether you have this jar-file in your classpath.
-> https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core

Body:
This question is a follow up to this one. I can't seem to be able to access the jackson library in the following code:

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.ObjectWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ServerConfiguration {
    public String info = null;
    public String idlURL = null;
    public String idlContents = null;
    public List<ServerInfo> servers = new ArrayList<>();

    public final void clear() {
        info = null;
        idlURL = null;
        idlContents = null;
        if (servers != null)
            servers.clear();
    }

    private final static ObjectReader jsonReader;
    private final static ObjectWriter jsonWriter;

    static {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); // <== Error:(52, 15) java: cannot access com.fasterxml.jackson.core.JsonGenerator class file for com.fasterxml.jackson.core.JsonGenerator not found
        //mapper.configure(SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED, true);
        jsonWriter = mapper.writer();
        jsonReader = mapper.reader(ServerConfiguration.class);
    }

    public static ServerConfiguration fromJson(String json) throws IOException {
        return jsonReader.<ServerConfiguration>readValue(json); // <== Error:(59, 26) java: cannot access com.fasterxml.jackson.core.JsonProcessingException class file for com.fasterxml.jackson.core.JsonProcessingException not found
    }

    public String toJson() throws IOException {
        return jsonWriter.writeValueAsString(this);
    }

}

eventhough the jar files are in the classpath(autocomplete shows the method declaration in Intellij).

What am I missing?


问:
PyQt4: printing Code 128 barcode fonts
I'm trying to write a text in code128 and a printer also ends in a picture, but it does not work in either of the two ways, I looked at the official documentation and other forum questions but it does not print in code128

```<code>from PyQt4.QtGui import QApplication,QImage,QFont
from PyQt4.QtCore import QSizeF
import sys,time
app = QApplication(sys.argv)
image = QImage(640,100,QImage.Format_Mono)
image.fill(1)
font = QFont('code128',32,QFont.Normal)
painter = QPainter()
painter.begin(image)
painter.setFont(font)
text = "\xccasdfsf\xce"
painter.drawText(10,90,text)
painter.end()
image.save('test.png')
</code>```

and also in my thermal printer

```<code>from PyQt4.QtGui import QApplication,QImage,QFont,QPrinter
from PyQt4.QtCore import QSizeF
import sys,time
app = QApplication(sys.argv)
printer = QPrinter('POS-58(copy of 1)')
font = QFont('code128',32,QFont.Normal)
painter = QPainter()
painter.begin(printer)
painter.setFont(font)
text = "\xccasdfsf\xce"
painter.drawText(10,90,text)
painter.end()
</code>```

Neither of these two works for me and I find a solution for this, what could be happening?

The actual output is this

I am using PyQt4 in windows 10 with python 2.7

答:
From your comments, it is clear that the Code 128 font has not been installed properly on your system, so it is falling back to MS Shell Dlg 2 as a default.

To see exactly which fonts are available to Qt on your system, you can do this:

```<code>>>> fd = QtGui.QFontDatabase()
>>> len(fd.families())
209
>>> for f in sorted(fd.families()): print(f)
...
Adobe Courier
Adobe Helvetica
Adobe New Century Schoolbook
Adobe Times
Adobe Utopia
Arabic Newspaper
B&H Lucida
B&H LucidaBright
B&H LucidaTypewriter
Bitstream Charter
Bitstream Terminal
Bitstream Vera Sans
Bitstream Vera Sans Mono
Bitstream Vera Serif
C059
Cantarell
Code 128
Code 128 low
Code 2 of 5 interleaved
Code 3 de 9
Code Datamatrix
Code EAN13
Code PDF417
D050000L
...
</code>```

If the Code 128 font doesn't appear in this list, it has definitely not been installed properly. There are plenty of free versions of this font available online (e.g. Free Barcode Font), so I suggest you try installing some of those instead.

If these fonts still don't show up in Qt's list of font families, you can try adding them explicitly, like this:

```<code>>>> QtGui.QFontDatabase.addApplicationFont('C:\\MyFonts\\code128.ttf')
</code>```

To check that the newly installed font is valid, use QFontInfo:

```<code>>>> font = QtGui.QFont('Code 128')
>>> info = QtGui.QFontInfo(font)
>>> info.family()
'Code 128'
</code>```

(NB: checking font.family() is not sufficient here, because that will only return what was requested, rather than what was actually found).

Title: PyQt4: printing Code 128 barcode fonts

Body:
I'm trying to write a text in code128 and a printer also ends in a picture, but it does not work in either of the two ways, I looked at the official documentation and other forum questions but it does not print in code128

from PyQt4.QtGui import QApplication,QImage,QFont
from PyQt4.QtCore import QSizeF
import sys,time
app = QApplication(sys.argv)
image = QImage(640,100,QImage.Format_Mono)
image.fill(1)
font = QFont('code128',32,QFont.Normal)
painter = QPainter()
painter.begin(image)
painter.setFont(font)
text = "\xccasdfsf\xce"
painter.drawText(10,90,text)
painter.end()
image.save('test.png')

and also in my thermal printer

from PyQt4.QtGui import QApplication,QImage,QFont,QPrinter
from PyQt4.QtCore import QSizeF
import sys,time
app = QApplication(sys.argv)
printer = QPrinter('POS-58(copy of 1)')
font = QFont('code128',32,QFont.Normal)
painter = QPainter()
painter.begin(printer)
painter.setFont(font)
text = "\xccasdfsf\xce"
painter.drawText(10,90,text)
painter.end()

Neither of these two works for me and I find a solution for this, what could be happening?

The actual output is this

I am using PyQt4 in windows 10 with python 2.7

Body:
From your comments, it is clear that the Code 128 font has not been installed properly on your system, so it is falling back to MS Shell Dlg 2 as a default.

To see exactly which fonts are available to Qt on your system, you can do this:

>>> fd = QtGui.QFontDatabase()
>>> len(fd.families())
209
>>> for f in sorted(fd.families()): print(f)
...
Adobe Courier
Adobe Helvetica
Adobe New Century Schoolbook
Adobe Times
Adobe Utopia
Arabic Newspaper
B&H Lucida
B&H LucidaBright
B&H LucidaTypewriter
Bitstream Charter
Bitstream Terminal
Bitstream Vera Sans
Bitstream Vera Sans Mono
Bitstream Vera Serif
C059
Cantarell
Code 128
Code 128 low
Code 2 of 5 interleaved
Code 3 de 9
Code Datamatrix
Code EAN13
Code PDF417
D050000L
...

If the Code 128 font doesn't appear in this list, it has definitely not been installed properly. There are plenty of free versions of this font available online (e.g. Free Barcode Font), so I suggest you try installing some of those instead.

If these fonts still don't show up in Qt's list of font families, you can try adding them explicitly, like this:

>>> QtGui.QFontDatabase.addApplicationFont('C:\\MyFonts\\code128.ttf')

To check that the newly installed font is valid, use QFontInfo:

>>> font = QtGui.QFont('Code 128')
>>> info = QtGui.QFontInfo(font)
>>> info.family()
'Code 128'

(NB: checking font.family() is not sufficient here, because that will only return what was requested, rather than what was actually found).


问:
Change anchors/Constraints when a button is pressed
I have added a subview inside of a UIViewController. This subview (called PlayerView) should have two states. One is a collapsed state, which only has a height of 56. It's expanded state has a height of 385. When the subview is changed from collapsed to expanded, I want the subviews within the PlayerView to change shape and position.

When the PlayerView is added to the UIViewController (MasterViewController), it uses layoutSubviews() like so:

```<code>override func layoutSubviews() {
    super.layoutSubviews()

    backgroundColor = UIColor(red: 24/255, green: 24/255, blue: 24/255, alpha: 1)

    roundCorners([.topLeft, .topRight], radius: 10)

    addSubview(albumImage)
    addSubview(songTitleLabel)
    addSubview(songArtistLabel)
    addSubview(playPauseButton)

    _ = albumImage.anchor(nil, left: leftAnchor, bottom: nil, right: nil, topConstant: 0, leftConstant: 20, bottomConstant: 0, rightConstant: 0, widthConstant: 40, heightConstant: 40)
    albumImage.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
    _ = playPauseButton.anchor(nil, left: nil, bottom: nil, right: rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 30, widthConstant: 22, heightConstant: 22)
    _ = songTitleLabel.anchor(albumImage.topAnchor, left: albumImage.rightAnchor, bottom: nil, right: playPauseButton.leftAnchor, topConstant: 0, leftConstant: 8, bottomConstant: 0, rightConstant: 8, widthConstant: songTitleLabel.frame.width, heightConstant: songTitleLabel.frame.height)
    _ = songArtistLabel.anchor(songTitleLabel.bottomAnchor, left: songTitleLabel.leftAnchor, bottom: nil, right: playPauseButton.leftAnchor, topConstant: 2, leftConstant: 8, bottomConstant: 0, rightConstant: 8, widthConstant: songArtistLabel.frame.width, heightConstant: songArtistLabel.frame.height)
    playPauseButton.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true

}
</code>```

When the collapsed view is pressed, it is supposed to expand. Here is how I went about doing that (This is inside my MasterViewController):

```<code>let pv = PlayerView()

func expandPlayerView() {
    UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {

        self.view.layoutIfNeeded()
        self.pv.frame = CGRect(x: 0, y: CGFloat((self.view.frame.maxY) - 352), width: 375, height: 350)
        self.pv.changePlayerView()

        self.view.layoutSubviews()
    }) { (true) in

    }
}
</code>```

The changePlayerView() function is defined like this:

```<code>func changePlayerView() {
    subviews.forEach({$0.removeFromSuperview()})
    addSubview(playPauseButton)
    playPauseButton.removeConstraints(playPauseButton.constraints)

    _ = playPauseButton.anchor(nil, left: nil, bottom: bottomAnchor, right: nil, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 22, heightConstant: 22)
    playPauseButton.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
}
</code>```

What happens after all of this code is executed is:
1. The playerView expands to 385 fine
2. All other subviews are removed from the playerView
3. The play pause button takes up almost the entire PlayerView subview, and does not conform to its width and height constraint of 22

What do I need to do to get the playPauseButton conform to all of its constraints?

EDIT:

The .anchor function is defined in an extension of UIView like so:

```<code>func anchor(_ top: NSLayoutYAxisAnchor? = nil, left: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, right: NSLayoutXAxisAnchor? = nil, topConstant: CGFloat = 0, leftConstant: CGFloat = 0, bottomConstant: CGFloat = 0, rightConstant: CGFloat = 0, widthConstant: CGFloat = 0, heightConstant: CGFloat = 0) -> [NSLayoutConstraint] {
    translatesAutoresizingMaskIntoConstraints = false

    var anchors = [NSLayoutConstraint]()

    if let top = top{
        anchors.append(topAnchor.constraint(equalTo: top, constant: topConstant))
    }
    if let left = left{
        anchors.append(leftAnchor.constraint(equalTo: left, constant: leftConstant))
    }
    if let bottom = bottom{
        anchors.append(bottomAnchor.constraint(equalTo: bottom, constant: -bottomConstant))
    }
    if let right = right{
        anchors.append(rightAnchor.constraint(equalTo: right, constant: -rightConstant))
    }
    if widthConstant > 0{
        anchors.append(widthAnchor.constraint(equalToConstant: widthConstant))
    }
    if heightConstant > 0{
        anchors.append(heightAnchor.constraint(equalToConstant: heightConstant))
    }
    anchors.forEach({$0.isActive = true})
    return anchors
}
</code>```

答:
I can't say what is happening in your code, but you are trying to change constraints very differently than I do. Here's what I tend to do for changing constraints:

Declare all consistant or global constraints - those that will not change "as usual", setting isActive = true. No need to re-write things.

Explicitly set up those constraints that change, either one at a time or in an array, depending on your needs.

Never use removeConstraints! (While it's maybe more of a personal rule, I've never found a good use case for using it.) Instead set isActive or use NSLayoutConstraint.deactivate and NSLayoutConstraint.activate for your arrays.

Unless you have a specific need to, do not remove subviews! Messing with the view hierarchy risks ending up with either missing or incomplete constraints. Instead, use isHidden = true.

I'm thinking it's my last bullet point that's the cause for your result.

Here's an example of setting up two arrays of constraints, one for portrait and one for landscape orientation. Say I have two views that I wish to be above each other in portrait but next to each other in landscape.

In my view controller I have two views:

```<code>var p = [NSLayoutConstraint]()
var l = [NSLayoutConstraint]()
var initialOrientation = true
var isInPortrait = false

var greenView = UIView()
var redView = UIView()

override func viewDidLoad() {
    super.viewDidLoad()
    view.translatesAutoresizingMaskIntoConstraints = false
    greenView.translatesAutoresizingMaskIntoConstraints = false
    redView.translatesAutoresizingMaskIntoConstraints = false

    greenView.backgroundColor = UIColor.green
    redView.backgroundColor = UIColor.red

    view.addSubview(greenView)
    view.addSubview(redView)

    setupConstraints()

}

override func viewWillLayoutSubviews() {
    super.viewDidLayoutSubviews()
    if initialOrientation {
        initialOrientation = false
        if view.frame.width > view.frame.height {
            isInPortrait = false
        } else {
            isInPortrait = true
        }
        view.setOrientation(p, l)
    } else {
        if view.orientationHasChanged(&isInPortrait) {
            view.setOrientation(p, l)
        }
    }
}
</code>```

I create two extensions. Here's the view controller extension:

```<code>extension ViewController {
    func setupConstraints() {

        // create generic layout guides

        let layoutGuideTop = UILayoutGuide()
        view.addLayoutGuide(layoutGuideTop)

        let layoutGuideBottom = UILayoutGuide()
        view.addLayoutGuide(layoutGuideBottom)

        let margins = view.layoutMarginsGuide
        view.addLayoutGuide(margins)

        if #available(iOS 11, *) {
            let guide = view.safeAreaLayoutGuide
            layoutGuideTop.topAnchor.constraintEqualToSystemSpacingBelow(guide.topAnchor, multiplier: 1.0).isActive = true
            layoutGuideBottom.bottomAnchor.constraintEqualToSystemSpacingBelow(guide.bottomAnchor, multiplier: 1.0).isActive = true
        } else {
            layoutGuideTop.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor).isActive = true
            layoutGuideBottom.bottomAnchor.constraint(equalTo: bottomLayoutGuide.topAnchor).isActive = true
        }

        p.append(greenView.topAnchor.constraint(equalTo: layoutGuideTop.topAnchor))
        p.append(greenView.leadingAnchor.constraint(equalTo: margins.leadingAnchor))
        p.append(greenView.trailingAnchor.constraint(equalTo: margins.trailingAnchor))
        p.append(greenView.heightAnchor.constraint(equalTo: redView.heightAnchor))

        p.append(redView.topAnchor.constraint(equalTo: greenView.bottomAnchor))
        p.append(redView.leadingAnchor.constraint(equalTo: margins.leadingAnchor))
        p.append(redView.trailingAnchor.constraint(equalTo: margins.trailingAnchor))
        p.append(redView.bottomAnchor.constraint(equalTo: layoutGuideBottom.bottomAnchor))

        l.append(greenView.topAnchor.constraint(equalTo: layoutGuideTop.topAnchor))
        l.append(greenView.leadingAnchor.constraint(equalTo: margins.leadingAnchor))
        l.append(greenView.widthAnchor.constraint(equalTo: redView.widthAnchor))
        l.append(greenView.bottomAnchor.constraint(equalTo: layoutGuideBottom.bottomAnchor))

        l.append(redView.topAnchor.constraint(equalTo: layoutGuideTop.topAnchor))
        l.append(redView.leadingAnchor.constraint(equalTo: greenView.trailingAnchor))
        l.append(redView.bottomAnchor.constraint(equalTo: layoutGuideBottom.bottomAnchor))
        l.append(redView.trailingAnchor.constraint(equalTo:margins.trailingAnchor))
    }
}
</code>```

The real magic is in a UIView extension, where I activate/deactivate the two arrays:

```<code>extension UIView {
    public func orientationHasChanged(_ isInPortrait:inout Bool) -> Bool {
        if self.frame.width > self.frame.height {
            if isInPortrait {
                isInPortrait = false
                return true
            }
        } else {
            if !isInPortrait {
                isInPortrait = true
                return true
            }
        }
        return false
    }
    public func setOrientation(_ p:[NSLayoutConstraint], _ l:[NSLayoutConstraint]) {
        NSLayoutConstraint.deactivate(l)
        NSLayoutConstraint.deactivate(p)
        if self.bounds.width > self.bounds.height {
            NSLayoutConstraint.activate(l)
        } else {
            NSLayoutConstraint.activate(p)
        }
    }
}
</code>```

The other way I change constraints is by directly declaring something and changing the multiplier, constant, or priority. The main trick is to remember you need to separate setting the isActive flag. (Don't ask me why. It's improperly typed in Xcode and I'll bet Apple calls it a "behavior".)

```<code>var myButtonWidth = myButton.widthAnchor.constraint(equalToConstant: 100)
myButtonWidth.isActive = true
</code>```

And to change is, just code against it:

```<code>func changeMyButton() {
    myButtonWidth.constant = 200
}
</code>```

Hopefully some of this helps.

Body:
I have added a subview inside of a UIViewController. This subview (called PlayerView) should have two states. One is a collapsed state, which only has a height of 56. It's expanded state has a height of 385. When the subview is changed from collapsed to expanded, I want the subviews within the PlayerView to change shape and position.

When the PlayerView is added to the UIViewController (MasterViewController), it uses layoutSubviews() like so:

override func layoutSubviews() {
    super.layoutSubviews()

    backgroundColor = UIColor(red: 24/255, green: 24/255, blue: 24/255, alpha: 1)

    roundCorners([.topLeft, .topRight], radius: 10)

    addSubview(albumImage)
    addSubview(songTitleLabel)
    addSubview(songArtistLabel)
    addSubview(playPauseButton)

    _ = albumImage.anchor(nil, left: leftAnchor, bottom: nil, right: nil, topConstant: 0, leftConstant: 20, bottomConstant: 0, rightConstant: 0, widthConstant: 40, heightConstant: 40)
    albumImage.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
    _ = playPauseButton.anchor(nil, left: nil, bottom: nil, right: rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 30, widthConstant: 22, heightConstant: 22)
    _ = songTitleLabel.anchor(albumImage.topAnchor, left: albumImage.rightAnchor, bottom: nil, right: playPauseButton.leftAnchor, topConstant: 0, leftConstant: 8, bottomConstant: 0, rightConstant: 8, widthConstant: songTitleLabel.frame.width, heightConstant: songTitleLabel.frame.height)
    _ = songArtistLabel.anchor(songTitleLabel.bottomAnchor, left: songTitleLabel.leftAnchor, bottom: nil, right: playPauseButton.leftAnchor, topConstant: 2, leftConstant: 8, bottomConstant: 0, rightConstant: 8, widthConstant: songArtistLabel.frame.width, heightConstant: songArtistLabel.frame.height)
    playPauseButton.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true

}

When the collapsed view is pressed, it is supposed to expand. Here is how I went about doing that (This is inside my MasterViewController):

let pv = PlayerView()

func expandPlayerView() {
    UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {

        self.view.layoutIfNeeded()
        self.pv.frame = CGRect(x: 0, y: CGFloat((self.view.frame.maxY) - 352), width: 375, height: 350)
        self.pv.changePlayerView()

        self.view.layoutSubviews()
    }) { (true) in

    }
}

The changePlayerView() function is defined like this:

func changePlayerView() {
    subviews.forEach({$0.removeFromSuperview()})
    addSubview(playPauseButton)
    playPauseButton.removeConstraints(playPauseButton.constraints)

    _ = playPauseButton.anchor(nil, left: nil, bottom: bottomAnchor, right: nil, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 22, heightConstant: 22)
    playPauseButton.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
}

What happens after all of this code is executed is:
1. The playerView expands to 385 fine
2. All other subviews are removed from the playerView
3. The play pause button takes up almost the entire PlayerView subview, and does not conform to its width and height constraint of 22

What do I need to do to get the playPauseButton conform to all of its constraints?

EDIT:

The .anchor function is defined in an extension of UIView like so:

func anchor(_ top: NSLayoutYAxisAnchor? = nil, left: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, right: NSLayoutXAxisAnchor? = nil, topConstant: CGFloat = 0, leftConstant: CGFloat = 0, bottomConstant: CGFloat = 0, rightConstant: CGFloat = 0, widthConstant: CGFloat = 0, heightConstant: CGFloat = 0) -> [NSLayoutConstraint] {
    translatesAutoresizingMaskIntoConstraints = false

    var anchors = [NSLayoutConstraint]()

    if let top = top{
        anchors.append(topAnchor.constraint(equalTo: top, constant: topConstant))
    }
    if let left = left{
        anchors.append(leftAnchor.constraint(equalTo: left, constant: leftConstant))
    }
    if let bottom = bottom{
        anchors.append(bottomAnchor.constraint(equalTo: bottom, constant: -bottomConstant))
    }
    if let right = right{
        anchors.append(rightAnchor.constraint(equalTo: right, constant: -rightConstant))
    }
    if widthConstant > 0{
        anchors.append(widthAnchor.constraint(equalToConstant: widthConstant))
    }
    if heightConstant > 0{
        anchors.append(heightAnchor.constraint(equalToConstant: heightConstant))
    }
    anchors.forEach({$0.isActive = true})
    return anchors
}

Body:
I can't say what is happening in your code, but you are trying to change constraints very differently than I do. Here's what I tend to do for changing constraints:

Declare all consistant or global constraints - those that will not change "as usual", setting isActive = true. No need to re-write things.

Explicitly set up those constraints that change, either one at a time or in an array, depending on your needs.

Never use removeConstraints! (While it's maybe more of a personal rule, I've never found a good use case for using it.) Instead set isActive or use NSLayoutConstraint.deactivate and NSLayoutConstraint.activate for your arrays.

Unless you have a specific need to, do not remove subviews! Messing with the view hierarchy risks ending up with either missing or incomplete constraints. Instead, use isHidden = true.

I'm thinking it's my last bullet point that's the cause for your result.

Here's an example of setting up two arrays of constraints, one for portrait and one for landscape orientation. Say I have two views that I wish to be above each other in portrait but next to each other in landscape.

In my view controller I have two views:

var p = [NSLayoutConstraint]()
var l = [NSLayoutConstraint]()
var initialOrientation = true
var isInPortrait = false

var greenView = UIView()
var redView = UIView()

override func viewDidLoad() {
    super.viewDidLoad()
    view.translatesAutoresizingMaskIntoConstraints = false
    greenView.translatesAutoresizingMaskIntoConstraints = false
    redView.translatesAutoresizingMaskIntoConstraints = false

    greenView.backgroundColor = UIColor.green
    redView.backgroundColor = UIColor.red

    view.addSubview(greenView)
    view.addSubview(redView)

    setupConstraints()

}

override func viewWillLayoutSubviews() {
    super.viewDidLayoutSubviews()
    if initialOrientation {
        initialOrientation = false
        if view.frame.width > view.frame.height {
            isInPortrait = false
        } else {
            isInPortrait = true
        }
        view.setOrientation(p, l)
    } else {
        if view.orientationHasChanged(&isInPortrait) {
            view.setOrientation(p, l)
        }
    }
}

I create two extensions. Here's the view controller extension:

extension ViewController {
    func setupConstraints() {

        // create generic layout guides

        let layoutGuideTop = UILayoutGuide()
        view.addLayoutGuide(layoutGuideTop)

        let layoutGuideBottom = UILayoutGuide()
        view.addLayoutGuide(layoutGuideBottom)

        let margins = view.layoutMarginsGuide
        view.addLayoutGuide(margins)

        if #available(iOS 11, *) {
            let guide = view.safeAreaLayoutGuide
            layoutGuideTop.topAnchor.constraintEqualToSystemSpacingBelow(guide.topAnchor, multiplier: 1.0).isActive = true
            layoutGuideBottom.bottomAnchor.constraintEqualToSystemSpacingBelow(guide.bottomAnchor, multiplier: 1.0).isActive = true
        } else {
            layoutGuideTop.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor).isActive = true
            layoutGuideBottom.bottomAnchor.constraint(equalTo: bottomLayoutGuide.topAnchor).isActive = true
        }

        p.append(greenView.topAnchor.constraint(equalTo: layoutGuideTop.topAnchor))
        p.append(greenView.leadingAnchor.constraint(equalTo: margins.leadingAnchor))
        p.append(greenView.trailingAnchor.constraint(equalTo: margins.trailingAnchor))
        p.append(greenView.heightAnchor.constraint(equalTo: redView.heightAnchor))

        p.append(redView.topAnchor.constraint(equalTo: greenView.bottomAnchor))
        p.append(redView.leadingAnchor.constraint(equalTo: margins.leadingAnchor))
        p.append(redView.trailingAnchor.constraint(equalTo: margins.trailingAnchor))
        p.append(redView.bottomAnchor.constraint(equalTo: layoutGuideBottom.bottomAnchor))

        l.append(greenView.topAnchor.constraint(equalTo: layoutGuideTop.topAnchor))
        l.append(greenView.leadingAnchor.constraint(equalTo: margins.leadingAnchor))
        l.append(greenView.widthAnchor.constraint(equalTo: redView.widthAnchor))
        l.append(greenView.bottomAnchor.constraint(equalTo: layoutGuideBottom.bottomAnchor))

        l.append(redView.topAnchor.constraint(equalTo: layoutGuideTop.topAnchor))
        l.append(redView.leadingAnchor.constraint(equalTo: greenView.trailingAnchor))
        l.append(redView.bottomAnchor.constraint(equalTo: layoutGuideBottom.bottomAnchor))
        l.append(redView.trailingAnchor.constraint(equalTo:margins.trailingAnchor))
    }
}

The real magic is in a UIView extension, where I activate/deactivate the two arrays:

extension UIView {
    public func orientationHasChanged(_ isInPortrait:inout Bool) -> Bool {
        if self.frame.width > self.frame.height {
            if isInPortrait {
                isInPortrait = false
                return true
            }
        } else {
            if !isInPortrait {
                isInPortrait = true
                return true
            }
        }
        return false
    }
    public func setOrientation(_ p:[NSLayoutConstraint], _ l:[NSLayoutConstraint]) {
        NSLayoutConstraint.deactivate(l)
        NSLayoutConstraint.deactivate(p)
        if self.bounds.width > self.bounds.height {
            NSLayoutConstraint.activate(l)
        } else {
            NSLayoutConstraint.activate(p)
        }
    }
}

The other way I change constraints is by directly declaring something and changing the multiplier, constant, or priority. The main trick is to remember you need to separate setting the isActive flag. (Don't ask me why. It's improperly typed in Xcode and I'll bet Apple calls it a "behavior".)

var myButtonWidth = myButton.widthAnchor.constraint(equalToConstant: 100)
myButtonWidth.isActive = true

And to change is, just code against it:

func changeMyButton() {
    myButtonWidth.constant = 200
}

Hopefully some of this helps.


问:
Polymer JS: Does prepending an item to an Array property re-render the whole UI?
I have a component with following template markup inside it

```<code><template is="dom-repeat" items="{{values}}">
    <div><span>{{item.msg}}</span></div>
</template>
</code>```

This component has a property values which is an Array of objects.

Now  I want to prepend item to this array property in response to an event. Does polymer rerender this complete UI throwing away the existing DOM elements, because all the existing elements will pushed down by an index of 1 ? If so, what are optimizations I can implements to avoid DOM rerendering which can be expensive when the Array grows big.

答:
Short answer is no.

It's not about Polymer, it's about dom-repeat.

About dom-repeat behavior, you can see from github.

In simple words for every render

Create index array to apply sort and filter function

Loop through the array of instance (an object from templatize function), assign an item to it if already exist (from previous render)

If not, create a new one, push to array and insert to parent node.

If it has exceeded instances, remove it.

See __applyFullRefresh.

So yes it reuse existing DOM elements.

As I said this is about dom-repeat. You should see iron-list which do similar thing with better performance or create by yourself in the way you want.

Body:
I have a component with following template markup inside it

<template is="dom-repeat" items="{{values}}">

{{item.msg}}

</template>

This component has a property values which is an Array of objects.

Now  I want to prepend item to this array property in response to an event. Does polymer rerender this complete UI throwing away the existing DOM elements, because all the existing elements will pushed down by an index of 1 ? If so, what are optimizations I can implements to avoid DOM rerendering which can be expensive when the Array grows big.


问:
There alawys has complile error when compile the latest kernel in ubuntu,as follow
LD      arch/x86/realmode/rm/realmode.elf
arch/x86/realmode/rm/header.o: In function real_mode_header':
(.header+0x8): undefined reference topa_trampoline_start'
arch/x86/realmode/rm/header.o: In function real_mode_header':
(.header+0xc): undefined reference topa_trampoline_status'
arch/x86/realmode/rm/header.o: In function real_mode_header':
(.header+0x10): undefined reference topa_trampoline_header'
arch/x86/realmode/rm/header.o: In function real_mode_header':
(.header+0x14): undefined reference topa_trampoline_pgd'
arch/x86/realmode/rm/header.o: In function real_mode_header':
(.header+0x18): undefined reference topa_wakeup_start'
arch/x86/realmode/rm/header.o: In function real_mode_header':
(.header+0x1c): undefined reference topa_wakeup_header'
arch/x86/realmode/rm/header.o: In function real_mode_header':
(.header+0x20): undefined reference topa_machine_real_restart_asm'
arch/x86/realmode/rm/trampoline_64.o: In function trampoline_start':
/home/xhyang/src/linux/arch/x86/realmode/rm/trampoline_64.S:77: undefined reference topa_startup_32'
arch/x86/realmode/rm/trampoline_64.o: In function startup_32':
/home/xhyang/src/linux/arch/x86/realmode/rm/trampoline_64.S:95: undefined reference topa_tr_cr4'
/home/xhyang/src/linux/arch/x86/realmode/rm/trampoline_64.S:99: undefined reference to pa_trampoline_pgd'
/home/xhyang/src/linux/arch/x86/realmode/rm/trampoline_64.S:103: undefined reference topa_tr_efer'
/home/xhyang/src/linux/arch/x86/realmode/rm/trampoline_64.S:104: undefined reference to pa_tr_efer'
/home/xhyang/src/linux/arch/x86/realmode/rm/trampoline_64.S:118: undefined reference topa_startup_64'
arch/x86/realmode/rm/trampoline_64.o: In function tr_gdt':
(.rodata+0x2): undefined reference topa_tr_gdt'
arch/x86/realmode/rm/reboot.o: In function machine_real_restart_asm':
/home/xhyang/src/linux/arch/x86/realmode/rm/reboot.S:27: undefined reference topa_tr_gdt'
/home/xhyang/src/linux/arch/x86/realmode/rm/reboot.S:33: undefined reference to pa_machine_real_restart_paging_off'
arch/x86/realmode/rm/reboot.o: In functionmachine_real_restart_paging_off':
/home/xhyang/src/linux/arch/x86/realmode/rm/reboot.S:46: undefined reference to pa_machine_real_restart_idt'
/home/xhyang/src/linux/arch/x86/realmode/rm/reboot.S:53: undefined reference topa_machine_real_restart_gdt'
arch/x86/realmode/rm/reboot.o: In function machine_real_restart_gdt':
(.rodata+0x12): undefined reference topa_machine_real_restart_gdt'
arch/x86/realmode/rm/wakeup_asm.o: In function wakeup_gdt':
(.rodata+0x2): undefined reference topa_wakeup_gdt'
make[3]: * [arch/x86/realmode/rm/realmode.elf] Error 1
make[2]: * [arch/x86/realmode/rm/realmode.bin] Error 2

答:
I also experienced this issue.

I did find a fix. My issue was with: sed flags. Specifically, the "-r" in the sed params from the Makefile.

After installing GNU bintools and gsed and then changing the Makefile for the realtime linking to use gsed instead of sed resolved this issue.

Hope that helps.

~m


答: You are missing a semi-colon after padding-top: 100px . You can also try position:fixed instead of position:absolute. An element with position: fixed; is positioned relative to the viewport, which means it always stays in the same place even if the page is scrolled. </p>

Title: How to make footer stick to the bottom


问:
Why use isolated storage in an ASP.NET application?
I need to store user preferences on a per page basis in my application.  For example, several pages use a custom grid pager control that needs to keep its current page size between postbacks.  Most of the settings don't need to persist once the user leaves the page, but in some situations they do need to be restored.  Note: Session is disabled in this application and will not be used.

I did some reading on isolated storage and understand that it can be used to store these user settings.  Obviously cookies have been around a long time and are a proven approach to this scenario, but what about isolated storage?  Is it going to work for all browsers and in all environments?  Are permissions a problem?  Does it require configuring anything on the end-user's side?  Just how widely used is it?  Why should one use isolated storage in an application for the given example?

Thanks!

答:
Obviously cookies have been around a
  long time and are a proven approach to
  this scenario, but what about isolated
  storage? Is it going to work for all
  browsers and in all environments?

Ah - .NET isolated storage is SERVER SIDE. Like a database. It is meant as a small way to store small amounts of data( ONE user, not all users, viewstate) on the side the .NET application runs (in asp.net case = the server).

As such it is totally irrelvant to your question.

Put the data in a database. I know of VERY few usages of isolated stoage for ASP.NET applications, it craetes a TON of long term problems. It is not meant for server side apps.


问:
Targeting imagebutton inside template data field in web data grid
I have an ImageButton (ImageButton1) inside a web data grid. I am trying to write an if statement that if the date is less than a certain date then the image button won't be visible. I cannot figure out how to target the ImageButton though. This is the code I have:

```<code> <ig:TemplateDataField Key="Export" CssClass="MinWidth45 Nowrap">
  <Header Text="Map Link"></Header>
  <ItemTemplate>
    <asp:ImageButton ID="ImageButton1" runat="server" OnClientClick="Block(true);" OnClick="ImageButton1_Click" CssClass="Stopper" ImageUrl="~/images/ExcelExport.bmp" Height="25px" Width="24px" ToolTip="Export to Excel" EnableViewState="false"/>
  </ItemTemplate>
 </ig:TemplateDataField>
</code>```

back-end code(Targeting it by typing it's ID(ImageButton1) doesn't work):

```<code> If e.Row.Items.FindItemByKey("Dates").Value < Date.Today Then

    ImageButton1.visible = False

 End If
</code>```

答:
```<code>If e.Row.Items.FindItemByKey("Dates").Value < Date.Today Then

   e.Row.Items(13).FindControl("ImageButton1").Visible = False

End If
</code>```

<p>"(13)" being the index of the column in my data table</p>

Body:
I have an ImageButton (ImageButton1) inside a web data grid. I am trying to write an if statement that if the date is less than a certain date then the image button won't be visible. I cannot figure out how to target the ImageButton though. This is the code I have:

 <ig:TemplateDataField Key="Export" CssClass="MinWidth45 Nowrap">

  <ItemTemplate>
    <asp:ImageButton ID="ImageButton1" runat="server" OnClientClick="Block(true);" OnClick="ImageButton1_Click" CssClass="Stopper" ImageUrl="~/images/ExcelExport.bmp" Height="25px" Width="24px" ToolTip="Export to Excel" EnableViewState="false"/>
  </ItemTemplate>
 </ig:TemplateDataField>

back-end code(Targeting it by typing it's ID(ImageButton1) doesn't work):

 If e.Row.Items.FindItemByKey("Dates").Value < Date.Today Then

    ImageButton1.visible = False

 End If

Body:
If e.Row.Items.FindItemByKey("Dates").Value < Date.Today Then

   e.Row.Items(13).FindControl("ImageButton1").Visible = False

End If

"(13)" being the index of the column in my data table


问:
{TypeError: unsupported operand type(s) for +: 'int' and 'str'} with input
I am new to python and I was learning with Grok, but I got stuck on this part</p>

```<code>money = input("Enter the expenses: ")
addup = money.split()
total = sum(addup)
print("Total: ", total)
</code>```

答:
You're trying to "sum" strings, which of course doesn't work. You'll need to make them integers or floats to add them up. How exactly you could do that depends on what you expect the user to input.

This may work

```<code>addup=[float(x) for x in addup]
</code>```

Body:
I am new to python and I was learning with Grok, but I got stuck on this part

money = input("Enter the expenses: ")
addup = money.split()
total = sum(addup)
print("Total: ", total)

Body:
You're trying to "sum" strings, which of course doesn't work. You'll need to make them integers or floats to add them up. How exactly you could do that depends on what you expect the user to input.

This may work

addup=[float(x) for x in addup]