问:
Bootstrap footer is not at the bottom of any page
I've seen a few of these on Stack Overflow, but the questions that have been asked don't lead to an answer which solves my issue. Please take the time to look over my code before marking it down or flagging it as a duplicate.

I'm working through a book called "Beginning django CMS". I'm finding that a few parts are out of date, and that might be the issue here. It's tough for me to say because I'm new to web design.

The footer isn't in a
, and I've gone over the padding to see if that helps. Those are the kinds of issues that come up as answers to questions that have previously been posted on Stack Overflow.

I'm being left with a footer which begins ends an inch from the bottom of the screen. Does anyone know what might be causing this?

I've checked this in Chrome and Edge so far, both come up with the indent.

Here's the HTML:

```<code>{% load cms_tags staticfiles sekizai_tags menu_tags %}
<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv"X-UA-Compatible" Content = "IE=Edge">
    <meta name = "viewport" content="width=device-width", initial-scale=1>

    <link rel="icon" href="favicon.ico">

    <title>{% block title %}MyBlog Title{% endblock title %}</title>

    <link href="https://cdnjs.cloudfare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.min.css" rel = "stylesheet">

    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.min.css">

    <!-- MyBlog custom styles -->
    <link href="{% static "myblog.css" %}" rel="stylesheet">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
        <script src=https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
        <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->

    {% render_block "css" %}
</head>
<body>
    {% cms_toolbar %}
    <nav class="navbar navbar-default navbar-static-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a href=""><img src="{% static "" %}"/></a>
            </div>
            <div id="navbar" class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    {% show_menu 0 1 0 100 "menu.html" %}
                </ul>
            </div>
        </div>
    </nav>

    <div class="container">
        <div class="blog-header">
            <h1 class="blog-title">(Now a banner)</h1>
            <p class="lead blog-description">The political system is broken; it could do with a Patch</p>
        </div>
        {% block content %}{% endblock content %}
    </div>

    <footer class="footer">
     <div class="container">
      <p class="text-muted">{% block footer %}My Blog©2015{%endblock footer%}</p>
     </div>
    </footer>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/js/bootstrap.min.js"></script>
    <!-- IE10 viewport hack for Surface/desktop Windows 8 bu -->
    <script src="{% static "ie10-viewport-bug-workaround.js" %}"></script>

    {% render_block "js" %}
</body>
</code>```

And the CSS:

```<code>html {
    position : relative;
    min-height: 100%;
}

body {
    /* Margin bottom by footer height */
    margin-bottom: 60px;
    font-family : Georgia, "Times New Roman", Times, serif;
    color #555;
}
h1, .h1, h2, .h2, h3, .h3, h4, .h4, h5, .h5, h6, .h6 {
    margin-top: 0;
    font-family: "Helvetica Neue", Helvetica, Arial, sans-serfi;
    font-weight: normal;
    color: #333;
}
.footer {
    position: absolute;
    margin-left : 0px
    bottom: 0;
    width: 100%;
    height: 60px;
    background-color: #f5f5f5;
}
.blog-header {
    padding-top: 20px;
    padding-bottom: 20px;
}

.blog-title {
    margin-top: 30px;
    margin-bottom: 0;
    font-size: 28px;
    font-weight: normal;
}
.blog-description{
    font-size: 20px;
    color: #999;
}
.sidebar-module{
    padding: 15px;
    margin: 0 -15px 15px;
}
.sidebar-module-inset {
    padding: 15px;
    background-color: #f5f5f5;
    border-radius: 4px;
}
.sidebar-module-inset p:last-child,
.sidebar-module-inset ul:last-child,
.sidebar-module-inset ol:last-child{
    margin-bottom: 0;
}
.pager {
    margin-bottom: 60px;
    text-align: left
}
.pager > li > a {
    width: 140px;
    padding: 10px 20px;
    text-align: center;
    border-radius: 30px;
}
.blog-post{
    margin-bottom: 60px;
}
.blog-post-title{
    margin-bottom: 5px;
    font-size: 40px;
}
.blog-post-meta {
    margin-bottom: 20px;
    color : #999;
}
body > container {
    padding: 0px 0px 0;
}
.container .text-muted {
    margin: 20px 0;
}
.footer > .container {
    padding-right: 15px;
    padding-left: 0;
}
.row {
    margin-right: 0px!important;
}
</code>```

答:
I found the issue. The footer is extending to the bottom of the body, but the bottom wasn't extending to the bottom of the page.

To the start of the CSS, I added:

```<code> * {
     margin:0;
    height: 100%
}
</code>```

That seems to have solved the issue.

Body:
I've seen a few of these on Stack Overflow, but the questions that have been asked don't lead to an answer which solves my issue. Please take the time to look over my code before marking it down or flagging it as a duplicate.

I'm working through a book called "Beginning django CMS". I'm finding that a few parts are out of date, and that might be the issue here. It's tough for me to say because I'm new to web design.

The footer isn't in a
, and I've gone over the padding to see if that helps. Those are the kinds of issues that come up as answers to questions that have previously been posted on Stack Overflow.

I'm being left with a footer which begins ends an inch from the bottom of the screen. Does anyone know what might be causing this?

I've checked this in Chrome and Edge so far, both come up with the indent.

Here's the HTML:

{% load cms_tags staticfiles sekizai_tags menu_tags %}
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv"X-UA-Compatible" Content = "IE=Edge">
    <meta name = "viewport" content="width=device-width", initial-scale=1>

    <link rel="icon" href="favicon.ico">

    <title>{% block title %}MyBlog Title{% endblock title %}</title>

    <link href="https://cdnjs.cloudfare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.min.css" rel = "stylesheet">

    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.min.css">

    <link href="{% static "myblog.css" %}" rel="stylesheet">

    {% render_block "css" %}

    {% cms_toolbar %}

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    Toggle navigation

                </button>

                    {% show_menu 0 1 0 100 "menu.html" %}

(Now a banner)

The political system is broken; it could do with a Patch

        {% block content %}{% endblock content %}

{% block footer %}My Blog©2015{%endblock footer%}

    {% render_block "js" %}

And the CSS:

html {
    position : relative;
    min-height: 100%;
}

body {
    /* Margin bottom by footer height */
    margin-bottom: 60px;
    font-family : Georgia, "Times New Roman", Times, serif;
    color #555;
}
h1, .h1, h2, .h2, h3, .h3, h4, .h4, h5, .h5, h6, .h6 {
    margin-top: 0;
    font-family: "Helvetica Neue", Helvetica, Arial, sans-serfi;
    font-weight: normal;
    color: #333;
}
.footer {
    position: absolute;
    margin-left : 0px
    bottom: 0;
    width: 100%;
    height: 60px;
    background-color: #f5f5f5;
}
.blog-header {
    padding-top: 20px;
    padding-bottom: 20px;
}

.blog-title {
    margin-top: 30px;
    margin-bottom: 0;
    font-size: 28px;
    font-weight: normal;
}
.blog-description{
    font-size: 20px;
    color: #999;
}
.sidebar-module{
    padding: 15px;
    margin: 0 -15px 15px;
}
.sidebar-module-inset {
    padding: 15px;
    background-color: #f5f5f5;
    border-radius: 4px;
}
.sidebar-module-inset p:last-child,
.sidebar-module-inset ul:last-child,
.sidebar-module-inset ol:last-child{
    margin-bottom: 0;
}
.pager {
    margin-bottom: 60px;
    text-align: left
}
.pager > li > a {
    width: 140px;
    padding: 10px 20px;
    text-align: center;
    border-radius: 30px;
}
.blog-post{
    margin-bottom: 60px;
}
.blog-post-title{
    margin-bottom: 5px;
    font-size: 40px;
}
.blog-post-meta {
    margin-bottom: 20px;
    color : #999;
}
body > container {
    padding: 0px 0px 0;
}
.container .text-muted {
    margin: 20px 0;
}
.footer > .container {
    padding-right: 15px;
    padding-left: 0;
}
.row {
    margin-right: 0px!important;
}

Body:
I found the issue. The footer is extending to the bottom of the body, but the bottom wasn't extending to the bottom of the page.

To the start of the CSS, I added:

 * {
     margin:0;
    height: 100%
}

That seems to have solved the issue.


来源: stackexchange

问:
How to append input field dynamically with styles in angular5
I'm trying to append elements dynamically when I click a button.
Actually when I click a button, elements append well.
But the problem is that function and style is not worked.
My code is below.

P.S. I'm using angular5

HTML

```<code><table style="text-align: center; width: 100%">
    <tbody #tContent>
        <!-- I want to append element in here -->
    </tbody>
</table>
    <button type="button" mat-raised-button color="primary" (click)="addTbody()">click here</button>
</code>```

TS

```<code>    addTbody() {
    // I want append below code whenever I click.
    <tr>
      <td style="padding: 30px">
        <input type="file" accept="image/png, image/gif, image/jpeg, image/bmp, image/x-icon" (click)="alert('$event')">
      </td>
      <td style="padding: 30px">
        <input type="file" accept="image/png, image/gif, image/jpeg, image/bmp, image/x-icon" (click)="test2(file)">
      </td>
    </tr>
    <tr>
      <td style="padding: 30px">
          <input  placeholder="image Info" type="text" size="25">
      </td>
      <td style="padding: 30px">
          <input placeholder="image Info" type="text" size="25">
      </td>
    </tr>
}
</code>```

答:
Here you go :

Component side :

```<code>this.rows = [];

addTbody() {
    this.rows.push(1);
}
</code>```

Template side :

```<code><table style="text-align: center; width: 100%">
    <tbody>
        <ng-container *ngFor='let row of rows'>
            <tr>
                <td style="padding: 30px">
                    <input type="file" accept="image/png, image/gif, image/jpeg, image/bmp, image/x-icon" (click)="alert('$event')">
                </td>
                <td style="padding: 30px">
                    <input type="file" accept="image/png, image/gif, image/jpeg, image/bmp, image/x-icon" (click)="test2(file)">
                </td>
            </tr>
            <tr>
                <td style="padding: 30px">
                    <input  placeholder="image Info" type="text" size="25">
                </td>
                <td style="padding: 30px">
                    <input placeholder="image Info" type="text" size="25">
                </td>
            </tr>
        </ng-container>
    </tbody>
</table>
</code>```

Link to WORKING DEMO

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to append elements dynamically when I click a button.
Actually when I click a button, elements append well.
But the problem is that function and style is not worked.
My code is below.

P.S. I'm using angular5

HTML

    <button type="button" mat-raised-button color="primary" (click)="addTbody()">click here</button>

TS

    addTbody() {
    // I want append below code whenever I click.

        <input type="file" accept="image/png, image/gif, image/jpeg, image/bmp, image/x-icon" (click)="alert('$event')">

        <input type="file" accept="image/png, image/gif, image/jpeg, image/bmp, image/x-icon" (click)="test2(file)">

          <input  placeholder="image Info" type="text" size="25">

          <input placeholder="image Info" type="text" size="25">

}

Body:
Here you go :

Component side :

this.rows = [];

addTbody() {
    this.rows.push(1);
}

Template side :

<table style="text-align: center; width: 100%">
    <tbody>
        <ng-container *ngFor='let row of rows'>
            <tr>
                <td style="padding: 30px">
                    <input type="file" accept="image/png, image/gif, image/jpeg, image/bmp, image/x-icon" (click)="alert('$event')">
                </td>
                <td style="padding: 30px">
                    <input type="file" accept="image/png, image/gif, image/jpeg, image/bmp, image/x-icon" (click)="test2(file)">
                </td>
            </tr>
            <tr>
                <td style="padding: 30px">
                    <input  placeholder="image Info" type="text" size="25">
                </td>
                <td style="padding: 30px">
                    <input placeholder="image Info" type="text" size="25">
                </td>
            </tr>
        </ng-container>
    </tbody>
</table>

Link to WORKING DEMO


问:
LLVM IR : C++ API : Typecast from i1 to i32 and i32 to i1
I am writing a compiler for a self-made language which can handle only int values i.e. i32. Conditions and expressions are similar to C language. Thus, I am considering conditional statements as expressions i.e. they return an int value. They can also be used in expressions e.g (2 > 1) + (3 > 2) will return 2. But LLVM conditions output i1 value.

Now, I want that after each conditional statement, i1 should be converted into i32, so that I can carry out binary operations

Also, I want to use variables and expression results as condition e.g. if(variable) or if(a + b). For that I need to convert i32 to i1

At the end, I want a way to typecast from i1 to i32 and from i32 to i1. My code is giving these kinds of errors as of now :

For statement like if(variable) :

```<code>error: branch condition must have 'i1' type
br i32 %0, label %ifb, label %else
   ^
</code>```

For statement like a = b > 3

```<code>error: stored value and pointer type do not match
store i1 %gttmp, i32* @a
      ^
</code>```

Any suggestion on how to do that ?

答:
I figured it out. To convert from i1 to i32, as pointed out here by Ismail Badawi , I used IRBuilder::CreateIntCast. So if v is Value * pointer pointing to an expression resulting in i1, I did following to convert it to i32 :

```<code>v = Builder.CreateIntCast(v, Type::getInt32Ty(getGlobalContext()), true);
</code>```

But same can't be applied for converting i32 to i1. It will truncate the value to least significant bit. So i32 2 will result in i1 0. I needed i1 1 for non-zero i32. If v is Value * pointer pointing to an expression resulting in i32, I did following to convert it in i1 :

```<code>v = Builder.CreateICmpNE(v, ConstantInt::get(Type::getInt32Ty(getGlobalContext()), 0, true))
</code>```

Body:
I am writing a compiler for a self-made language which can handle only int values i.e. i32. Conditions and expressions are similar to C language. Thus, I am considering conditional statements as expressions i.e. they return an int value. They can also be used in expressions e.g (2 > 1) + (3 > 2) will return 2. But LLVM conditions output i1 value.

Now, I want that after each conditional statement, i1 should be converted into i32, so that I can carry out binary operations

Also, I want to use variables and expression results as condition e.g. if(variable) or if(a + b). For that I need to convert i32 to i1

At the end, I want a way to typecast from i1 to i32 and from i32 to i1. My code is giving these kinds of errors as of now :

For statement like if(variable) :

error: branch condition must have 'i1' type
br i32 %0, label %ifb, label %else
   ^

For statement like a = b > 3

error: stored value and pointer type do not match
store i1 %gttmp, i32* @a
      ^

Any suggestion on how to do that ?

Body:
I figured it out. To convert from i1 to i32, as pointed out here by Ismail Badawi , I used IRBuilder::CreateIntCast. So if v is Value * pointer pointing to an expression resulting in i1, I did following to convert it to i32 :

v = Builder.CreateIntCast(v, Type::getInt32Ty(getGlobalContext()), true);

But same can't be applied for converting i32 to i1. It will truncate the value to least significant bit. So i32 2 will result in i1 0. I needed i1 1 for non-zero i32. If v is Value * pointer pointing to an expression resulting in i32, I did following to convert it in i1 :

v = Builder.CreateICmpNE(v, ConstantInt::get(Type::getInt32Ty(getGlobalContext()), 0, true))


问:
Android Studio 3.1 Canary 3 - Gradle sync failed
For a unknown reason Android Studio 3.1 Canary 3 is bugged and stopped to work, I updated gradle to 3.1-alpha03 and it stopped working, no matter if I download the project again, already downloaded Android Studio again too.

I've already checkout old versions of the project, but this message still show:

```<code>Gradle sync failed: com.android.tools.idea.gradle.project.model.AndroidModuleModel.getSelectedVariant()Lcom/android/tools/idea/gradle/project/model/ide/android/IdeVariant; (8s 806ms)
</code>```

I've removed .idea folder, .gradle folder, did invalidate and restart

I don't know nothing more to do, cant run or use the IDE.

Edit:

Edit2:

New Projects doesnt work too

答:
To solve this issue, you have to either upgrade or downgrade your kotlin plugin

Solution 1: Upgrade Plugin

First go to Tools menu > Select Kotlin > Configure Kotlin Plugin Updates > Select one of the kotlin plugin & press download (stable or early access, i chose early access to solve this issue)

And finally change the kotlin version in build.gradle(Project:) according to the
downloaded version

Solution 2: Downgrade Plugin

If your on mac then press: Command + ,
 to open preference, then select plugin & search for kotlin & uninstall it, it will rollback to previous version: 1.1.51

On Windows machine, press Control + Alt + S to open settings dialog, then select plugins & search for kotlin & uninstall it, it will rollback to previous version: 1.1.51

Please Note: Do not uncheck kotlin in plugins else it will disable kotlin & fail to recognise kotlin file & syntax

Body:
For a unknown reason Android Studio 3.1 Canary 3 is bugged and stopped to work, I updated gradle to 3.1-alpha03 and it stopped working, no matter if I download the project again, already downloaded Android Studio again too.

I've already checkout old versions of the project, but this message still show:

Gradle sync failed: com.android.tools.idea.gradle.project.model.AndroidModuleModel.getSelectedVariant()Lcom/android/tools/idea/gradle/project/model/ide/android/IdeVariant; (8s 806ms)

I've removed .idea folder, .gradle folder, did invalidate and restart

I don't know nothing more to do, cant run or use the IDE.

Edit:

Edit2:

New Projects doesnt work too


Title: Sorting a list of dates in ascending order, without concerning the other element

Body:
This is the list:

[['2017-11-09', 21], ['2017-11-14', 39], ['2017-11-13', 43], ['2017-11-10', 37]]

This has to be the output:

[['2017-11-09', 21], ['2017-11-10', 37], ['2017-11-13', 43], ['2017-11-14', 39]]

How do I do this in Python?

Body:
You can use itemgetter for a more generic solution.

>>> from operator import itemgetter
>>> ls = [['2017-11-09', 21], ['2017-11-14', 39], ['2017-11-13', 43], ['2017-11-10', 37]]
>>> sorted(ls, key=itemgetter(0))


问:
OnBackButton pressed Issue
I have 3 Activities A, B, and C.

A is the home activity and B is its child and C is its child.

When I go to Activity C and return to A by pressing back button it gets proper navigation. But after this, if I press back button again to exit the app, it goes back to Activity B instead of exiting the app.

I have finished the Activity B onBackpressed override.

And I have implemented dynamic fragments on Activity B is that causes this problem.

I can't find out why this happens. Does Anyone have an answer?

答:
You can use finish() or finishAffinity() to end that activity

```<code>@Override
public void onBackPressed() {
   finishAffinity();
}
</code>```

Title: OnBackButton pressed Issue

Body:
You can use finish() or finishAffinity() to end that activity

@Override
public void onBackPressed() {
   finishAffinity();
}


问:
flex property not working in IE
I have been unable to determine why flexbox is not working in IE 11.

For testing, I sourced a very simple flexbox layout from CodePen and have pasted the information below.

Chrome works as intended; IE11 fails.

Image of layout-success running on Chrome:

Image of layout-failure on IE11

body {
  background: #333;
  font-family: helvetica;
  font-weight: bold;
  font-size: 1.7rem;
}

ul {
  list-style: none;
}

li {
  background: hotpink;
  height: 200px;
  text-align: center;
  border: 2px solid seashell;
  color: seashell;
  margin: 10px;
  flex: auto;
  min-width: 120px;
  max-width: 180px;
}

.flex {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="flex">
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
  <li>9</li>
  <li>10</li>
</ul></code>```

http://codepen.io/hankthewhale/pen/IdKkB?editors=110

答: Just use flex:1 0 auto;. It will work.

Title: flex property not working in IE

Body:
I have been unable to determine why flexbox is not working in IE 11.

For testing, I sourced a very simple flexbox layout from CodePen and have pasted the information below.

Chrome works as intended; IE11 fails.

Image of layout-success running on Chrome:

Image of layout-failure on IE11

body {
  background: #333;
  font-family: helvetica;
  font-weight: bold;
  font-size: 1.7rem;
}

ul {
  list-style: none;
}

li {
  background: hotpink;
  height: 200px;
  text-align: center;
  border: 2px solid seashell;
  color: seashell;
  margin: 10px;
  flex: auto;
  min-width: 120px;
  max-width: 180px;
}

.flex {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
}

1

2

3

4

5

6

7

8

9

10

http://codepen.io/hankthewhale/pen/IdKkB?editors=110

Body: Just use flex:1 0 auto;. It will work.


问:
Decode Base64 data in Java
I have an image that is Base64 encoded. What is the best way to decode that in Java? Hopefully using only the libraries included with Sun Java 6.</p>

答:
As an alternative to sun.misc.BASE64Decoder or non-core libraries, look at javax.mail.internet.MimeUtility.decode().

```<code>public static byte[] encode(byte[] b) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    OutputStream b64os = MimeUtility.encode(baos, "base64");
    b64os.write(b);
    b64os.close();
    return baos.toByteArray();
}
public static byte[] decode(byte[] b) throws Exception {
    ByteArrayInputStream bais = new ByteArrayInputStream(b);
    InputStream b64is = MimeUtility.decode(bais, "base64");
    byte[] tmp = new byte[b.length];
    int n = b64is.read(tmp);
    byte[] res = new byte[n];
    System.arraycopy(tmp, 0, res, 0, n);
    return res;
}
</code>```

OwnerDisplayName: Ryan P

Title: Decode Base64 data in Java

LastEditorDisplayName: Ryan P

Body:
As an alternative to sun.misc.BASE64Decoder or non-core libraries, look at javax.mail.internet.MimeUtility.decode().

public static byte[] encode(byte[] b) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    OutputStream b64os = MimeUtility.encode(baos, "base64");
    b64os.write(b);
    b64os.close();
    return baos.toByteArray();
}
public static byte[] decode(byte[] b) throws Exception {
    ByteArrayInputStream bais = new ByteArrayInputStream(b);
    InputStream b64is = MimeUtility.decode(bais, "base64");
    byte[] tmp = new byte[b.length];
    int n = b64is.read(tmp);
    byte[] res = new byte[n];
    System.arraycopy(tmp, 0, res, 0, n);
    return res;
}

OwnerDisplayName: RealHowTo

ContentLicense: CC BY-SA 4.0


问:
XML schema to restrict the range (min, max) of a hexadecimal value
I would like to restrict the range of a hexadecimal memory address value in an XML document using a schema. The xml hexadecimal entry has to be in string format as it is parsed from a GUI textbox and directly saved to the XML document after it is validated with the schema document.

I have this.

XSD:

```<code><xs:simpleType name="memory_address_type">
  <xs:restriction base="xs:string">
    <xs:pattern value="([0-9A-Fa-f])+"/>
    <xs:maxLength value="8"/>
  </xs:restriction>
</xs:simpleType>

<xs:element name="memory_address"
    type="x:memory_address_type"
    x:use="required"
    x:default="00000000">
</code>```

XML:

```<code><memory_address>4FFF</memory_address>
</code>```

How should I write the XSD in order to restrict the XML entry to only have a range (minimum and maximum) from 40000 to 47FFF or from 0000 to FFFF?

答:
In XML, the only numeric datatype for hexadecimal numbers is xsd:hexBinary, however, this allows two hexadecimal digits only (to represent a sequence of octets). Therefore, the only way to describe arbitrary hexadecimal values is to use the xsd:string datatype with pattern restrictions, as seen in the question, but strings cannot have numerical ranges for permissible values, only numbers can.

Of course, you can define the permissible characters one by one, and whenever possible, in groups (depending on the range), e.g., 4[A-F0-9]{4} or 40-7. However, defining regex string patterns for hexadecimal digits is not only tedious, but it loses the semantics of the corresponding numbers.

Body:
I would like to restrict the range of a hexadecimal memory address value in an XML document using a schema. The xml hexadecimal entry has to be in string format as it is parsed from a GUI textbox and directly saved to the XML document after it is validated with the schema document.

I have this.

XSD:

<xs:simpleType name="memory_address_type">
  <xs:restriction base="xs:string">
    <xs:pattern value="([0-9A-Fa-f])+"/>
    <xs:maxLength value="8"/>
  </xs:restriction>
</xs:simpleType>

<xs:element name="memory_address"
    type="x:memory_address_type"
    x:use="required"
    x:default="00000000">

XML:

<memory_address>4FFF</memory_address>

How should I write the XSD in order to restrict the XML entry to only have a range (minimum and maximum) from 40000 to 47FFF or from 0000 to FFFF?


问:
How to reload fetchedResultsController on viewWillAppear?
How to reload fetchedResultsController on viewWillAppear? because I want to reload the table view and data after I dismiss a pop out view controller.

This fetch controller seem only run when the view is load because It keep the old data. How to run or refresh the fetch controller when the view is appear?

```<code>var fetchedResultsController: NSFetchedResultsController<Record> {
    if _fetchedResultsController != nil {
        return _fetchedResultsController!
    }

    let fetchRequest: NSFetchRequest<Record> = Record.fetchRequest()
    fetchRequest.fetchBatchSize = 20
    let accBtn = UserDefaults().value(forKey: "BtnName") as! String
    let sortDescriptor = NSSortDescriptor(key: "createdAt", ascending: false)
    fetchRequest.sortDescriptors = [sortDescriptor]
    fetchRequest.predicate = NSPredicate(format: "%K == %@", "accountbook" , "\(accBtn)")
    let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: "createdAt", cacheName: nil)
    aFetchedResultsController.delegate = self
    _fetchedResultsController = aFetchedResultsController

    do {
        try _fetchedResultsController!.performFetch()
    } catch {
        let nserror = error as NSError
        fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
    }

    return _fetchedResultsController!
}

var _fetchedResultsController: NSFetchedResultsController<Record>? = nil

func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
    self.tableView.beginUpdates()
}

func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) {
    switch type {
    case .insert:
        self.tableView.insertSections(IndexSet(integer: sectionIndex), with: .fade)
    case .delete:
        self.tableView.deleteSections(IndexSet(integer: sectionIndex), with: .fade)
    default:
        return
    }
}

func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
    switch type {
    case .insert:
        tableView.insertRows(at: [newIndexPath!], with: .fade)
    case .delete:
        tableView.deleteRows(at: [indexPath!], with: .fade)
    case .update:
        self.configureCell(tableView.cellForRow(at: indexPath!)! as! DashboardCell, withRecordItem: anObject as! Record)
    case .move:
        tableView.moveRow(at: indexPath!, to: newIndexPath!)
    }
}

func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
    self.tableView.endUpdates()
}
</code>```

答:
If your ViewController is in memory when you change the data in the managed object context, the fetched result controller delegates should  work.

In your current implementation, you are updating the tableview when each change is made and its not always advisable to do it. I guess you need to digress and implement only didChangeContent and reloadData on it

```<code>func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
    self.tableView.reloadData()
}
</code>```

Body:
How to reload fetchedResultsController on viewWillAppear? because I want to reload the table view and data after I dismiss a pop out view controller.

This fetch controller seem only run when the view is load because It keep the old data. How to run or refresh the fetch controller when the view is appear?

var fetchedResultsController: NSFetchedResultsController<Record> {
    if _fetchedResultsController != nil {
        return _fetchedResultsController!
    }

    let fetchRequest: NSFetchRequest<Record> = Record.fetchRequest()
    fetchRequest.fetchBatchSize = 20
    let accBtn = UserDefaults().value(forKey: "BtnName") as! String
    let sortDescriptor = NSSortDescriptor(key: "createdAt", ascending: false)
    fetchRequest.sortDescriptors = [sortDescriptor]
    fetchRequest.predicate = NSPredicate(format: "%K == %@", "accountbook" , "\(accBtn)")
    let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: "createdAt", cacheName: nil)
    aFetchedResultsController.delegate = self
    _fetchedResultsController = aFetchedResultsController

    do {
        try _fetchedResultsController!.performFetch()
    } catch {
        let nserror = error as NSError
        fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
    }

    return _fetchedResultsController!
}

var _fetchedResultsController: NSFetchedResultsController<Record>? = nil

func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
    self.tableView.beginUpdates()
}

func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) {
    switch type {
    case .insert:
        self.tableView.insertSections(IndexSet(integer: sectionIndex), with: .fade)
    case .delete:
        self.tableView.deleteSections(IndexSet(integer: sectionIndex), with: .fade)
    default:
        return
    }
}

func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
    switch type {
    case .insert:
        tableView.insertRows(at: [newIndexPath!], with: .fade)
    case .delete:
        tableView.deleteRows(at: [indexPath!], with: .fade)
    case .update:
        self.configureCell(tableView.cellForRow(at: indexPath!)! as! DashboardCell, withRecordItem: anObject as! Record)
    case .move:
        tableView.moveRow(at: indexPath!, to: newIndexPath!)
    }
}

func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
    self.tableView.endUpdates()
}

Body:
If your ViewController is in memory when you change the data in the managed object context, the fetched result controller delegates should  work.

In your current implementation, you are updating the tableview when each change is made and its not always advisable to do it. I guess you need to digress and implement only didChangeContent and reloadData on it

func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
    self.tableView.reloadData()
}


问:
Javascript typewriter does not write and backspace properly
I have written a simple JavaScript/jQuery typewriter with backspacing, which loops through several messages (& a background image).

The problem I'm facing is that as the functions loop, they are not written out properly - missing several of the characters.

i.e. my array is [everyone, dog owners, the diet-conscious, workers, families] but what will get written in turn is: ryone, g owners, diet-conscious, (blank), families.

I think the problem could be that a variable somewhere is not being reset properly or the length is being worked out from the previous message - possible scoping issues.

On Codepen: https://codepen.io/nathankeenmelb/pen/MOovXJ?editors=0010

The relevant HTML

There's something for everyone.

```

<p><strong>The JS, with jQuery</strong></p>

<pre class="lang-js prettyprint-override"><code>let messages = [
  " everyone.",
  " dog owners.",
  " the diet-conscious.",
  " workers.",
  " families."
];
let images = [
  "url(https://via.placeholder.com/200x100)",
  "url(https://via.placeholder.com/400x100)",
  "url(https://via.placeholder.com/400x200)",
  "url(https://via.placeholder.com/400x300)",
  "url(https://via.placeholder.com/400x400)"
];

let loopDuration = 3000;

function displayImages(arr){
  //Loop through other images, but start at second item
    let j = 1;
    setInterval( //evaluates every x ms
        function(){
            $('body').css("background-image",arr[j]);
            j++;
          console.log('j in image = ' + j);
          //Reset loop after been through them all to repeat
            if(j >= images.length) j = 0;
          //Interval length in ms
        }, loopDuration);
}

function displayMessages() {

  //CHANGE THE MESSAGE -starting the loop
    let i = 0;
    setInterval( //evaluates every x ms
        function(){
            //TYPEWRITE MESSAGE
            let char = 0;
            function typeWriter() {
              //for as long as the current character length is less than the full character length

              if (char < messages[i].length) {
                //Add the next character to the html
                document.getElementById("message").innerHTML += messages[i].charAt(char);

                //Go to next character
                char++;
                //Wait x ms to write next character
                setTimeout(typeWriter, 50);
              }

            } //end typewriter()

          //Run the function
          typeWriter();

          //START BACKSPACE
          let theMessage = document.getElementById("message").innerHTML;
          let bchar = theMessage.length;

          function backSpacer() {
            if (bchar > 0) {
              theMessage = theMessage.slice(0,-1);
              document.getElementById("message").innerHTML = theMessage;
              bchar--;
              //Run the function again, after x m
              setTimeout(backSpacer, 25);
            }
          }
          //Run the function
          backSpacer();

          //If instead of using backspacer() I deleted the text as follows, that worked fine
          //$('#message').text('');
          //document.getElementById("message").innerHTML = "";

          //Having typed it all out, backspaced it, go to the next message
          i++;

          //Having gone through each message, reset loop to repeat, to 0 to include the original
            if(i >= messages.length) i = 0;
          //Interval length in ms
        }, loopDuration);

}

//Wait till the whole page loads
window.onload = function loadChanges() {
  setTimeout(function() {
    //Run whatever after time elapses
    displayImages(images);
    displayMessages();
    //Wait x ms after page loads
  }, 1000)
};
</code>```

答:
I looked at your code a bit. It seems to me like you were running both typeWriter and backSpacer at the same time.

Your code had this structure (I've simplified it a lot):

```<code>setInterval(function(){
  function typeWriter() {
    if (char < messages[i].length) {
      char++;
      setTimeout(typeWriter, 50);
    }

  }

  typeWriter();

  let bchar = theMessage.length;

  function backSpacer() {
    if (bchar > 0) {
      bchar--;
      setTimeout(backSpacer, 25);
    }
  }

  backSpacer();
}, loopDuration);
</code>```

As you can see you call both typeWriter and backSpacer. The setTimeout will cause these methods to run "in parallel" and therefore remove and add letters at the same time causing the message to be messed up.

I created a working example that is more of a state machine. Meaning that it will first type the message. When that is done it will switch to erasing the message. And when that is done it will wait to restart.

The code isn't great, but it sorta works and might help you get to a working solution. Let me know in the comments if you have any questions.

https://codepen.io/andreasmcdermott/pen/ZaXXyK?editors=0010

Body:
I have written a simple JavaScript/jQuery typewriter with backspacing, which loops through several messages (& a background image).

The problem I'm facing is that as the functions loop, they are not written out properly - missing several of the characters.

i.e. my array is [everyone, dog owners, the diet-conscious, workers, families] but what will get written in turn is: ryone, g owners, diet-conscious, (blank), families.

I think the problem could be that a variable somewhere is not being reset properly or the length is being worked out from the previous message - possible scoping issues.

On Codepen: https://codepen.io/nathankeenmelb/pen/MOovXJ?editors=0010

The relevant HTML

There's something for everyone.

The JS, with jQuery

let messages = [
  " everyone.",
  " dog owners.",
  " the diet-conscious.",
  " workers.",
  " families."
];
let images = [
  "url(https://via.placeholder.com/200x100)",
  "url(https://via.placeholder.com/400x100)",
  "url(https://via.placeholder.com/400x200)",
  "url(https://via.placeholder.com/400x300)",
  "url(https://via.placeholder.com/400x400)"
];

let loopDuration = 3000;

function displayImages(arr){
  //Loop through other images, but start at second item
    let j = 1;
    setInterval( //evaluates every x ms
        function(){
            $('body').css("background-image",arr[j]);
            j++;
          console.log('j in image = ' + j);
          //Reset loop after been through them all to repeat
            if(j >= images.length) j = 0;
          //Interval length in ms
        }, loopDuration);
}

function displayMessages() {

  //CHANGE THE MESSAGE -starting the loop
    let i = 0;
    setInterval( //evaluates every x ms
        function(){
            //TYPEWRITE MESSAGE
            let char = 0;
            function typeWriter() {
              //for as long as the current character length is less than the full character length

              if (char < messages[i].length) {
                //Add the next character to the html
                document.getElementById("message").innerHTML += messages[i].charAt(char);

                //Go to next character
                char++;
                //Wait x ms to write next character
                setTimeout(typeWriter, 50);
              }

            } //end typewriter()

          //Run the function
          typeWriter();

          //START BACKSPACE
          let theMessage = document.getElementById("message").innerHTML;
          let bchar = theMessage.length;

          function backSpacer() {
            if (bchar > 0) {
              theMessage = theMessage.slice(0,-1);
              document.getElementById("message").innerHTML = theMessage;
              bchar--;
              //Run the function again, after x m
              setTimeout(backSpacer, 25);
            }
          }
          //Run the function
          backSpacer();

          //If instead of using backspacer() I deleted the text as follows, that worked fine
          //$('#message').text('');
          //document.getElementById("message").innerHTML = "";

          //Having typed it all out, backspaced it, go to the next message
          i++;

          //Having gone through each message, reset loop to repeat, to 0 to include the original
            if(i >= messages.length) i = 0;
          //Interval length in ms
        }, loopDuration);

}

//Wait till the whole page loads
window.onload = function loadChanges() {
  setTimeout(function() {
    //Run whatever after time elapses
    displayImages(images);
    displayMessages();
    //Wait x ms after page loads
  }, 1000)
};

Body:
I looked at your code a bit. It seems to me like you were running both typeWriter and backSpacer at the same time.

Your code had this structure (I've simplified it a lot):

setInterval(function(){
  function typeWriter() {
    if (char < messages[i].length) {
      char++;
      setTimeout(typeWriter, 50);
    }

  }

  typeWriter();

  let bchar = theMessage.length;

  function backSpacer() {
    if (bchar > 0) {
      bchar--;
      setTimeout(backSpacer, 25);
    }
  }

  backSpacer();
}, loopDuration);

As you can see you call both typeWriter and backSpacer. The setTimeout will cause these methods to run "in parallel" and therefore remove and add letters at the same time causing the message to be messed up.

I created a working example that is more of a state machine. Meaning that it will first type the message. When that is done it will switch to erasing the message. And when that is done it will wait to restart.

The code isn't great, but it sorta works and might help you get to a working solution. Let me know in the comments if you have any questions.

https://codepen.io/andreasmcdermott/pen/ZaXXyK?editors=0010


问:
Any good strategies for dealing with 'not reproducible' bugs?
Very often you will get or submit bug reports for defects that are 'not reproducible'. They may be reproducible on your computer or software project, but not on a vendor's system. Or the user supplies steps to reproduce, but you can't see the defect locally. Many variations on this scenario of course, so to simplify I guess what I'm trying to learn is:

What is your company's policy towards 'not reproducible' bugs? Shelve them, close them, ignore? I occasionally see intermittent, non reproducible bugs in 3-rd party frameworks, and these are pretty much always closed instantly by the vendor... but they are real bugs.

Have you found any techniques that help in fixing these types of bugs? Usually what I do is get a system info report from the user, and steps to reproduce, then search on keywords, and try to see any sort of pattern.

答:
The accepted answer is the best general approach. At a high level, it's worth weighing the importance of fixing the bug against what you could add as a feature or enhance that would benefit the user. Could a 'non-reproducible' bug take two days to fix? Could a feature be added in that time that gives users more benefit than that bug fix? Maybe the users would prefer the feature. I've been fixated at times as a developer on imperfections I can see, and then users are asked for feedback and none of them actually mention the bug(s) that I can see, but the software is missing a feature that they really want!

Sometimes, simple persistence in attempting to reproduce the bug whilst debugging can be the most effective approach. For this strategy to work, the bug needs to be 'intermittent' rather than completely 'non-reproducible'. If you can repeat a bug even one time in 10, and you have ideas about the most likely place it's occurring, you can place breakpoints at those points then doggedly attempt to repeat the bug and see exactly what's going on. I've experienced this to be more effective than logging in one or two cases (although logging would be my first go-to in general).

ContentLicense: CC BY-SA 2.5


问:
adding properties to custom classes
I'm trying to create my own UIImageView handler. I managed to subclass the touch events necessary. I haven't figured out how to add my own properties. I'd like to add a UIColor property to set the stroke color for my handlers. Here's the .h file.

```<code>//
//  imageViewController.h
//  slate
//
//  Created by House of Pawn on 11/15/17.
//  Copyright © 2017 ma. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface imageViewController : UIImageView

@end
</code>```

Here's the .m file

```<code>//
//  imageViewController.m
//  slate
//
//  Created by House of Pawn on 11/15/17.
//  Copyright © 2017 ma. All rights reserved.
//

#import "imageViewController.h"

@interface imageViewController ()

@end

@implementation imageViewController
CGPoint lastPoint;
CGFloat red;
CGFloat green;

NSString const *key = @"my.very.unique.key";

CGFloat blue;
CGFloat brush;
CGFloat opacity;
UIColor* strokeColor;
BOOL mouseSwiped;

- (void)viewDidLoad {
  //  [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
 //   [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{

    mouseSwiped = NO;

    UITouch *touch = [touches anyObject];
    lastPoint = [touch locationInView:self];

    NSLog(@"Touches Began");
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

    mouseSwiped = YES;
    UITouch *touch = [touches anyObject];
    CGPoint currentPoint = [touch locationInView:self];

    UIGraphicsBeginImageContext(self.frame.size);

    [self.image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
    CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
    CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
    CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 30.0 );

    CGFloat* components = CGColorGetComponents(_strokeColor.CGColor);

    CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), components[0], components[1], components[2], 1.0);
    CGContextSetBlendMode(UIGraphicsGetCurrentContext(),kCGBlendModeNormal);

    CGContextStrokePath(UIGraphicsGetCurrentContext());
    self.image = UIGraphicsGetImageFromCurrentImageContext();
    [self setAlpha:1.0];
    UIGraphicsEndImageContext();

    lastPoint = currentPoint;
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

    if(!mouseSwiped) {
        UIGraphicsBeginImageContext(self.frame.size);
        [self.image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
        CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
        CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 14.0);
        CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0, 1, 0, 1);
        CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
        CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
        CGContextStrokePath(UIGraphicsGetCurrentContext());
        CGContextFlush(UIGraphicsGetCurrentContext());
        self.image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }

}

@end
</code>```

I need to be able to pass my custom UIImageView controller class a UIColor like I said above. The variable i'd like to use is stroke color. I've seen posts about using categories but they make no sense to me. If someone can help me implement this it'd be great.

答:
To Customise the control, you should use IBInspectable & IBDesignable

For Objective C:
use this Link : https://useyourloaf.com/blog/ib-designable-custom-views-in-interface-builder/

```<code>#import <UIKit/UIKit.h>

IB_DESIGNABLE

@interface imageViewController : UIImageView

@property (nonatomic) IBInspectable UIColor *strokeColor;

@end
</code>```

For Swift:
use this Link: http://nshipster.com/ibinspectable-ibdesignable/

```<code>@IBInspectable var strokeColor: UIColor? {
   didSet {
       layer.borderColor = borderColor?.CGColor
   }
}
</code>```

Thank You.

Title: adding properties to custom classes

Body:
I'm trying to create my own UIImageView handler. I managed to subclass the touch events necessary. I haven't figured out how to add my own properties. I'd like to add a UIColor property to set the stroke color for my handlers. Here's the .h file.

//
//  imageViewController.h
//  slate
//
//  Created by House of Pawn on 11/15/17.
//  Copyright © 2017 ma. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface imageViewController : UIImageView

@end

Here's the .m file

//
//  imageViewController.m
//  slate
//
//  Created by House of Pawn on 11/15/17.
//  Copyright © 2017 ma. All rights reserved.
//

#import "imageViewController.h"

@interface imageViewController ()

@end

@implementation imageViewController
CGPoint lastPoint;
CGFloat red;
CGFloat green;

NSString const *key = @"my.very.unique.key";

CGFloat blue;
CGFloat brush;
CGFloat opacity;
UIColor* strokeColor;
BOOL mouseSwiped;

- (void)viewDidLoad {
  //  [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
 //   [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{

    mouseSwiped = NO;

    UITouch *touch = [touches anyObject];
    lastPoint = [touch locationInView:self];

    NSLog(@"Touches Began");
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

    mouseSwiped = YES;
    UITouch *touch = [touches anyObject];
    CGPoint currentPoint = [touch locationInView:self];

    UIGraphicsBeginImageContext(self.frame.size);

    [self.image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
    CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
    CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
    CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 30.0 );

    CGFloat* components = CGColorGetComponents(_strokeColor.CGColor);

    CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), components[0], components[1], components[2], 1.0);
    CGContextSetBlendMode(UIGraphicsGetCurrentContext(),kCGBlendModeNormal);

    CGContextStrokePath(UIGraphicsGetCurrentContext());
    self.image = UIGraphicsGetImageFromCurrentImageContext();
    [self setAlpha:1.0];
    UIGraphicsEndImageContext();

    lastPoint = currentPoint;
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

    if(!mouseSwiped) {
        UIGraphicsBeginImageContext(self.frame.size);
        [self.image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
        CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
        CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 14.0);
        CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0, 1, 0, 1);
        CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
        CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
        CGContextStrokePath(UIGraphicsGetCurrentContext());
        CGContextFlush(UIGraphicsGetCurrentContext());
        self.image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }

}

@end

I need to be able to pass my custom UIImageView controller class a UIColor like I said above. The variable i'd like to use is stroke color. I've seen posts about using categories but they make no sense to me. If someone can help me implement this it'd be great.

Body:
To Customise the control, you should use IBInspectable & IBDesignable

For Objective C:
use this Link : https://useyourloaf.com/blog/ib-designable-custom-views-in-interface-builder/

#import <UIKit/UIKit.h>

IB_DESIGNABLE

@interface imageViewController : UIImageView

@property (nonatomic) IBInspectable UIColor *strokeColor;

@end

For Swift:
use this Link: http://nshipster.com/ibinspectable-ibdesignable/

@IBInspectable var strokeColor: UIColor? {
   didSet {
       layer.borderColor = borderColor?.CGColor
   }
}

Thank You.


问:
Converting socket.io data to JSON in Swift
I'm writing a socket.io client and I'm having trouble getting the emitted data into any usable format.

My handler is:

```<code>socket.on("foriEvent") { data, ack in
    print(data)
}
</code>```

which prints:

```<code>[
   {
      "foriEvent":{
         "eventType":"location",
         "state":"moving",
         "latitude":"60.4413407",
         "longitude":"22.2476208",
         "accuracy":"20",
         "ts":1510653600189
      }
   }
]
</code>```

I have a Struct that "looks" like that data, and I would like to use something like this where the from object is of type Data.

```<code>let decoder = JSONDecoder()
let foriEvent = try decoder.decode(ForiEvent.self, from: data)
</code>```

Currently I'm using the following to get a Data object, but when I send it to decoder.decode, I get the following error message:

```<code>return try JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.prettyPrinted)
</code>```

```<code>error trying to convert data to JSON typeMismatch(Swift.Dictionary<Swift.String, Any>,
Swift.DecodingError.Context(codingPath: [], debugDescription:
"Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))
</code>```

Could it be my struct? What should it look like? The Struct looks like this right now:

```<code>struct ForiEvent : Codable {
    var eventType: String?
    var state : String?
    var latitude: String?
    var longitude : String?
    var accuracy : String?
    var timeStamp : CLong?
}

struct ForiData : Codable {
    var foriEvent : ForiEvent?
}
</code>```

答:
I think there is no need to implement any third party (BTW I'm not againsed to SwiftyJson or any other).
You can do it as: </p>

```<code>//Here is the new struct for your ForiEvent
struct ForiEvent {
var eventType: String?
var state : String?
var latitude: String?
var longitude : String?
var accuracy : String?
var timeStamp : CLong?

init(dict: [String:Any]) {
    if let obj = dict["eventType"] {
        eventType = "\(obj)"
    }

    if let obj = dict["state"] {
        state = "\(obj)"
    }

    if let obj = dict["latitude"] {
        latitude = "\(obj)"
    }

    if let obj = dict["longitude"] {
        longitude = "\(obj)"
    }

    if let obj = dict["accuracy"] {
        accuracy = "\(obj)"
    }

    if let obj = dict["timeStamp"] as? CLong {
        timeStamp = obj
    }
}
}

//You data as [[String:Any]] returend from on complitionhandler
let dictArray:[[String:Any]] = [[
"foriEvent":[
    "eventType" : "location",
    "state":"moving",
    "latitude":"60.4413407",
    "longitude":"22.2476208",
    "accuracy":"20",
    "ts":1510653600189
]
]
]

print(dictArray)

// How to Use it:
var foriEventArray = [ForiEvent]()
for eventData in dictArray {
if let eventDict = eventData["foriEvent"] as? [String:Any] {
    foriEventArray.append(ForiEvent(dict: eventDict))
}
}
print(foriEventArray)
</code>```

Body:
I'm writing a socket.io client and I'm having trouble getting the emitted data into any usable format.

My handler is:

socket.on("foriEvent") { data, ack in
    print(data)
}

which prints:

[
   {
      "foriEvent":{
         "eventType":"location",
         "state":"moving",
         "latitude":"60.4413407",
         "longitude":"22.2476208",
         "accuracy":"20",
         "ts":1510653600189
      }
   }
]

I have a Struct that "looks" like that data, and I would like to use something like this where the from object is of type Data.

let decoder = JSONDecoder()
let foriEvent = try decoder.decode(ForiEvent.self, from: data)

Currently I'm using the following to get a Data object, but when I send it to decoder.decode, I get the following error message:

return try JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.prettyPrinted)

error trying to convert data to JSON typeMismatch(Swift.Dictionary<Swift.String, Any>,
Swift.DecodingError.Context(codingPath: [], debugDescription:
"Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))

Could it be my struct? What should it look like? The Struct looks like this right now:

struct ForiEvent : Codable {
    var eventType: String?
    var state : String?
    var latitude: String?
    var longitude : String?
    var accuracy : String?
    var timeStamp : CLong?
}

struct ForiData : Codable {
    var foriEvent : ForiEvent?
}

Body:
I think there is no need to implement any third party (BTW I'm not againsed to SwiftyJson or any other).
You can do it as:

//Here is the new struct for your ForiEvent
struct ForiEvent {
var eventType: String?
var state : String?
var latitude: String?
var longitude : String?
var accuracy : String?
var timeStamp : CLong?

init(dict: [String:Any]) {
    if let obj = dict["eventType"] {
        eventType = "\(obj)"
    }

    if let obj = dict["state"] {
        state = "\(obj)"
    }

    if let obj = dict["latitude"] {
        latitude = "\(obj)"
    }

    if let obj = dict["longitude"] {
        longitude = "\(obj)"
    }

    if let obj = dict["accuracy"] {
        accuracy = "\(obj)"
    }

    if let obj = dict["timeStamp"] as? CLong {
        timeStamp = obj
    }
}
}

//You data as [[String:Any]] returend from on complitionhandler
let dictArray:[[String:Any]] = [[
"foriEvent":[
    "eventType" : "location",
    "state":"moving",
    "latitude":"60.4413407",
    "longitude":"22.2476208",
    "accuracy":"20",
    "ts":1510653600189
]
]
]

print(dictArray)

// How to Use it:
var foriEventArray = [ForiEvent]()
for eventData in dictArray {
if let eventDict = eventData["foriEvent"] as? [String:Any] {
    foriEventArray.append(ForiEvent(dict: eventDict))
}
}
print(foriEventArray)


问:
What's wrong if compiler optimization is turned on in debug build?
Why is it necessary/recommended to turn off all compiler optimizations when debugging application?

Background

I'm working in an 8-bit micro controller (OKI 411) which has 15K usable code memory space for interrupt service routines + ROM region/window (const global variables) + code. We nearly eat up ~13K so it is very tempting to turn on maximum possible optimization during even debugging.

答:
Consider:

```<code>for (i = 0; i < 10; i++) {
    src[i] = dest[i];
}
</code>```

After optimization, this code might look like:

```<code>src[0] = dest[0];
src[1] = dest[1];
⋮
src[9] = dest[9];
</code>```

In other words, there's no i anymore. The debugger would expect i to be on the stack frame, but the optimizer removed it.

Also, when stepping, the PC will jump all over the place (apparently randomly), and you will encounter various other weirdness that will make debugging very difficult or impossible (depending on what the optimizer did).

Body:
Consider:

for (i = 0; i < 10; i++) {
    src[i] = dest[i];
}

After optimization, this code might look like:

src[0] = dest[0];
src[1] = dest[1];
⋮
src[9] = dest[9];

In other words, there's no i anymore. The debugger would expect i to be on the stack frame, but the optimizer removed it.

Also, when stepping, the PC will jump all over the place (apparently randomly), and you will encounter various other weirdness that will make debugging very difficult or impossible (depending on what the optimizer did).


问:
Subtract t1 from t2 then add it to already exist t3 and display in t3 in javascript
I want txtFirstNumberValue - txtSecondNumberValue and then add it already exists txtThirdNumberValue value but in my case, it is not working.

function sub() {
    var txtFirstNumberValue = document.getElementById('payment_image').value;
    var txtSecondNumberValue = document.getElementById('pay_amount').value;
    var txtThirdNumberValue = document.getElementById('pay_balance').value;
    if (txtFirstNumberValue == "")
     txtFirstNumberValue = 0;
   if (txtSecondNumberValue == "")
     txtSecondNumberValue = 0;
   var result = parseInt(txtFirstNumberValue) - parseInt(txtSecondNumberValue);

   if (!isNaN(result)) {
    document.getElementById('pay_balance').value += result;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <div class="input-box">
   <span>Amount</span>
   <input placeholder="Payment Amount" type="text" name="payment_image" onkeyup="sub();"  id="payment_image" class="number">
 </div>
 <div class="input-box">
   <span>Expences</span>
   <input placeholder="Expenses" type="text" name="expenses" id="pay_amount" onkeyup="sub();"  class="number">
 </div>
 <div class="input-box">
   <span>Balance</span>
   <input placeholder="Balance" value="15" readonly="readonly" type="text" name="pay_balance" id="pay_balance"   class="number">
 </div></code>```

txtThirdNumberValue is coming dynamically from PHP code

答:
You need to convert already existing value from string to number before adding result to it. Here's how to do it:

function sub() {
    var txtFirstNumberValue = document.getElementById('payment_image').value;
    var txtSecondNumberValue = document.getElementById('pay_amount').value;
    var txtThirdNumberValue = document.getElementById('pay_balance').value;
    if (txtFirstNumberValue == "")
     txtFirstNumberValue = 0;
   if (txtSecondNumberValue == "")
     txtSecondNumberValue = 0;
   var result = parseInt(txtFirstNumberValue) - parseInt(txtSecondNumberValue);

   if (!isNaN(result)) {
    var existing = parseInt(document.getElementById('pay_balance').value);
    var newResult = result + existing;
    document.getElementById('pay_balance').value = newResult;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <div class="input-box">
   <span>Amount</span>
   <input placeholder="Payment Amount" type="text" name="payment_image" onkeyup="sub();"  id="payment_image" class="number">
 </div>
 <div class="input-box">
   <span>Expences</span>
   <input placeholder="Expenses" type="text" name="expenses" id="pay_amount" onkeyup="sub();"  class="number">
 </div>
 <div class="input-box">
   <span>Balance</span>
   <input placeholder="Balance" value="15" readonly="readonly" type="text" name="pay_balance" id="pay_balance"   class="number">
 </div></code>```

Body:
I want txtFirstNumberValue - txtSecondNumberValue and then add it already exists txtThirdNumberValue value but in my case, it is not working.

function sub() {
    var txtFirstNumberValue = document.getElementById('payment_image').value;
    var txtSecondNumberValue = document.getElementById('pay_amount').value;
    var txtThirdNumberValue = document.getElementById('pay_balance').value;
    if (txtFirstNumberValue == "")
     txtFirstNumberValue = 0;
   if (txtSecondNumberValue == "")
     txtSecondNumberValue = 0;
   var result = parseInt(txtFirstNumberValue) - parseInt(txtSecondNumberValue);

   if (!isNaN(result)) {
    document.getElementById('pay_balance').value += result;
  }
}

   Amount
   <input placeholder="Payment Amount" type="text" name="payment_image" onkeyup="sub();"  id="payment_image" class="number">

   Expences
   <input placeholder="Expenses" type="text" name="expenses" id="pay_amount" onkeyup="sub();"  class="number">

   Balance
   <input placeholder="Balance" value="15" readonly="readonly" type="text" name="pay_balance" id="pay_balance"   class="number">

txtThirdNumberValue is coming dynamically from PHP code

Body:
You need to convert already existing value from string to number before adding result to it. Here's how to do it:

function sub() {
    var txtFirstNumberValue = document.getElementById('payment_image').value;
    var txtSecondNumberValue = document.getElementById('pay_amount').value;
    var txtThirdNumberValue = document.getElementById('pay_balance').value;
    if (txtFirstNumberValue == "")
     txtFirstNumberValue = 0;
   if (txtSecondNumberValue == "")
     txtSecondNumberValue = 0;
   var result = parseInt(txtFirstNumberValue) - parseInt(txtSecondNumberValue);

   if (!isNaN(result)) {
    var existing = parseInt(document.getElementById('pay_balance').value);
    var newResult = result + existing;
    document.getElementById('pay_balance').value = newResult;
  }
}

  <div class="input-box">
   <span>Amount</span>
   <input placeholder="Payment Amount" type="text" name="payment_image" onkeyup="sub();"  id="payment_image" class="number">
 </div>
 <div class="input-box">
   <span>Expences</span>
   <input placeholder="Expenses" type="text" name="expenses" id="pay_amount" onkeyup="sub();"  class="number">
 </div>
 <div class="input-box">
   <span>Balance</span>
   <input placeholder="Balance" value="15" readonly="readonly" type="text" name="pay_balance" id="pay_balance"   class="number">
 </div>


问:
How to make an async event run continuously?
I am creating a little console app that is just in proof-of-concept stage right now.  The idea is that it will query 3rd party API's for events on their end.  (That part is all working just fine).

When an event arrives, we need to stick the json string for that event into a sqlite db on our side.  At the same time, I need a process running in the same app that is continuously looking for records in the sqlite table, and when it finds one, it handles it.

Here's what I have so far... (again, this is just a proof of concept while I learn the basics of how to set this up)...

```<code>static void Main(string[] args)
{
    var t = CheckEventsAsync();
    while (true)
    {
        System.Threading.Thread.Sleep(5000);
        DataAccess.InsertData("INSERT INTO events(value) VALUES ('this is an event');");
    }
}

static private async Task CheckEventsAsync()
{
    DataTable dt = await DataAccess.LoadDataAsync("SELECT * FROM events");
    foreach (var dr in dt.Rows)
    {
        Console.WriteLine("got an event!");
    }
}
</code>```

The problem is that CheckEventsAsync() only ever fires once, and then when the 5 second timer goes off an a record is added to the table, nothing happens.

Am I going to need to use an EventHandler (with a delegate, etc) to make this work?  Or is it possible w/o doing it that way?

Thanks!

Oh, almost forgot... (this works in that it returns a data table if there is data, and null if not.  But I'm not sure I'm doing  it right for the overall goal)...

```<code>    public static async Task<DataTable> LoadDataAsync(string txtQuery)
    {
        var dataTable = new DataTable();
        var connection = new SQLiteConnection(_source);
        using (connection)
        {
            connection.Open();
            var command = connection.CreateCommand();
            command.CommandText = txtQuery;
            var task = await command.ExecuteReaderAsync();
            dataTable = new DataTable();
            dataTable.Load(task);
            connection.Close();
        }
        if (dataTable != null & dataTable.Rows.Count > 0)
            return dataTable;
        else
            return null;
    }
</code>```

EDIT

I see from the answers so far that I did a bad job of asking the question.  I need to have two processes running:

The first process will listen for 3rd party events and add them to the sqlite table.  This is simulated with the 5 second timer.  But in reality, there will not be a timer inside a While(true) loop.  It will be a WebSocket Listener.

The second process will watch for records in the database and handle them. So, CheckEventsAsync() needs to be a listener that triggers without the method being called.

The two need to operate within the same app, but independent of each other.

I hope I am making sense?

答:
Since all that is running in the same OS process - you don't need to constantly poll database for new events. Instead - use in-memory queue to which all producers push data and consumer, well, consumes. You can still insert data into sqlite table to handle the case when process crashes and some items are left unprocessed. Here is some code (for illustration purposes - in your real application you will not have Thread.Sleep and such of course):

```<code>class Program {
    static readonly BlockingCollection<ItemToProcess> _queue = new BlockingCollection<ItemToProcess>(new ConcurrentQueue<ItemToProcess>());
    static readonly CancellationTokenSource _cts = new CancellationTokenSource();

    static void Main(string[] args) {
        // get all unprocessed items from database here and insert into queue
        var producerThread = StartProducer(_cts.Token);
        var consumerThread = StartConsumer();
        Console.ReadKey();
        // cancel
        _cts.Cancel();
        // wait for producer thread to finish
        producerThread.Join();
        // notify there will be no more items
        _queue.CompleteAdding();
        // wait for consumer to finish
        consumerThread.Join();
    }

    static Thread StartProducer(CancellationToken ct) {
        var thread = new Thread(() => {
            while (!ct.IsCancellationRequested) {
                // also insert into database here
                _queue.Add(new ItemToProcess() {
                    Value = "value"
                });
                // imitate delay
                Thread.Sleep(5000);
            }
        }) {
            IsBackground = true
        };
        thread.Start();
        return thread;
    }

    static Thread StartConsumer() {
        var thread = new Thread(() => {
            foreach (var item in _queue.GetConsumingEnumerable()) {
                try {
                    // process
                    Console.WriteLine(item.Value);
                    // delete from database here
                }
                catch (Exception ex) {
                    // handle
                }
            }
        }) {
            IsBackground = true
        };
        thread.Start();
        return thread;
    }
}

class ItemToProcess
{
    public string Value { get; set; }
}
</code>```

Body:
I am creating a little console app that is just in proof-of-concept stage right now.  The idea is that it will query 3rd party API's for events on their end.  (That part is all working just fine).

When an event arrives, we need to stick the json string for that event into a sqlite db on our side.  At the same time, I need a process running in the same app that is continuously looking for records in the sqlite table, and when it finds one, it handles it.

Here's what I have so far... (again, this is just a proof of concept while I learn the basics of how to set this up)...

static void Main(string[] args)
{
    var t = CheckEventsAsync();
    while (true)
    {
        System.Threading.Thread.Sleep(5000);
        DataAccess.InsertData("INSERT INTO events(value) VALUES ('this is an event');");
    }
}

static private async Task CheckEventsAsync()
{
    DataTable dt = await DataAccess.LoadDataAsync("SELECT * FROM events");
    foreach (var dr in dt.Rows)
    {
        Console.WriteLine("got an event!");
    }
}

The problem is that CheckEventsAsync() only ever fires once, and then when the 5 second timer goes off an a record is added to the table, nothing happens.

Am I going to need to use an EventHandler (with a delegate, etc) to make this work?  Or is it possible w/o doing it that way?

Thanks!

Oh, almost forgot... (this works in that it returns a data table if there is data, and null if not.  But I'm not sure I'm doing  it right for the overall goal)...

    public static async Task<DataTable> LoadDataAsync(string txtQuery)
    {
        var dataTable = new DataTable();
        var connection = new SQLiteConnection(_source);
        using (connection)
        {
            connection.Open();
            var command = connection.CreateCommand();
            command.CommandText = txtQuery;
            var task = await command.ExecuteReaderAsync();
            dataTable = new DataTable();
            dataTable.Load(task);
            connection.Close();
        }
        if (dataTable != null & dataTable.Rows.Count > 0)
            return dataTable;
        else
            return null;
    }

EDIT

I see from the answers so far that I did a bad job of asking the question.  I need to have two processes running:

The first process will listen for 3rd party events and add them to the sqlite table.  This is simulated with the 5 second timer.  But in reality, there will not be a timer inside a While(true) loop.  It will be a WebSocket Listener.

The second process will watch for records in the database and handle them. So, CheckEventsAsync() needs to be a listener that triggers without the method being called.

The two need to operate within the same app, but independent of each other.

I hope I am making sense?

Body:
Since all that is running in the same OS process - you don't need to constantly poll database for new events. Instead - use in-memory queue to which all producers push data and consumer, well, consumes. You can still insert data into sqlite table to handle the case when process crashes and some items are left unprocessed. Here is some code (for illustration purposes - in your real application you will not have Thread.Sleep and such of course):

class Program {
    static readonly BlockingCollection<ItemToProcess> _queue = new BlockingCollection<ItemToProcess>(new ConcurrentQueue<ItemToProcess>());
    static readonly CancellationTokenSource _cts = new CancellationTokenSource();

    static void Main(string[] args) {
        // get all unprocessed items from database here and insert into queue
        var producerThread = StartProducer(_cts.Token);
        var consumerThread = StartConsumer();
        Console.ReadKey();
        // cancel
        _cts.Cancel();
        // wait for producer thread to finish
        producerThread.Join();
        // notify there will be no more items
        _queue.CompleteAdding();
        // wait for consumer to finish
        consumerThread.Join();
    }

    static Thread StartProducer(CancellationToken ct) {
        var thread = new Thread(() => {
            while (!ct.IsCancellationRequested) {
                // also insert into database here
                _queue.Add(new ItemToProcess() {
                    Value = "value"
                });
                // imitate delay
                Thread.Sleep(5000);
            }
        }) {
            IsBackground = true
        };
        thread.Start();
        return thread;
    }

    static Thread StartConsumer() {
        var thread = new Thread(() => {
            foreach (var item in _queue.GetConsumingEnumerable()) {
                try {
                    // process
                    Console.WriteLine(item.Value);
                    // delete from database here
                }
                catch (Exception ex) {
                    // handle
                }
            }
        }) {
            IsBackground = true
        };
        thread.Start();
        return thread;
    }
}

class ItemToProcess
{
    public string Value { get; set; }
}


问:
Highcharts 6.0.2: Overlapping labels
New to Highcharts, and was wondering if someone had a solution they'd developed for my issue. Finding when slices of my donut chart are small enough, their value labels overlap/impede on each other - has anyone found a solution before I go pulling it all apart? :)

Any advice appreciated!

答:
I ended up with a solution...

Originally I was using:

```<code>options: {
            chart: {
                height: 320,
                plotShadow: false,
                plotBorderWidth: 0,
                spacingBottom: 10,
                type: 'pie',
            },
            credits: {
                enabled: false
            },
            legend: {
                align: 'center',
                symbolRadius: 0,
                floating: true,
                layout: 'vertical',
                y: -110
            },
            tooltip: {
                enabled: false
            },
            title: {
                text: ''
            },
            subtitle: {
                text: ''
            },
            plotOptions: {
                pie: {
                    showInLegend: true,
                    startAngle: 45,
                    dataLabels: {
                        allowOverlap: false,
                        distance: 10,
                        padding: 2,
                        softConnector: true,
                        className: 'pieLabels ',
                        format: '{y}',
                        useHTML: true,
                        enabled: true
                    },
                    shadow: false,
                    center: ['50%', '50%'],
                    size: '90%',
                    innerSize: '65%',
                    borderColor: 'none'
                }
            },
            series: this.props.series
        }
</code>```

And ended up with :

```<code>options: {
            chart: {
                height: 320,
                plotShadow: false,
                plotBorderWidth: 0,
                spacingBottom: 10,
                type: 'pie',
            },
            credits: {
                enabled: false
            },
            legend: {
                align: 'center',
                symbolRadius: 0,
                floating: true,
                layout: 'vertical',
                y: -100
            },
            tooltip: {
                enabled: false
            },
            title: {
                text: ''
            },
            subtitle: {
                text: ''
            },
            plotOptions: {
                pie: {
                    showInLegend: true,
                    dataLabels: {
                        connectorWidth: 0,
                        distance: -25,
                        // overflow: 'none',
                        className: 'pieLabels ',
                        format: '{y}',
                        useHTML: true,
                        enabled: true
                    },
                    shadow: false,
                    center: ['50%', '50%'],
                    size: '100%',
                    innerSize: '60%',
                    borderColor: 'none',
                },
            },
            series: this.props.series
        }
</code>```

Which gave me :

Title: Highcharts 6.0.2: Overlapping labels

Body:
I ended up with a solution...

Originally I was using:

options: {
            chart: {
                height: 320,
                plotShadow: false,
                plotBorderWidth: 0,
                spacingBottom: 10,
                type: 'pie',
            },
            credits: {
                enabled: false
            },
            legend: {
                align: 'center',
                symbolRadius: 0,
                floating: true,
                layout: 'vertical',
                y: -110
            },
            tooltip: {
                enabled: false
            },
            title: {
                text: ''
            },
            subtitle: {
                text: ''
            },
            plotOptions: {
                pie: {
                    showInLegend: true,
                    startAngle: 45,
                    dataLabels: {
                        allowOverlap: false,
                        distance: 10,
                        padding: 2,
                        softConnector: true,
                        className: 'pieLabels ',
                        format: '{y}',
                        useHTML: true,
                        enabled: true
                    },
                    shadow: false,
                    center: ['50%', '50%'],
                    size: '90%',
                    innerSize: '65%',
                    borderColor: 'none'
                }
            },
            series: this.props.series
        }

And ended up with :

options: {
            chart: {
                height: 320,
                plotShadow: false,
                plotBorderWidth: 0,
                spacingBottom: 10,
                type: 'pie',
            },
            credits: {
                enabled: false
            },
            legend: {
                align: 'center',
                symbolRadius: 0,
                floating: true,
                layout: 'vertical',
                y: -100
            },
            tooltip: {
                enabled: false
            },
            title: {
                text: ''
            },
            subtitle: {
                text: ''
            },
            plotOptions: {
                pie: {
                    showInLegend: true,
                    dataLabels: {
                        connectorWidth: 0,
                        distance: -25,
                        // overflow: 'none',
                        className: 'pieLabels ',
                        format: '{y}',
                        useHTML: true,
                        enabled: true
                    },
                    shadow: false,
                    center: ['50%', '50%'],
                    size: '100%',
                    innerSize: '60%',
                    borderColor: 'none',
                },
            },
            series: this.props.series
        }

Which gave me :


问:
Awk Command analyze and explain
I have tried reading some tutorial about awk script, but still have doubt with below scripts:

```<code>get_value_from_ini()
{
    section=$1
    key_name=$2
    echo `awk -F '=' '/\['"$section"'\]/{a=1}a==1&&$1~/'"$key_name"'/{gsub(/[[:blank:]]*/,"",$2); print $2}' $cfg_file`
}

db_user=`get_value_from_ini DB DBUSER`
db_passwd=`get_value_from_ini DB DBPASSWD`
</code>```

And input config ini file like:

```<code>....
[DB]
DBUSER=dbuser
DBPASSWD=dbpasswd
...
</code>```

As I unserstand, in awk command, the pattern is "[DB]", and field seperator is '=', but it worked correctly and can return correct result, Why ? Could you help me understand it ?

Thanks a lot!

答:
Although poorly written code you simply read from left to right:

```<code>-F '='  -- As you have said, set FS to =

'/\'"$section"'\]/{a=1} -- If the line contains the information stored in variable section then set a=1

a==1 && $1~/'"$key_name"'/ -- If 'a' set and first field contains the information stored in variable key_name, execute all between {}

{gsub(/[[:blank:]]*/,"",$2); print $2}' -- If previous step returns true, remove all whitespace from second field and then print it out

$cfg_file -- file to be read
</code>```

Here is an alternative to get rid of all the extra quotes which make it very confusing to read and become possibly error prone:

```<code>get_value_from_ini()
{
  awk -F '=' -vsection="$1" -vkey_name="$2" '$0 ~ "["section"]"{a=1}a==1 && $1 ~ key_name{gsub(/[[:blank:]]*/,"",$2); print $2}' $cfg_file`
}
</code>```

Title: Awk Command analyze and explain

Body:
I have tried reading some tutorial about awk script, but still have doubt with below scripts:

get_value_from_ini()
{
    section=$1
    key_name=$2
    echo `awk -F '=' '/\['"$section"'\]/{a=1}a==1&&$1~/'"$key_name"'/{gsub(/[[:blank:]]*/,"",$2); print $2}' $cfg_file`
}

db_user=`get_value_from_ini DB DBUSER`
db_passwd=`get_value_from_ini DB DBPASSWD`

And input config ini file like:

....
[DB]
DBUSER=dbuser
DBPASSWD=dbpasswd
...

As I unserstand, in awk command, the pattern is "[DB]", and field seperator is '=', but it worked correctly and can return correct result, Why ? Could you help me understand it ?

Thanks a lot!

Body:
Although poorly written code you simply read from left to right:

-F '='  -- As you have said, set FS to =

'/\'"$section"'\]/{a=1} -- If the line contains the information stored in variable section then set a=1

a==1 && $1~/'"$key_name"'/ -- If 'a' set and first field contains the information stored in variable key_name, execute all between {}

{gsub(/[[:blank:]]*/,"",$2); print $2}' -- If previous step returns true, remove all whitespace from second field and then print it out

$cfg_file -- file to be read

Here is an alternative to get rid of all the extra quotes which make it very confusing to read and become possibly error prone:

get_value_from_ini()
{
  awk -F '=' -vsection="$1" -vkey_name="$2" '$0 ~ "["section"]"{a=1}a==1 && $1 ~ key_name{gsub(/[[:blank:]]*/,"",$2); print $2}' $cfg_file`
}


答:
I don't know what you are trying to do, but you should parseInt your 3rd value and then add it back.

Here is what you did wrong.

One more thing you should use radix value in your parseInt

function sub() {
    var txtFirstNumberValue = document.getElementById('payment_image').value;
    var txtSecondNumberValue = document.getElementById('pay_amount').value;
    var txtThirdNumberValue = document.getElementById('pay_balance').value;
    if (txtFirstNumberValue == "")
     txtFirstNumberValue = 0;
   if (txtSecondNumberValue == "")
     txtSecondNumberValue = 0;
   var result = parseInt(txtFirstNumberValue, 10) - parseInt(txtSecondNumberValue, 10);

   if (!isNaN(result)) {
    //This is what you should be doing. You didn't convert the value to int
    //You were concatinating it as a string
    var payVal = parseInt(document.getElementById('pay_balance').value, 10);
    payVal += result;
    document.getElementById('pay_balance').value = payVal;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <div class="input-box">
   <span>Amount</span>
   <input placeholder="Payment Amount" type="text" name="payment_image" onkeyup="sub();"  id="payment_image" class="number">
 </div>
 <div class="input-box">
   <span>Expences</span>
   <input placeholder="Expenses" type="text" name="expenses" id="pay_amount" onkeyup="sub();"  class="number">
 </div>
 <div class="input-box">
   <span>Balance</span>
   <input placeholder="Balance" value="15" readonly="readonly" type="text" name="pay_balance" id="pay_balance"   class="number">
 </div></code>```

Title: Subtract t1 from t2 then add it to already exist t3 and display in t3 in javascript

Body:
I don't know what you are trying to do, but you should parseInt your 3rd value and then add it back.

Here is what you did wrong.

One more thing you should use radix value in your parseInt

function sub() {
    var txtFirstNumberValue = document.getElementById('payment_image').value;
    var txtSecondNumberValue = document.getElementById('pay_amount').value;
    var txtThirdNumberValue = document.getElementById('pay_balance').value;
    if (txtFirstNumberValue == "")
     txtFirstNumberValue = 0;
   if (txtSecondNumberValue == "")
     txtSecondNumberValue = 0;
   var result = parseInt(txtFirstNumberValue, 10) - parseInt(txtSecondNumberValue, 10);

   if (!isNaN(result)) {
    //This is what you should be doing. You didn't convert the value to int
    //You were concatinating it as a string
    var payVal = parseInt(document.getElementById('pay_balance').value, 10);
    payVal += result;
    document.getElementById('pay_balance').value = payVal;
  }
}

  <div class="input-box">
   <span>Amount</span>
   <input placeholder="Payment Amount" type="text" name="payment_image" onkeyup="sub();"  id="payment_image" class="number">
 </div>
 <div class="input-box">
   <span>Expences</span>
   <input placeholder="Expenses" type="text" name="expenses" id="pay_amount" onkeyup="sub();"  class="number">
 </div>
 <div class="input-box">
   <span>Balance</span>
   <input placeholder="Balance" value="15" readonly="readonly" type="text" name="pay_balance" id="pay_balance"   class="number">
 </div>


问:
Using FORM.getPartsArray() in Lucee
Currently I'm working on a project to convert source code from ColdFusion to Lucee. I found an error occurs in Lucee, when using FORM.getPartArray(). Does Lucee have a similar function that can replace FORM.getPartArray()?

Example code:

```<code><cfset var fileExt = 'png'>
<cfset var tmpPartsArray = FORM.getPartsArray() />
<cfif IsDefined("tmpPartsArray")>
    <cfloop array="#tmpPartsArray#" index="local.tmpPart">
        <cfif local.tmpPart.isFile() AND local.tmpPart.getName() EQ arguments.formField>
            <cfset fileExt = ListLast(local.tmpPart.getFileName(), ".")>
        </cfif>
    </cfloop>
</cfif>
</code>```

答:
Not exactly.

FORM.getPartsArray() is proprietary to Adobe, in Lucee you can try FORM.getRaw() but you'll probably have to do some work.

getName() will match but I'm not sure about the other ones.

Title: Using FORM.getPartsArray() in Lucee

Body:
Currently I'm working on a project to convert source code from ColdFusion to Lucee. I found an error occurs in Lucee, when using FORM.getPartArray(). Does Lucee have a similar function that can replace FORM.getPartArray()?

Example code:

<cfset var fileExt = 'png'>
<cfset var tmpPartsArray = FORM.getPartsArray() />
<cfif IsDefined("tmpPartsArray")>
    <cfloop array="#tmpPartsArray#" index="local.tmpPart">
        <cfif local.tmpPart.isFile() AND local.tmpPart.getName() EQ arguments.formField>
            <cfset fileExt = ListLast(local.tmpPart.getFileName(), ".")>
        </cfif>
    </cfloop>
</cfif>


问:
How to change the color of the status bar in Android?
I would like to change the color of highlighted bar in Android Studio:

How can i do it?

答:
You can also add these lines of code in the main activity

```<code>if (Build.VERSION.SDK_INT >= 21)
{
getWindow().setStatusBarColor(ContextCompat.getColor(this,R.color.statusbar)); //status bar or the time bar at the top (see example image1)

getWindow().setNavigationBarColor(ContextCompat.getColor(this, R.color.dark_nav)); // Navigation bar the soft bottom of some phones like nexus and some Samsung note series  (see example image2)
}
</code>```

example image1 setStatusBarColor

example image2 setNavigationBarColor

Body:
You can also add these lines of code in the main activity

if (Build.VERSION.SDK_INT >= 21)
{
getWindow().setStatusBarColor(ContextCompat.getColor(this,R.color.statusbar)); //status bar or the time bar at the top (see example image1)

getWindow().setNavigationBarColor(ContextCompat.getColor(this, R.color.dark_nav)); // Navigation bar the soft bottom of some phones like nexus and some Samsung note series  (see example image2)
}

example image1 setStatusBarColor

example image2 setNavigationBarColor


问:
Python code for word search in excel
I need a code that can search for the specific word in excel file. In the specific columns and I want it to output with columns letter and rows number and sheet name? I have started but don't know further:

```<code>from xlrd import open_workbook
book = open_workbook("excel1.xlsx")
for sheet in book.sheets():
</code>```

its needs to print row number, column letter, sheet name? also if you can use pandas instead xlrd it will be great.

答:
An alternative is you may use Pandas library to do this. Pandas works on data frames i.e. tabular data, so have rows and columns. You need to specify your needs according to the dataset in Pandas.

```<code>import pandas as pd
df = pd.read_excel('filename.xls')
df[df['col_name'].str.contains('ABC')].head()
df.query('col_name == ["words"]').head()
df[df['Column'] >= 'Your_search_word'].head()
</code>```

etc. You can search more on the documentation of Pandas http://pbpython.com/excel-pandas-comp-2.html

Note: Pandas merge all sheets together to create one data frame in a tabular structure that can make things easier to search.

Title: Python code for word search in excel

Body:
I need a code that can search for the specific word in excel file. In the specific columns and I want it to output with columns letter and rows number and sheet name? I have started but don't know further:

from xlrd import open_workbook
book = open_workbook("excel1.xlsx")
for sheet in book.sheets():

its needs to print row number, column letter, sheet name? also if you can use pandas instead xlrd it will be great.

Body:
An alternative is you may use Pandas library to do this. Pandas works on data frames i.e. tabular data, so have rows and columns. You need to specify your needs according to the dataset in Pandas.

import pandas as pd
df = pd.read_excel('filename.xls')
df[df['col_name'].str.contains('ABC')].head()
df.query('col_name == ["words"]').head()
df[df['Column'] >= 'Your_search_word'].head()

etc. You can search more on the documentation of Pandas http://pbpython.com/excel-pandas-comp-2.html

Note: Pandas merge all sheets together to create one data frame in a tabular structure that can make things easier to search.


问:
Is there any method to check parameter of view functions in python (Django)?
What I want:

```<code>@api_view(['POST'])
@params(required=["arg1", "arg2"], optional=["arg3"])
def test(request):
    # if arg1, args not posted, abort 400 or something
    arg1 = request.data.get("arg1")
    arg2 = request.data.get("arg2")
    arg3 = request.data.get("arg3")
    # do something
</code>```

I use the rest framework but it seems that there is only validator for serializer.

答:
Why not define a basic function somewhere and get called by view functions.

For example, validator code snippet here:

```<code>@staticmethod
def checkMandatoryParams(request, params):
    msg = "need param `%s`"
    for param in params:
        if param not in request.data:
            return JsonResponse({'retcode':1,'msg': msg})
</code>```

Then, call this guy from view functions like:

```<code>def handle_test(self, request):
    ret = checkMandatoryParams(request, ['images','tasks','whatever'])
    # check ret to return or not , or you can even wrap the validator to return by case
</code>```

By this way, you could define whatever validators.

Body:
What I want:

@api_view(['POST'])
@params(required=["arg1", "arg2"], optional=["arg3"])
def test(request):
    # if arg1, args not posted, abort 400 or something
    arg1 = request.data.get("arg1")
    arg2 = request.data.get("arg2")
    arg3 = request.data.get("arg3")
    # do something

I use the rest framework but it seems that there is only validator for serializer.

Body:
Why not define a basic function somewhere and get called by view functions.

For example, validator code snippet here:

@staticmethod
def checkMandatoryParams(request, params):
    msg = "need param `%s`"
    for param in params:
        if param not in request.data:
            return JsonResponse({'retcode':1,'msg': msg})

Then, call this guy from view functions like:

def handle_test(self, request):
    ret = checkMandatoryParams(request, ['images','tasks','whatever'])
    # check ret to return or not , or you can even wrap the validator to return by case

By this way, you could define whatever validators.


问:
WebRTC iOS: remote video is not shown in iOS client
I am trying to implement WebRTC in an iOS application using GoogleWebRTC pod. i can place a video call between iOS app and a web client, in which case the audio/video works just fine. however when i place a video call between two iOS devices there is no video(audio works). i've checked if there is remote stream and there is.</p>

```<code>let localStream = connectionFactory?.mediaStream(withStreamId: "StreamID")
let audioTrack = connectionFactory?.audioTrack(withTrackId: "AudioTrackID")
let videoSource = connectionFactory?.avFoundationVideoSource(with: mediaConstraint)
let videoTrack = connectionFactory?.videoTrack(with: videoSource!, trackId: "VideoTrackID")
localStream?.addAudioTrack(audioTrack!)
localStream?.addVideoTrack(videoTrack!)
peerConnection?.add(localStream!)
</code>```

答: Found the problem. I was giving a hard coded string as id when creating stream and video track. which when a connection is established becomes the same for both local and remote streams. providing unique strings as ids solves the problem.</p>

Body:
I am trying to implement WebRTC in an iOS application using GoogleWebRTC pod. i can place a video call between iOS app and a web client, in which case the audio/video works just fine. however when i place a video call between two iOS devices there is no video(audio works). i've checked if there is remote stream and there is.

let localStream = connectionFactory?.mediaStream(withStreamId: "StreamID")
let audioTrack = connectionFactory?.audioTrack(withTrackId: "AudioTrackID")
let videoSource = connectionFactory?.avFoundationVideoSource(with: mediaConstraint)
let videoTrack = connectionFactory?.videoTrack(with: videoSource!, trackId: "VideoTrackID")
localStream?.addAudioTrack(audioTrack!)
localStream?.addVideoTrack(videoTrack!)
peerConnection?.add(localStream!)