问:
Show form validation errors using laravel and ajax
I need to output the validation errors in case if the validation fails.
But the errors are not being displayed.
I have used Laravel for the server side and ajax for sending the HTTP request.

FORM

```<code><form action="#" method="POST" id="frmcontactuspage" class="contact-form">
            {{ csrf_field() }}
            <div class="form-row">
                <label for="">@lang('language.name') *</label>
                <input id="name" type="text" name="name">
                  <span class="text-danger" id="name-error"></span>
            </div>
            <div class="form-row">
                <label for="">@lang('language.address') *</label>
                <input id="address" type="text" name="address">
                <span class="text-danger" id="address-error"></span>
            </div>
            <div class="form-row">
                <label for="">@lang('language.phone') *</label>
                <input id="phoneno" type="text" name="phoneno">
                   <span class="text-danger" id="phone-error"></span>
            </div>
            <div class="form-row">
                <label for="">@lang('language.email') *</label>
                <input id="email" type="email" name="email">
                <span class="text-danger" id="email-error"></span>
            </div>

            <div class="form-row">
                <label for="">@lang('language.subject') *</label>
                <input id="metitle" type="text" name="subject">
                    <span class="text-danger" id="subject-error"></span>
            </div>
            <div class="form-row">
                <label for="">@lang('language.message') *</label>
                <textarea name="message" id="message" rows="3"></textarea>

            </div>
            <div class="form-row-s">
                 <button type="button" class="submit s-btn-a" id="btncontactuspage">@lang('language.submit')</button>
                </button>
            </div>

        </form>
</code>```

CONTROLLER

```<code>public function insertfeedback(Request $request){
        $validator = Validator::make($request->all(), [
            'name'              => 'required|min:2',
            'email'             => 'required|email',
            'phoneno'           => 'required',
            'address'           => 'required|min:5',
            'message'           => 'required|min:10',
        ]);

    if ($validator->passes()) {
        $contact = new AdminContact;
        $contact->name = $request->name;
        $contact->email = $request->email;
        $contact->address = $request->address;
        $contact->phoneno = $request->phoneno;
        $contact->message = $request->message;
        $contact->inserted_date = date('Y-m-d H:i:s');

        $contact->save();

         $message = "We've received your feedback. Thank You !!!";

        return response()->json(['error' => false, 'message' => $message]);
    }
else{
    return response()->json(['error' => true,'errors' => $validator->errors()]);
}
}
</code>```

AJAX

```<code>$('#btncontactuspage').click(function(event) {
    var formdata = $("#frmcontactuspage").serialize();
    $("#name-error").html("");
    $("#email-error").html("");
    $("#phoneno-error").html("");
    $("#address-error").html("");
    $("#message-error").html("");
    $("#statuspage-msg").html("");
    $.ajax({
        url: baseurl+'/'+locale+'/insertfeedback',
        type: "POST",
        data: formdata
    }).always(function(resp) {
        console.log(resp)
        if(resp.error=='true'){
            if(resp.errors.branch_id){
              $('#branch_id-error').html(resp.errors.branch_id[0]);
            }
            if(resp.errors.name){
              $('#name-error').html(resp.errors.name[0]);
            }
            if(resp.errors.email){
              $('#email-error').html(resp.errors.email[0]);
            }
            if(resp.errors.phoneno){
              $('#phoneno-error').html(resp.errors.phoneno[0]);
            }
            if(resp.errors.address){
              $('#address-error').html(resp.errors.address[0]);
            }
            if(resp.errors.message){
              $('#message-error').html(resp.errors.message[0]);
            }
        }
        if(resp.error=='false'){
            $("#frmcontactuspage")[0].reset();
            $("#statuspage-msg").removeClass('d-none');
            $("#statuspage-msg").html(resp.message);
        }
    });
</code>```

});

Whats the issue here?
Why is the validation not being displayed? Is there any problem in the ajax code?
I am not being able to sort it out.
help

答:
Make sure you pass a Accept: application/json header with your request, otherwise the response will be a 302 redirect and you won't see the validation errors. You need to pass the folliwing in your ajax call:

```<code>$.ajax({
    ...
    headers: {
       "Accept": "application/json",
    }
</code>```

Body:
I need to output the validation errors in case if the validation fails.
But the errors are not being displayed.
I have used Laravel for the server side and ajax for sending the HTTP request.

FORM

<form action="#" method="POST" id="frmcontactuspage" class="contact-form">
            {{ csrf_field() }}

                @lang('language.name') *
                <input id="name" type="text" name="name">

                @lang('language.address') *
                <input id="address" type="text" name="address">

                @lang('language.phone') *
                <input id="phoneno" type="text" name="phoneno">

                @lang('language.email') *
                <input id="email" type="email" name="email">

                @lang('language.subject') *
                <input id="metitle" type="text" name="subject">

                @lang('language.message') *
                <textarea name="message" id="message" rows="3"></textarea>

                 <button type="button" class="submit s-btn-a" id="btncontactuspage">@lang('language.submit')</button>
                </button>

        </form>

CONTROLLER

public function insertfeedback(Request $request){
        $validator = Validator::make($request->all(), [
            'name'              => 'required|min:2',
            'email'             => 'required|email',
            'phoneno'           => 'required',
            'address'           => 'required|min:5',
            'message'           => 'required|min:10',
        ]);

    if ($validator->passes()) {
        $contact = new AdminContact;
        $contact->name = $request->name;
        $contact->email = $request->email;
        $contact->address = $request->address;
        $contact->phoneno = $request->phoneno;
        $contact->message = $request->message;
        $contact->inserted_date = date('Y-m-d H:i:s');

        $contact->save();

         $message = "We've received your feedback. Thank You !!!";

        return response()->json(['error' => false, 'message' => $message]);
    }
else{
    return response()->json(['error' => true,'errors' => $validator->errors()]);
}
}

AJAX

$('#btncontactuspage').click(function(event) {
    var formdata = $("#frmcontactuspage").serialize();
    $("#name-error").html("");
    $("#email-error").html("");
    $("#phoneno-error").html("");
    $("#address-error").html("");
    $("#message-error").html("");
    $("#statuspage-msg").html("");
    $.ajax({
        url: baseurl+'/'+locale+'/insertfeedback',
        type: "POST",
        data: formdata
    }).always(function(resp) {
        console.log(resp)
        if(resp.error=='true'){
            if(resp.errors.branch_id){
              $('#branch_id-error').html(resp.errors.branch_id[0]);
            }
            if(resp.errors.name){
              $('#name-error').html(resp.errors.name[0]);
            }
            if(resp.errors.email){
              $('#email-error').html(resp.errors.email[0]);
            }
            if(resp.errors.phoneno){
              $('#phoneno-error').html(resp.errors.phoneno[0]);
            }
            if(resp.errors.address){
              $('#address-error').html(resp.errors.address[0]);
            }
            if(resp.errors.message){
              $('#message-error').html(resp.errors.message[0]);
            }
        }
        if(resp.error=='false'){
            $("#frmcontactuspage")[0].reset();
            $("#statuspage-msg").removeClass('d-none');
            $("#statuspage-msg").html(resp.message);
        }
    });

});

Whats the issue here?
Why is the validation not being displayed? Is there any problem in the ajax code?
I am not being able to sort it out.
help

Body:
Make sure you pass a Accept: application/json header with your request, otherwise the response will be a 302 redirect and you won't see the validation errors. You need to pass the folliwing in your ajax call:

$.ajax({
    ...
    headers: {
       "Accept": "application/json",
    }


来源: stackexchange

问:
Failed to execute 'removeChild' while component is unmounting
I am currently integrating a video chat where people can switch between different rooms. That part works well. Now I want to add an additional components. If I click on "another component" while loading the Daily component I get the error:

Failed to execute 'removeChild' on 'Node': The node to be removed is
  not a child of this node.

Video example of bug: https://www.loom.com/share/e9b03203fe42458f8b0abd44d250517b

I created the following Sandbox to demonstrate the problem: https://codesandbox.io/s/agitated-blackburn-oorng?file=/src/App.js

The problem seems to be connected with dailyRef.current.destroy();. And that it can't be executed if the video isn't in a "loaded finished" state.

答:
This is an implementation of daily.destroy method

 async destroy() {
    try {
      "joined-meeting" === this._meetingState && (await this.leave());
    } catch (t) {}
    let t = this.iframe();
    if (t) {
      let e = t.parentElement;
      e && e.removeChild(t);
    }
    window.removeEventListener("message", this._messageListener);
  }
```

<p>You can extract from that necessary bits and only cleanup event listener</p>

```  return () => {
    try {
      "joined-meeting" === daily._meetingState && (await daily.leave());
    } catch (t) {}

    window.removeEventListener("message", daily._messageListener);
};
```

ContentLicense: CC BY-SA 4.0

Body:
This is an implementation of daily.destroy method

 async destroy() {
    try {
      "joined-meeting" === this._meetingState && (await this.leave());
    } catch (t) {}
    let t = this.iframe();
    if (t) {
      let e = t.parentElement;
      e && e.removeChild(t);
    }
    window.removeEventListener("message", this._messageListener);
  }

You can extract from that necessary bits and only cleanup event listener

  return () => {
    try {
      "joined-meeting" === daily._meetingState && (await daily.leave());
    } catch (t) {}

    window.removeEventListener("message", daily._messageListener);
};


问:
Right_only Merging two data frames. What does it return?
I have merged two data frames from two large data tables (300k + rows) but when I right_only merged them on various columns, only six rows returned for one merged table, and sometimes the merge returned a table with zero rows. Can someone help me understand what is happening?

Here is an example of the command I used to merge:

```<code>right_retail = merged_retail[merged_retail['_merge']=='right_only']
</code>```

Regards

答:
This is the syntax for right join and you can add more keys for join.</p>

```<code>result = pd.merge(left, right, how='right', on=['key1', 'key2'])
</code>```

Body:
I have merged two data frames from two large data tables (300k + rows) but when I right_only merged them on various columns, only six rows returned for one merged table, and sometimes the merge returned a table with zero rows. Can someone help me understand what is happening?

Here is an example of the command I used to merge:

right_retail = merged_retail[merged_retail['_merge']=='right_only']

Regards

Body:
This is the syntax for right join and you can add more keys for join.

result = pd.merge(left, right, how='right', on=['key1', 'key2'])


问:
Populate envers revision tables with existing data from Hibernate Entities
I'm adding envers to an existing hibernate entities. Everything is working smoothly so far as far as auditing, however querying is a different issue because the revision tables aren’t populated with the existing data. Has anyone else already solved this issue? Maybe you’ve found some way to populate the revision tables with the existing table? Just thought I’d ask, I'm sure others would find it useful.  </p>

答:
You don't need to.

AuditQuery allows you to get both RevisionEntity and data revision by :

```<code>AuditQuery query = getAuditReader().createQuery()
                .forRevisionsOfEntity(YourAuditedEntity.class, false, false);
</code>```

This will construct a query which returns a list of Object [3]. Fisrt element is your data, the second is the revision entity and the third is the type of revision.

ContentLicense: CC BY-SA 2.5

Body:
You don't need to.

AuditQuery allows you to get both RevisionEntity and data revision by :

AuditQuery query = getAuditReader().createQuery()
                .forRevisionsOfEntity(YourAuditedEntity.class, false, false);

This will construct a query which returns a list of Object [3]. Fisrt element is your data, the second is the revision entity and the third is the type of revision.

ContentLicense: CC BY-SA 3.0


问:
How do I set the length of a string in a table to a certain length in a rails application?
I have a table with a title column on my index.html.erb. These titles are very long so when I render my page the table goes quite far horizontally across the screen. It's all on one line as well.
How do I set it so that after around 6 words it goes onto another line, and after 6 more words the string is cut off. The table is looped! The full description can be read when a user visits the seperate show.html page

Some of the code below

```<code><td class="px-6 py-4 whitespace-no-wrap border-b border-gray-200">
   <div class="text-sm leading-5 text-gray-900"><%= article.title %></div>
</td>
</code>```

答:
I guess you could try counting the amount of characters that you want and limit by that, e.g

```<code><%= truncate(title, length:10) %>
</code>```

But if you need something very robust to support screen sizes etc I'm pretty sure css can help you
CSS text-overflow in a table cell?

Body:
I have a table with a title column on my index.html.erb. These titles are very long so when I render my page the table goes quite far horizontally across the screen. It's all on one line as well.
How do I set it so that after around 6 words it goes onto another line, and after 6 more words the string is cut off. The table is looped! The full description can be read when a user visits the seperate show.html page

Some of the code below

<%= article.title %>

Body:
I guess you could try counting the amount of characters that you want and limit by that, e.g

<%= truncate(title, length:10) %>

But if you need something very robust to support screen sizes etc I'm pretty sure css can help you
CSS text-overflow in a table cell?


问:
Creating a Collapsible table in JSP
JSP Code:

```<code> <c:forEach var="map" items="${map}">
                    <tr>
                        <td>
                            <table border="1">
                                <tr class="header expand">
                                    <th>${map.key.id}</th><th>${map.key.name}</th><th>${map.key.status}<span class="sign"></span></th>
                                </tr>
                            </table>
                        </td>
                        <td>
                            <table border="1">
                            <tr>
                            <th>REQUEST_ID</th>
                            <th>LOGIN_USER</th>
                            <th>PRICE</th>
                            <th>STATUS</th>
                        </tr>
                                <c:forEach var="item" items="${map.value}">
                                    <tr>
                                        <td>${item.REQUEST_ID}</td><td>${item.LOGIN_USER}</td><td>${item.PRICE}</td><td>${item.STATUS}</td>
                                    </tr>
                                </c:forEach>
                            </table>
                        </td>
                    </tr>
                </c:forEach>
</code>```

Collapsible Table Code:

```<code><style type="text/css">
    table, tr, td, th
{
    border: 1px solid black;
    border-collapse:collapse;
}
tr.header
{
    cursor:pointer;
}
.header .sign:after{
  content:"+";
  display:inline-block;
}
.header.expand .sign:after{
  content:"-";
 }
</style>
<body>
<table border="0">
  <tr  class="header expand">
      <th colspan="2">Header <span class="sign"></span></th>
  </tr>
  <tr>
    <td>data</td>
    <td>data</td>
  </tr>
  <tr>
    <td>data</td>
    <td>data</td>
  </tr>
</table>
  <script type="text/javascript">
    $('.header').click(function(){
     $(this).toggleClass('expand').nextUntil('tr.header').slideToggle(100);
});
  </script>
</body>
</code>```

I have a map which is being retrieved in JSP. It has object as key and arraylist as values.The arraylist consists of rows as objects.For a particular key which has unique reqid,it has all rows specific to the reqid as objects in the arraylist. I want to retrieve it in JSP. It must be collapsible table in such a way that key is my header and values i.e rows related to reqid must be present under that header.I have independent JavaScript code to implement it.I tried adding up in JSP but there is no outcome on browser.I need help in designing collapsible table in JSP code.

Expected Output:

```<code>123  A   1   ///Table header
123 A   5  2
123 A  10  3
//N no of rows

456 B 2    ///Table header
456 B  20  3
456 B  25  2
//N no of rows
</code>```

答:
Your jquery code is working but structure of your table is wrong .There are many invalid elements in it. That's the reason jquery is not able to find correct element to expand or collapse.

Some of the changes you need to make in your table structure :

```<code><table>
  <c:forEach var="map" items="${map}">
  <!--no need to have new tr td here that just add extra row to your table-->
    <tr class="header expand">
      <th>${map.key.id}</th>
      <th>${map.key.name}</th>
      <th>${map.key.status}</th>
      <th><span class="sign"></span></th>
    </tr>
   <!--no need to have different table-->
    <tr>
      <th>REQUEST_ID</th>
      <th>LOGIN_USER</th>
      <th>PRICE</th>
      <th>STATUS</th>
    </tr>
    <c:forEach var="item" items="${map.value}">
      <tr>
        <td>${item.REQUEST_ID}</td>
        <td>${item.LOGIN_USER}</td>
        <td>${item.PRICE}</td>
        <td>${item.STATUS}</td>
      </tr>
    </c:forEach>
  </c:forEach>
</table>
</code>```

Here is the demo code for above table structure:

$('.header').click(function() {
$(this).toggleClass('expand').nextUntil('tr.header').slideToggle(100);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table,
tr,
td,
th {
  border: 1px solid black;
  border-collapse: collapse;
}

tr.header {
  cursor: pointer;
  color: blue;
}

.header .sign:after {
  content: "-";
  display: inline-block;
}

.header.expand .sign:after {
  content: "+";
}</code>```

    ${map.key.id}
    ${map.key.name}
    ${map.key.status}

    REQUEST_ID
    LOGIN_USER
    PRICE
    STATUS

    ${item.REQUEST_ID}
    ${item.LOGIN_USER}
    ${item.PRICE}
    ${item.STATUS}

    ${map.key.id}
    ${map.key.name}
    ${map.key.status}

    REQUEST_ID
    LOGIN_USER
    PRICE
    STATUS

    ${item.REQUEST_ID}
    ${item.LOGIN_USER}
    ${item.PRICE}
    ${item.STATUS}

```

Title: Creating a Collapsible table in JSP

Body:
JSP Code:

 <c:forEach var="map" items="${map}">

                                    ${map.key.id}	${map.key.name}	${map.key.status}

                            REQUEST_ID
                            LOGIN_USER
                            PRICE
                            STATUS

                                <c:forEach var="item" items="${map.value}">

                                        ${item.REQUEST_ID}	${item.LOGIN_USER}	${item.PRICE}	${item.STATUS}

                                </c:forEach>

                </c:forEach>

Collapsible Table Code:

      Header

    data
    data

    data
    data

I have a map which is being retrieved in JSP. It has object as key and arraylist as values.The arraylist consists of rows as objects.For a particular key which has unique reqid,it has all rows specific to the reqid as objects in the arraylist. I want to retrieve it in JSP. It must be collapsible table in such a way that key is my header and values i.e rows related to reqid must be present under that header.I have independent JavaScript code to implement it.I tried adding up in JSP but there is no outcome on browser.I need help in designing collapsible table in JSP code.

Expected Output:

123  A   1   ///Table header
123 A   5  2
123 A  10  3
//N no of rows

456 B 2    ///Table header
456 B  20  3
456 B  25  2
//N no of rows

Body:
Your jquery code is working but structure of your table is wrong .There are many invalid elements in it. That's the reason jquery is not able to find correct element to expand or collapse.

Some of the changes you need to make in your table structure :

<table>
  <c:forEach var="map" items="${map}">
  <!--no need to have new tr td here that just add extra row to your table-->
    <tr class="header expand">
      <th>${map.key.id}</th>
      <th>${map.key.name}</th>
      <th>${map.key.status}</th>
      <th><span class="sign"></span></th>
    </tr>
   <!--no need to have different table-->
    <tr>
      <th>REQUEST_ID</th>
      <th>LOGIN_USER</th>
      <th>PRICE</th>
      <th>STATUS</th>
    </tr>
    <c:forEach var="item" items="${map.value}">
      <tr>
        <td>${item.REQUEST_ID}</td>
        <td>${item.LOGIN_USER}</td>
        <td>${item.PRICE}</td>
        <td>${item.STATUS}</td>
      </tr>
    </c:forEach>
  </c:forEach>
</table>

Here is the demo code for above table structure:

$('.header').click(function() {
$(this).toggleClass('expand').nextUntil('tr.header').slideToggle(100);
});

table,
tr,
td,
th {
  border: 1px solid black;
  border-collapse: collapse;
}

tr.header {
  cursor: pointer;
  color: blue;
}

.header .sign:after {
  content: "-";
  display: inline-block;
}

.header.expand .sign:after {
  content: "+";
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr class="header expand">
    <th>${map.key.id}</th>
    <th>${map.key.name}</th>
    <th>${map.key.status}</th>
    <th><span class="sign"></span></th>
  </tr>

  <tr style="display:none" >
    <th>REQUEST_ID</th>
    <th>LOGIN_USER</th>
    <th>PRICE</th>
    <th>STATUS</th>
  </tr>

  <tr style="display:none">
    <td>${item.REQUEST_ID}</td>
    <td>${item.LOGIN_USER}</td>
    <td>${item.PRICE}</td>
    <td>${item.STATUS}</td>
  </tr>

  <tr class="header expand">
    <th>${map.key.id}</th>
    <th>${map.key.name}</th>
    <th>${map.key.status}</th>
    <th><span class="sign"></span></th>
  </tr>

  <tr style="display:none">
    <th>REQUEST_ID</th>
    <th>LOGIN_USER</th>
    <th>PRICE</th>
    <th>STATUS</th>
  </tr>

  <tr style="display:none">
    <td>${item.REQUEST_ID}</td>
    <td>${item.LOGIN_USER}</td>
    <td>${item.PRICE}</td>
    <td>${item.STATUS}</td>
  </tr>

</table>


问:
Multiple IF condition based on previous and the current row - Pandas
I want to create a new column G which should display 1 if the previous row of D column contains a chrg or float and the current rows contains Dischrg. The first row should contain 0.

I want the pandas equivalent of the following excel code:

```<code>=IF(AND(D2="Chrg",D3="Dischrg"),G2+1,IF(AND(D2="Float",D3="Dischrg"),G2+1,0))
</code>```

```<code>D         G
Chrg      0
Dischrg   1
Float     0
Dischrg   0
Float     0
Dischrg   1
</code>```

答:
Use Series.shift with Series.isin:

```<code>m1 = df['D'].shift().isin(['Chrg', 'Float'])  # Chrg or Float previous row
m2 = df['D'].eq('Dischrg')                    # Current row Dischrg

df['G'] = (m1&m2).astype(int)

         D  G
0     Chrg  0
1  Dischrg  1
2    Float  0
3  Dischrg  1
4    Float  0
5  Dischrg  1
</code>```

Body:
I want to create a new column G which should display 1 if the previous row of D column contains a chrg or float and the current rows contains Dischrg. The first row should contain 0.

I want the pandas equivalent of the following excel code:

=IF(AND(D2="Chrg",D3="Dischrg"),G2+1,IF(AND(D2="Float",D3="Dischrg"),G2+1,0))

D         G
Chrg      0
Dischrg   1
Float     0
Dischrg   0
Float     0
Dischrg   1

Body:
Use Series.shift with Series.isin:

m1 = df['D'].shift().isin(['Chrg', 'Float'])  # Chrg or Float previous row
m2 = df['D'].eq('Dischrg')                    # Current row Dischrg

df['G'] = (m1&m2).astype(int)

         D  G
0     Chrg  0
1  Dischrg  1
2    Float  0
3  Dischrg  1
4    Float  0
5  Dischrg  1


问:
cabal install gving errror as LICENSE: openBinaryFile: does not exist (No such file or directory)
I have cabal version:

```<code>❯ cabal --version
cabal-install version 3.0.0.0
compiled using version 3.0.0.0 of the Cabal library
</code>```

Here is what I am doing.

```<code>mkdir foo
cd foo
cabal init
cabal install
</code>```

and I am getting an error:

```<code>LICENSE: openBinaryFile: does not exist (No such file or directory)
</code>```

What I am doing wrong here?

答:
When ran in the manner you describe, cabal init warns that:

```<code>Warning: unknown license type, you must put a copy in LICENSE yourself.
</code>```

Without a LICENSE file, certain commands won't work properly (cf., for instance, cabal issue #6744). You should either create a LICENSE file, or pick one of the licenses Cabal knows about by specifying it through the -l option of cabal init.

Body:
I have cabal version:

❯ cabal --version
cabal-install version 3.0.0.0
compiled using version 3.0.0.0 of the Cabal library

Here is what I am doing.

mkdir foo
cd foo
cabal init
cabal install

and I am getting an error:

LICENSE: openBinaryFile: does not exist (No such file or directory)

What I am doing wrong here?

Body:
When ran in the manner you describe, cabal init warns that:

Warning: unknown license type, you must put a copy in LICENSE yourself.

Without a LICENSE file, certain commands won't work properly (cf., for instance, cabal issue #6744). You should either create a LICENSE file, or pick one of the licenses Cabal knows about by specifying it through the -l option of cabal init.


问:
Whats the point of DOCTYPE?
I know that different doctypes are essentially about how compliant the html is, but what difference does it make what doctype you specify? Do browsers handle the same code differently depending on the doctype?
Thanks </p>

<p>UPDATE - most answers mention quirks mode can be set off if no doctype is specified. But what would be the different between xhtml and html 4.01? </p>

答:
From Wikipedia:

A Document Type Declaration, or
  DOCTYPE, is an instruction that
  associates a particular SGML or XML
  document (for example, a webpage) with
  a Document Type Definition (DTD) (for
  example, the formal definition of a
  particular version of HTML). In the
  serialized form of the document, it
  manifests as a short string of markup
  that conforms to a particular syntax.

The HTML layout engines in modern web
  browsers perform DOCTYPE "sniffing" or
  "switching", wherein the DOCTYPE in a
  document served as text/html
  determines a layout mode, such as
  "quirks mode" or "standards mode". The
  text/html serialization of HTML5,
  which is not SGML-based, uses the
  DOCTYPE only for mode selection. Since
  web browsers are implemented with
  special-purpose HTML parsers, rather
  than general-purpose DTD-based
  parsers, they don't use DTDs and will
  never access them even if a URL is
  provided. The DOCTYPE is retained in
  HTML5 as a "mostly useless, but
  required" header only to trigger
  "standards mode" in common browsers.

I decided to quote this text because it answers your question better than I would :). It is important that the absence of a DOCTYPE will trigger "quirks mode" in certain browsers.

Title: Whats the point of DOCTYPE?

Body:
I know that different doctypes are essentially about how compliant the html is, but what difference does it make what doctype you specify? Do browsers handle the same code differently depending on the doctype?
Thanks

UPDATE - most answers mention quirks mode can be set off if no doctype is specified. But what would be the different between xhtml and html 4.01?


问:
Multiple effects in `else` using ternary operator
I have the next condition in Java Script:

if(a === 10) {
  getName()
  getLastName()
} ```
</div>
</div>
</p>

<p>I want to write this code using ternary operator, and i wrote this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>a === 10 && (getName() && getLastName())</code>```

But this does not work.

 Question: What could be the issue with my code?

答:
I want to write this code using ternary operator

That's not a ternary operator (an operator accepting three operands), it's the &&, which is a binary operator (an operator accepting two operands). The only ternary operator in JavaScript right now is the conditional operator (condition ? valueIfTruthy : valueIfFalsy).

The problem is that when you combine things with &&, the right-hand operand is only evaluated if the left-hand operand's value is truthy. I guess getName is returning something falsy, which is why the right-hand operand isn't evaluated (getLastName isn't called). && short-circuits.

Don't rewrite the if. It's perfectly clear and straightforward and easy to debug the way it is. It's not broken.

If you were going to use && instead of if, you'd use the comma operator (a binary operator) for the two operations:

```<code>// Please don't do this
a === 10 && (getName(), getLastName());
</code>```

The comma operator evaluates its left-hand operand, throws the result away, and then evaluates its right-hand operand and takes that result as its result.

But again: Please don't. :-)

Body:
I have the next condition in Java Script:

if(a === 10) {
  getName()
  getLastName()
}

I want to write this code using ternary operator, and i wrote this:

a === 10 && (getName() && getLastName())

But this does not work.

 Question: What could be the issue with my code?

Body:
I want to write this code using ternary operator

That's not a ternary operator (an operator accepting three operands), it's the &&, which is a binary operator (an operator accepting two operands). The only ternary operator in JavaScript right now is the conditional operator (condition ? valueIfTruthy : valueIfFalsy).

The problem is that when you combine things with &&, the right-hand operand is only evaluated if the left-hand operand's value is truthy. I guess getName is returning something falsy, which is why the right-hand operand isn't evaluated (getLastName isn't called). && short-circuits.

Don't rewrite the if. It's perfectly clear and straightforward and easy to debug the way it is. It's not broken.

If you were going to use && instead of if, you'd use the comma operator (a binary operator) for the two operations:

// Please don't do this
a === 10 && (getName(), getLastName());

The comma operator evaluates its left-hand operand, throws the result away, and then evaluates its right-hand operand and takes that result as its result.

But again: Please don't. :-)


问:
Serializing enums with Jackson
I have an Enum desrcibed below:

```<code>public enum OrderType {

  UNKNOWN(0, "Undefined"),
  TYPEA(1, "Type A"),
  TYPEB(2, "Type B"),
  TYPEC(3, "Type C");

  private Integer id;
  private String name;

  private WorkOrderType(Integer id, String name) {
    this.id = id;
    this.name = name;
  }

  //Setters, getters....
}
</code>```

I return enum array with my controller ( new OrderType[] {UNKNOWN,TYPEA,TYPEB,TYPEC};), and Spring serializes it into the following json string:

```<code>["UNKNOWN", "TYPEA", "TYPEB", "TYPEC"]
</code>```

What is the best approach to force Jackson to serialize enums just like POJOs? E.g.:

```<code>[
  {"id": 1, "name": "Undefined"},
  {"id": 2, "name": "Type A"},
  {"id": 3, "name": "Type B"},
  {"id": 4, "name": "Type C"}
]
</code>```

I played with different annotations but couldn't manage to get such result.

答:
In Spring Boot 2, the easiest way is to declare in your application.properties:

```<code>spring.jackson.serialization.WRITE_ENUMS_USING_TO_STRING=true
spring.jackson.deserialization.READ_ENUMS_USING_TO_STRING=true
</code>```

and define the toString() method of your enums.

Title: Serializing enums with Jackson

Body:
I have an Enum desrcibed below:

public enum OrderType {

  UNKNOWN(0, "Undefined"),
  TYPEA(1, "Type A"),
  TYPEB(2, "Type B"),
  TYPEC(3, "Type C");

  private Integer id;
  private String name;

  private WorkOrderType(Integer id, String name) {
    this.id = id;
    this.name = name;
  }

  //Setters, getters....
}

I return enum array with my controller ( new OrderType[] {UNKNOWN,TYPEA,TYPEB,TYPEC};), and Spring serializes it into the following json string:

["UNKNOWN", "TYPEA", "TYPEB", "TYPEC"]

What is the best approach to force Jackson to serialize enums just like POJOs? E.g.:

[
  {"id": 1, "name": "Undefined"},
  {"id": 2, "name": "Type A"},
  {"id": 3, "name": "Type B"},
  {"id": 4, "name": "Type C"}
]

I played with different annotations but couldn't manage to get such result.

Body:
In Spring Boot 2, the easiest way is to declare in your application.properties:

spring.jackson.serialization.WRITE_ENUMS_USING_TO_STRING=true
spring.jackson.deserialization.READ_ENUMS_USING_TO_STRING=true

and define the toString() method of your enums.


问:
How to use '.' in magrittr with numerical formulas
I am unable to determine how to use (some ?) numerical formulas with magrittr. Here is a particular case:

```<code>library(magrittr)
y = c( complex(1, 1.0,2.0), complex(1, 3.0,4.0))
ymagn = y %>% sqrt(Re(.)**2 + Im(.)**2)
</code>```

Which results in

```
  Error in sqrt(., Re(.)^2 + Im(.)^2) :    2 arguments passed to 'sqrt'
  which requires 1
```

答:
Here is one approach you can use:

```<code>ymagn = y %>% {sqrt(Re(.)**2 + Im(.)**2)}
[1] 2.236068 5.000000
</code>```

The reason your version does not work is because by default the %>% operator provides the output of the left hand side (LHS) as the first argument of the right hand side (RHS).

Under the default circumstances, if you provide . again, in addition to providing it as the first argument, the pipe operator will provide the output in place of .. As you can read in help(`%>%`,"magrittr"), the package authors intend you to use this functionality in this type of way:

```<code>iris %>% subset(., 1:nrow(.) %% 2 == 0)
</code>```

Without the brackets, the code you attempted is evaluated in this way:

```<code>ymagn = y %>% sqrt(.,Re(.)**2 + Im(.)**2)
</code>```

This explains the error reporting 2 arguments.

Using the brackets is called a lambda expression. From help(`%>%`,"magrittr"):

Using lambda expressions with %>%

Each rhs is essentially a one-expression body of a unary function. Therefore defining lambdas in magrittr is very natural, and as the definitions of regular functions: if more than a single expression is needed one encloses the body in a pair of braces, { rhs }. However, note that within braces there are no "first-argument rule": it will be exactly like writing a unary function where the argument name is "." (the dot).

Body:
I am unable to determine how to use (some ?) numerical formulas with magrittr. Here is a particular case:

library(magrittr)
y = c( complex(1, 1.0,2.0), complex(1, 3.0,4.0))
ymagn = y %>% sqrt(Re(.)**2 + Im(.)**2)

Which results in

  Error in sqrt(., Re(.)^2 + Im(.)^2) :    2 arguments passed to 'sqrt'
  which requires 1

Body:
Here is one approach you can use:

ymagn = y %>% {sqrt(Re(.)**2 + Im(.)**2)}
[1] 2.236068 5.000000

The reason your version does not work is because by default the %>% operator provides the output of the left hand side (LHS) as the first argument of the right hand side (RHS).

Under the default circumstances, if you provide . again, in addition to providing it as the first argument, the pipe operator will provide the output in place of .. As you can read in help(`%>%`,"magrittr"), the package authors intend you to use this functionality in this type of way:

iris %>% subset(., 1:nrow(.) %% 2 == 0)

Without the brackets, the code you attempted is evaluated in this way:

ymagn = y %>% sqrt(.,Re(.)**2 + Im(.)**2)

This explains the error reporting 2 arguments.

Using the brackets is called a lambda expression. From help(`%>%`,"magrittr"):

Using lambda expressions with %>%

Each rhs is essentially a one-expression body of a unary function. Therefore defining lambdas in magrittr is very natural, and as the definitions of regular functions: if more than a single expression is needed one encloses the body in a pair of braces, { rhs }. However, note that within braces there are no "first-argument rule": it will be exactly like writing a unary function where the argument name is "." (the dot).


问:
Object received a naive datetime (...) while time zone support is active
I've been looking for an answer for this with no luck.
I'm creating and object that has an attribute called "accessdate"

When I create the object I receive the next warning

```<code>RuntimeWarning: DateTimeField Consumption.addedtime received a naive datetime (2020-06-01 13:07:47.222534)
while time zone support is active
</code>```

The thing is that what the object is reciving is NOT a naive datetime because it has the tzinfo filled with "Europe/Madrid" timezone.

These are the relevant imports I'm using:

```<code>import datetime
from django.utils.timezone import make_aware
</code>```

This is how I create my datetime variable:

```<code>date_object = datetime.datetime.strptime(data_from_request['FECHA ACTIVACION'], '%d/%m/%Y')
# data_from_request['FECHA ACTIVACION'] = '01/01/2020'
access_date = make_aware(date_object)
</code>```

This is the model:

```<code>class Consumption(models.Model):
    """Definición del modelo de Consumos"""
    ...
    accessdate = models.DateField("Fecha de acceso", auto_now=False, auto_now_add=False)
    ...
</code>```

And this is how I create the object

```<code>        consumption = Consumption.objects.create(
            client=client,
            rule=rule,
            course=course,
            provider=provider,
            usercode=data_from_request['CODIGO USUARIO'],
            username=data_from_request['NOMBRE USUARIO'],
            accessdate=access_date,
            billable=data_from_request['FACTURABLE'],
            status=data_from_request['VALIDADO']
        )
</code>```

How is this possible? I'm debugging my code and when I check for the "access_date" variable content I can see the tzinfo filled

Why am I still getting this warning?
Thank you guys !

答:
So you Consumption model probably look alike:

```<code>class Consumption(models.Model):
    ...
    accessdate = models.DateField("Fecha de acceso", auto_now=False, auto_now_add=False)
    ....
    addedtime = models.DateTimeField(default=datetime.now()) # this is not timezone aware
</code>```

replace it with

```<code>class Consumption(models.Model):
    ...
    accessdate = models.DateField("Fecha de acceso", auto_now=False, auto_now_add=False)
    ....
    addedtime = models.DateTimeField(auto_now_add=True)
</code>```

Read your error message carefully! It not speaking about accessdate but about attribute addedtime that probably has some bad default value!

Learn more in https://docs.djangoproject.com/en/3.1/ref/models/fields/#datefield

Body:
I've been looking for an answer for this with no luck.
I'm creating and object that has an attribute called "accessdate"

When I create the object I receive the next warning

RuntimeWarning: DateTimeField Consumption.addedtime received a naive datetime (2020-06-01 13:07:47.222534)
while time zone support is active

The thing is that what the object is reciving is NOT a naive datetime because it has the tzinfo filled with "Europe/Madrid" timezone.

These are the relevant imports I'm using:

import datetime
from django.utils.timezone import make_aware

This is how I create my datetime variable:

date_object = datetime.datetime.strptime(data_from_request['FECHA ACTIVACION'], '%d/%m/%Y')
# data_from_request['FECHA ACTIVACION'] = '01/01/2020'
access_date = make_aware(date_object)

This is the model:

class Consumption(models.Model):
    """Definición del modelo de Consumos"""
    ...
    accessdate = models.DateField("Fecha de acceso", auto_now=False, auto_now_add=False)
    ...

And this is how I create the object

        consumption = Consumption.objects.create(
            client=client,
            rule=rule,
            course=course,
            provider=provider,
            usercode=data_from_request['CODIGO USUARIO'],
            username=data_from_request['NOMBRE USUARIO'],
            accessdate=access_date,
            billable=data_from_request['FACTURABLE'],
            status=data_from_request['VALIDADO']
        )

How is this possible? I'm debugging my code and when I check for the "access_date" variable content I can see the tzinfo filled

Why am I still getting this warning?
Thank you guys !

Body:
So you Consumption model probably look alike:

class Consumption(models.Model):
    ...
    accessdate = models.DateField("Fecha de acceso", auto_now=False, auto_now_add=False)
    ....
    addedtime = models.DateTimeField(default=datetime.now()) # this is not timezone aware

replace it with

class Consumption(models.Model):
    ...
    accessdate = models.DateField("Fecha de acceso", auto_now=False, auto_now_add=False)
    ....
    addedtime = models.DateTimeField(auto_now_add=True)

Read your error message carefully! It not speaking about accessdate but about attribute addedtime that probably has some bad default value!

Learn more in https://docs.djangoproject.com/en/3.1/ref/models/fields/#datefield


问:
Could not get GOOGLE_APP_ID in Google Services file from build environment
For setting up firebase i am using two config 1.GoogleService-Info-test.plist, 2.GoogleService-Info-prdn.plist for UAT and Production. For installing crashlytics using firebase i have followed firebase documentation https://firebase.google.com/docs/crashlytics/get-started?authuser=1#ios. But when i try to run, it throws error in build phase while running script.

I tried without changing config file name and it worked.

Error msg at build phase while running fabric run script "Could not get GOOGLE_APP_ID in Google Services file from build environment".

Can anyone suggest better solution to achieve my requirement.

答:
I had the same error, also due to the fact that I have multiple bundle identifier and therefore I have a build phase script called Firebase Script (that pinpoints to the correct GoogleService-Info.plist ) that was running after the Crashlytics script.
The solution is to run Firebase Script before the Crashlytics script.


答:
The doctype declaration should be the first thing in an HTML document, before the  tag.

It isn't an HTML tag; it's an instruction to the web browser about what version of the markup language the page is written in.

It's getting simpler with HTML5: <!DOCTYPE html>

If you don't have that proper doctype, the browser won't know to use HTML5.

Title: Whats the point of DOCTYPE?


问:
How should I simplify the code for updating controls on the UI thread by Dispatcher
My codes need to update some UI element by triggerd event, and some of event is trigged in async or background thread, not in STA thread. So I need use Dispatcher.Invoke in event handler.

But there is so many same situation need to apply. These scattered thread-safe code makes the project codes look not elegant at all, I hope there is a way can improve it.

Here is the sample code of fire event in other thread(not real code):

```<code>//heres code just to simulate triggering events on non-STA threads
public static class MyAsyncClass
{
    public static event Action MyEvent;
    public static void AsyncCallEvent()
    {
        Task.Run(() => MyEvent?.Invoke());
    }
}
public class MyWindow : Window
{
    //...
    private void OtherMethod()
    {
        //safe
        UpdateText1();
        //throw exception
        AsyncCallEvent();
    }
    private void Init()
    {
        MyAsyncClass.MyEvent += UpdateText1;
    }
    private void UpdateText1()
    {
        //will throw exception in cross-thread invoking
        MyTextBox1.Text = "NewText";
        //safe but noisy
        Dispatcher.Invoke(() => MyTextBox1.Text = "NewText");
    }
    //some else method may will be invoke by cross-thread
    private void UpdateText2(){}...
    private void UpdateText3(){}...
    private void UpdateText4(){}...
    private void UpdateText5(){}...
    //...
}
</code>```

Sure, use Dispatcher.Invoke is definitely better, but if add it to all event handler that may potentially be called in async, the code will become make people unpleasant.

Is there a cleaner solution?

答:
Well, you could invoke UpdateText() itself on the dispatcher thread:

```<code>private void Init()
{
    MyAsyncClass.MyEvent += () => Dispatcher.Invoke(UpdateText);
}

private void UpdateText()
{
    MyTextBox.Text = "NewText";
}
</code>```

But what is truly ugly about your code is that you are using Task.Run to explicitly execute the event handler on another thread in MyAsyncClass. You should invoke the event handler on the same thread where the event was raised. It's then up to the subscriber of the event to choose whether to offload the code in the event handler to another thread.

Body:
My codes need to update some UI element by triggerd event, and some of event is trigged in async or background thread, not in STA thread. So I need use Dispatcher.Invoke in event handler.

But there is so many same situation need to apply. These scattered thread-safe code makes the project codes look not elegant at all, I hope there is a way can improve it.

Here is the sample code of fire event in other thread(not real code):

//heres code just to simulate triggering events on non-STA threads
public static class MyAsyncClass
{
    public static event Action MyEvent;
    public static void AsyncCallEvent()
    {
        Task.Run(() => MyEvent?.Invoke());
    }
}
public class MyWindow : Window
{
    //...
    private void OtherMethod()
    {
        //safe
        UpdateText1();
        //throw exception
        AsyncCallEvent();
    }
    private void Init()
    {
        MyAsyncClass.MyEvent += UpdateText1;
    }
    private void UpdateText1()
    {
        //will throw exception in cross-thread invoking
        MyTextBox1.Text = "NewText";
        //safe but noisy
        Dispatcher.Invoke(() => MyTextBox1.Text = "NewText");
    }
    //some else method may will be invoke by cross-thread
    private void UpdateText2(){}...
    private void UpdateText3(){}...
    private void UpdateText4(){}...
    private void UpdateText5(){}...
    //...
}

Sure, use Dispatcher.Invoke is definitely better, but if add it to all event handler that may potentially be called in async, the code will become make people unpleasant.

Is there a cleaner solution?

Body:
Well, you could invoke UpdateText() itself on the dispatcher thread:

private void Init()
{
    MyAsyncClass.MyEvent += () => Dispatcher.Invoke(UpdateText);
}

private void UpdateText()
{
    MyTextBox.Text = "NewText";
}

But what is truly ugly about your code is that you are using Task.Run to explicitly execute the event handler on another thread in MyAsyncClass. You should invoke the event handler on the same thread where the event was raised. It's then up to the subscriber of the event to choose whether to offload the code in the event handler to another thread.


问:
UWP C# mouse control with gestures
I'm working on implementation of controlling mouse cursor with gestures recognihened with depth camera. I wanna move cursor and perform left mouse click. How it can be implemented in UWP C#?

I have tryed this for mouse move and it works OK, but events of the other objects are not triggered (controlling with mouse everything is good):

```<code>Window.Current.CoreWindow.PointerPosition = new Point(pointerPosition.X - deltaX, pointerPosition.Y + deltaY);
</code>```

For mouse click I've tried this:

```<code>    [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
    public static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint cButtons, uint dwExtraInfo);
    //Mouse actions
    private const uint MOUSEEVENTF_LEFTDOWN = 0x0002;
    private const uint MOUSEEVENTF_LEFTUP = 0x0004;

    public async System.Threading.Tasks.Task DoMouseClickAsync()
    {
        //Call the imported function with the cursor's current position

        await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
        {
            var x = (uint)Window.Current.CoreWindow.PointerPosition.X;
            var y = (uint)Window.Current.CoreWindow.PointerPosition.Y;

            mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, x, y, 0, 0);
        });
    }
</code>```

But no reaction. Could you give me a piece of advice?)

答: As mention in this answer, mouse_event cannot be used within a UWP app (for obvious security reason).</p>

Title: UWP C# mouse control with gestures

Body:
I'm working on implementation of controlling mouse cursor with gestures recognihened with depth camera. I wanna move cursor and perform left mouse click. How it can be implemented in UWP C#?

I have tryed this for mouse move and it works OK, but events of the other objects are not triggered (controlling with mouse everything is good):

Window.Current.CoreWindow.PointerPosition = new Point(pointerPosition.X - deltaX, pointerPosition.Y + deltaY);

For mouse click I've tried this:

    [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
    public static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint cButtons, uint dwExtraInfo);
    //Mouse actions
    private const uint MOUSEEVENTF_LEFTDOWN = 0x0002;
    private const uint MOUSEEVENTF_LEFTUP = 0x0004;

    public async System.Threading.Tasks.Task DoMouseClickAsync()
    {
        //Call the imported function with the cursor's current position

        await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
        {
            var x = (uint)Window.Current.CoreWindow.PointerPosition.X;
            var y = (uint)Window.Current.CoreWindow.PointerPosition.Y;

            mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, x, y, 0, 0);
        });
    }

But no reaction. Could you give me a piece of advice?)


问:
How do you call a button in another sheet using another button in Excel?
I have a command button in Sheet1 and I want to activate it using button (form control) in Sheet2.

I have written on Module1 (almost same code with command button in Sheet1)

```<code>Function DataUpdate()
If (validateVer() = False) Then
    Exit Function
End If

Dim AsCn, AsRs, SQL
Dim x, y, WDATE, NGQTY, FAQTY, RWQTY, RNQTY, TotalCell, TotalCellx
Dim FA_TBL As Variant   ' (y, x)
Dim RW_TBL As Variant   ' (y, x)
Dim RN_TBL As Variant   ' (y, x)
Dim NG_TBL As Variant   ' (y, x)

'Sheet => Table
Sheet1.Range("C2:GS2").Select
Selection.ClearContents
FA_TBL = Sheet1.Range("A2:GS2")
Sheet1.Range("C4:GS4").Select
Selection.ClearContents
RW_TBL = Sheet1.Range("A4:GS4")
Sheet1.Range("C5:GS5").Select
Selection.ClearContents
RN_TBL = Sheet1.Range("A5:GS5")
Sheet1.Range("A9:GS208").Select
Selection.ClearContents
Sheet1.Range("C9").Select
NG_TBL = Sheet1.Range("A8:GS208")
</code>```

...

```<code>Sheet1.Range("A2:GS2") = FA_TBL
Sheet1.Range("A4:GS4") = RW_TBL
Sheet1.Range("A5:GS5") = RN_TBL
Sheet1.Range("A8:GS208") = NG_TBL
</code>```

...

```<code>Sheet1.Range("A8:" & TotalCellx & "100").Select
Selection.Sort Key1:=Range(TotalCellx & "9"), Order1:=xlDescending, Header:=xlGuess _
    , OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
    SortMethod:=xlPinYin
Sheet1.Range("C9").Select
End Function
</code>```

I have written on Module2 (code for my form control button at Sheet2):

```<code>Sub Command1_Click()
Sheet1.Range("C8:GF8").Value = Sheet1.Range("C240:GF240").Value
Sheet1.Range("B7").Value = Sheet1.Range("B240").Value
r = DataUpdate()
End Sub
</code>```

However, I get the

"Run-time error '1004': Select method of Range class failed".

Is there any way I can call or link my command button at Sheet1 to my form control button at Sheet2?

答:
In Sheet1

```<code>Public Sub ClickMe()
   MsgBox "You Clicked"
End Sub
</code>```

In Sheet2 CommandButton Click Code

```<code>Private Sub CommandButton1_Click()
   Sheets("Sheet1").ClickMe
End Sub
</code>```

Making the Routine Public makes it callable from outside the Sheet

Body:
I have a command button in Sheet1 and I want to activate it using button (form control) in Sheet2.

I have written on Module1 (almost same code with command button in Sheet1)

Function DataUpdate()
If (validateVer() = False) Then
    Exit Function
End If

Dim AsCn, AsRs, SQL
Dim x, y, WDATE, NGQTY, FAQTY, RWQTY, RNQTY, TotalCell, TotalCellx
Dim FA_TBL As Variant   ' (y, x)
Dim RW_TBL As Variant   ' (y, x)
Dim RN_TBL As Variant   ' (y, x)
Dim NG_TBL As Variant   ' (y, x)

'Sheet => Table
Sheet1.Range("C2:GS2").Select
Selection.ClearContents
FA_TBL = Sheet1.Range("A2:GS2")
Sheet1.Range("C4:GS4").Select
Selection.ClearContents
RW_TBL = Sheet1.Range("A4:GS4")
Sheet1.Range("C5:GS5").Select
Selection.ClearContents
RN_TBL = Sheet1.Range("A5:GS5")
Sheet1.Range("A9:GS208").Select
Selection.ClearContents
Sheet1.Range("C9").Select
NG_TBL = Sheet1.Range("A8:GS208")

...

Sheet1.Range("A2:GS2") = FA_TBL
Sheet1.Range("A4:GS4") = RW_TBL
Sheet1.Range("A5:GS5") = RN_TBL
Sheet1.Range("A8:GS208") = NG_TBL

...

Sheet1.Range("A8:" & TotalCellx & "100").Select
Selection.Sort Key1:=Range(TotalCellx & "9"), Order1:=xlDescending, Header:=xlGuess _
    , OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
    SortMethod:=xlPinYin
Sheet1.Range("C9").Select
End Function

I have written on Module2 (code for my form control button at Sheet2):

Sub Command1_Click()
Sheet1.Range("C8:GF8").Value = Sheet1.Range("C240:GF240").Value
Sheet1.Range("B7").Value = Sheet1.Range("B240").Value
r = DataUpdate()
End Sub

However, I get the

"Run-time error '1004': Select method of Range class failed".

Is there any way I can call or link my command button at Sheet1 to my form control button at Sheet2?

Body:
In Sheet1

Public Sub ClickMe()
   MsgBox "You Clicked"
End Sub

In Sheet2 CommandButton Click Code

Private Sub CommandButton1_Click()
   Sheets("Sheet1").ClickMe
End Sub

Making the Routine Public makes it callable from outside the Sheet


问:
I need first 3 digit number of version from AssemblyInfo.cs using powershell script
In our project, We have AssemblyInfo.cs

Here is some code...

```<code> [assembly: AssemblyVersion("1.5.26.0")]
 [assembly: AssemblyFileVersion("1.5.26.0")]
</code>```

What I want is the first three-digits numbers of the version.

I have one Powershell script, which gets the version but I need only first three digits

```<code>$assemblyInfoPath = "D:\PC- Downloads\AssemblyInfo.cs"

$regex = '^\[assembly: AssemblyVersion\("(.*?)"\)\]'
$assemblyInfo = Get-Content $assemblyInfoPath -Raw

  $version = [Regex]::Match(
    $assemblyInfo,
    $regex,
    [System.Text.RegularExpressions.RegexOptions]::Multiline
).Groups[1].Value
</code>```

reference link: Put Assembly Version from AssemblyInfo.cs in Web.config

Is anyone have an idea of how I can achieve?

答:
Hmmm ... I'll try ... assumed you have the source string saved to variable $sourceString:

```<code>$sourceString = '[assembly: AssemblyVersion("1.5.26.0")]'
</code>```

You can cut of everything you don't need and cast the result to a proper dot Net Version type:

```<code>[VERSION]$VersionString = $sourceString -replace '^.+((\d+\.){3}\d+).+', '$1'
</code>```

Now you can access all single elements by their name:

```<code>$VersionString.Major
$VersionString.Minor
$VersionString.Build
$VersionString.Revision

$VersionString
</code>```

Result would be this:

```<code>1
5
26
0

Major  Minor  Build  Revision
---- - ---- - ---- - --------
1      5      26     0
</code>```

Now you can re-join them  as you need them

```<code>$DhartisNeed = '{0}.{1}.{2}' -f $VersionString.Major,$VersionString.Minor,$VersionString.Build
$DhartisNeed
</code>```

Result would be this:

```<code>1.5.26
</code>```

Body:
In our project, We have AssemblyInfo.cs

Here is some code...

 [assembly: AssemblyVersion("1.5.26.0")]
 [assembly: AssemblyFileVersion("1.5.26.0")]

What I want is the first three-digits numbers of the version.

I have one Powershell script, which gets the version but I need only first three digits

$assemblyInfoPath = "D:\PC- Downloads\AssemblyInfo.cs"

$regex = '^\[assembly: AssemblyVersion\("(.*?)"\)\]'
$assemblyInfo = Get-Content $assemblyInfoPath -Raw

  $version = [Regex]::Match(
    $assemblyInfo,
    $regex,
    [System.Text.RegularExpressions.RegexOptions]::Multiline
).Groups[1].Value

reference link: Put Assembly Version from AssemblyInfo.cs in Web.config

Is anyone have an idea of how I can achieve?

Body:
Hmmm ... I'll try ... assumed you have the source string saved to variable $sourceString:

$sourceString = '[assembly: AssemblyVersion("1.5.26.0")]'

You can cut of everything you don't need and cast the result to a proper dot Net Version type:

[VERSION]$VersionString = $sourceString -replace '^.+((\d+\.){3}\d+).+', '$1'

Now you can access all single elements by their name:

$VersionString.Major
$VersionString.Minor
$VersionString.Build
$VersionString.Revision

$VersionString

Result would be this:

1
5
26
0

Major  Minor  Build  Revision
---- - ---- - ---- - --------
1      5      26     0

Now you can re-join them  as you need them

$DhartisNeed = '{0}.{1}.{2}' -f $VersionString.Major,$VersionString.Minor,$VersionString.Build
$DhartisNeed

Result would be this:

1.5.26


问:
Starting Cassandra with docker gives error
While starting cassandra with the below command, gives the error as

docker: invalid reference format: repository name must be lowercase. See 'docker run --help'.

```<code>docker run -e DS_LICENSE=accept --memory 4g -e CASSANDRA_ENDPOINT_SNITCH="GossipingPropertyFileSnitch" CASSANDRA_DC="testDC" CASSANDRA_RACK="testRack" DS_LICENSE=accept --memory 4g --name cassandra -d datastax/dse-server -g -s -k -v /Users/test/cassandranode01:/var/lib/cassandra
</code>```

Below is my repository screenshot

Please assist me on this.

答:
could you try using a specific version tag of DSE like 6.7.8? Latest tag is not working anymore.

Like this

```<code>docker run -e DS_LICENSE=accept --memory 4g -e CASSANDRA_ENDPOINT_SNITCH="GossipingPropertyFileSnitch" CASSANDRA_DC="testDC" CASSANDRA_RACK="testRack" DS_LICENSE=accept --memory 4g --name cassandra -d datastax/dse-server:6.7.8 -g -s -k -v /Users/test/cassandranode01:/var/lib/cassandra
</code>```

Body:
While starting cassandra with the below command, gives the error as

docker: invalid reference format: repository name must be lowercase. See 'docker run --help'.

docker run -e DS_LICENSE=accept --memory 4g -e CASSANDRA_ENDPOINT_SNITCH="GossipingPropertyFileSnitch" CASSANDRA_DC="testDC" CASSANDRA_RACK="testRack" DS_LICENSE=accept --memory 4g --name cassandra -d datastax/dse-server -g -s -k -v /Users/test/cassandranode01:/var/lib/cassandra

Below is my repository screenshot

Please assist me on this.

Body:
could you try using a specific version tag of DSE like 6.7.8? Latest tag is not working anymore.

Like this

docker run -e DS_LICENSE=accept --memory 4g -e CASSANDRA_ENDPOINT_SNITCH="GossipingPropertyFileSnitch" CASSANDRA_DC="testDC" CASSANDRA_RACK="testRack" DS_LICENSE=accept --memory 4g --name cassandra -d datastax/dse-server:6.7.8 -g -s -k -v /Users/test/cassandranode01:/var/lib/cassandra


问:
S3 Policy Allow Domains and Ip Address With OR Condition
I have a policy

```<code> {
    "Version": "2008-10-17",
     "Statement": [
    {
        "Sid": "IPALLOW",
        "Effect": "Allow",
        "Principal": {
            "AWS": "*"
        },
        "Action": "s3:GetObject",
        "Resource": "arn:aws:s3:::bucket/*",
        "Condition": {
            "StringLike": {
                "aws:Referer": [
                    "https://domain/*",
                    "http://domain/*",
                    "http://domain/*"
                ]
            },
            "IpAddress": {
                "aws:SourceIp": [
                    "ip/32",
                    "ip/32",
                    "ip/32",
                    "ip/32"
                ]
            }
        }
    }
  ]
}
</code>```

it's just allowing domains to access objects
seems like I require or condition but cannot find it anywhere how

答:
Creating two objects to allow and Deny worked.

```<code> {
"Version": "2008-10-17",
"Statement": [
    {
        "Sid": "IPALLOW",
        "Effect": "Allow",
        "Principal": {
            "AWS": "*"
        },
        "Action": "s3:GetObject",
        "Resource": "arn:aws:s3:::bucket/*",
        "Condition": {
            "StringLike": {
                "aws:Referer": [
                    "https://domain/*",
                    "http://domain/*",
                    "http://domain/*"
                ]
            }
        }
    },
    {
        "Sid": "IPALLOW",
        "Effect": "DENY",
        "Principal": {
            "AWS": "*"
        },
        "Action": "s3:GetObject",
        "Resource": "arn:aws:s3:::ip/*",
        "Condition": {
            "NotIpAddress": {
                "aws:SourceIp": [
                    "ip/32",
                    "ip/32",
                    "ip/32",
                    "ip/32"
                ]
            }
        }
    }
]
</code>```

}

Body:
I have a policy

 {
    "Version": "2008-10-17",
     "Statement": [
    {
        "Sid": "IPALLOW",
        "Effect": "Allow",
        "Principal": {
            "AWS": "*"
        },
        "Action": "s3:GetObject",
        "Resource": "arn:aws:s3:::bucket/*",
        "Condition": {
            "StringLike": {
                "aws:Referer": [
                    "https://domain/*",
                    "http://domain/*",
                    "http://domain/*"
                ]
            },
            "IpAddress": {
                "aws:SourceIp": [
                    "ip/32",
                    "ip/32",
                    "ip/32",
                    "ip/32"
                ]
            }
        }
    }
  ]
}

it's just allowing domains to access objects
seems like I require or condition but cannot find it anywhere how

Body:
Creating two objects to allow and Deny worked.

 {
"Version": "2008-10-17",
"Statement": [
    {
        "Sid": "IPALLOW",
        "Effect": "Allow",
        "Principal": {
            "AWS": "*"
        },
        "Action": "s3:GetObject",
        "Resource": "arn:aws:s3:::bucket/*",
        "Condition": {
            "StringLike": {
                "aws:Referer": [
                    "https://domain/*",
                    "http://domain/*",
                    "http://domain/*"
                ]
            }
        }
    },
    {
        "Sid": "IPALLOW",
        "Effect": "DENY",
        "Principal": {
            "AWS": "*"
        },
        "Action": "s3:GetObject",
        "Resource": "arn:aws:s3:::ip/*",
        "Condition": {
            "NotIpAddress": {
                "aws:SourceIp": [
                    "ip/32",
                    "ip/32",
                    "ip/32",
                    "ip/32"
                ]
            }
        }
    }
]

}


问:
Stripe Node JS integration no error callback
I've been trying to integrate Stripe with Node JS, but I can't get Stripe to return the error. I pass malformed data on purpose, but I still can not get the error back.

I'm new to Node JS.

Here is Stripe's official doc:
https://stripe.com/docs/api/charges/create

Here is my code:

```<code>Parse.Cloud.define("addCredit", (request) => {
// Use stripe API and your own 'secret key'
var stripe = require('stripe')('xdsewew');

// Charge user's card
stripe.charges.create({
    amount: request.params.amount,
    currency: 'usd',
    source: request.params.token,
    description: request.params.userId,
  }, function(error, charge) {
      return(error);
  });
</code>```

});

Maybe I'm not doing it right when I try to return the error?

答:
I tried the same and I'm able to log the error

```<code>  var stripe = require("stripe")("sk_test_4eC39HqLyjWDarjtT1zdp7d");

    stripe.charges.create(
      {
        amount: 2000,
        currency: "usd",
        source: "tok_mastercard",
        description: "My First Test Charge (created for API docs)",
      },
      function (err, charge) {
        if (err) {
          // different ways to log error
          console.log("error message -> ", err.message);
          console.log("error type - >", err.type);
          console.log("eror raw -> ", err.raw);
          return err;
        }
        console.log(charge);
      }
    );
</code>```

Hope this works for you :)

Body:
I've been trying to integrate Stripe with Node JS, but I can't get Stripe to return the error. I pass malformed data on purpose, but I still can not get the error back.

I'm new to Node JS.

Here is Stripe's official doc:
https://stripe.com/docs/api/charges/create

Here is my code:

Parse.Cloud.define("addCredit", (request) => {
// Use stripe API and your own 'secret key'
var stripe = require('stripe')('xdsewew');

// Charge user's card
stripe.charges.create({
    amount: request.params.amount,
    currency: 'usd',
    source: request.params.token,
    description: request.params.userId,
  }, function(error, charge) {
      return(error);
  });

});

Maybe I'm not doing it right when I try to return the error?

Body:
I tried the same and I'm able to log the error

  var stripe = require("stripe")("sk_test_4eC39HqLyjWDarjtT1zdp7d");

    stripe.charges.create(
      {
        amount: 2000,
        currency: "usd",
        source: "tok_mastercard",
        description: "My First Test Charge (created for API docs)",
      },
      function (err, charge) {
        if (err) {
          // different ways to log error
          console.log("error message -> ", err.message);
          console.log("error type - >", err.type);
          console.log("eror raw -> ", err.raw);
          return err;
        }
        console.log(charge);
      }
    );

Hope this works for you :)


问:
Decomposing tuples in function arguments
In python I can do this:

def f((a, b)):
    return a + b

d = (1, 2)
f(d)
```

<p>Here the passed in tuple is being decomposed while its being passed to <code>f</code>.</p>

<p>Right now in scala I am doing this:</p>

<pre class="lang-scala prettyprint-override"><code>def f(ab: (Int, Int)): Int = {
    val (a, b) = ab
    a + b
}

val d = (1, 2)
f(d)
</code>```

Is there something I can do here so that the decomposition happens while the arguments are passed in? Just curious.

答:
Starting in Scala 3, with the improved tupled function feature:

```<code>// val tuple = (1, 2)
// def f(a: Int, b: Int): Int = a + b
f.tupled(tuple)
// 3
</code>```

Play with it in Scastie

Body:
In python I can do this:

def f((a, b)):
    return a + b

d = (1, 2)
f(d)

Here the passed in tuple is being decomposed while its being passed to f.

Right now in scala I am doing this:

def f(ab: (Int, Int)): Int = {
    val (a, b) = ab
    a + b
}

val d = (1, 2)
f(d)

Is there something I can do here so that the decomposition happens while the arguments are passed in? Just curious.

Body:
Starting in Scala 3, with the improved tupled function feature:

// val tuple = (1, 2)
// def f(a: Int, b: Int): Int = a + b
f.tupled(tuple)
// 3

Play with it in Scastie


问:
Rust features which allow the optimizer to change the program's result?
In some languages, optimization is allowed to change the program execution result. For example,

C++11 has the concept of "copy-elision" which allows the optimizer to ignore the copy constructor (and its side-effects) in some circumstances.

Swift has the concept of "imprecise lifetimes" which allows the optimizer to release objects at any time after last usage before the end of lexical scope.

In both cases, optimizations are not guaranteed to happen, therefore the program execution result can be significantly different based on the optimizer implementations (e.g. debug vs. release build)

Copying can be skipped, object can die while a reference is alive. The only way to deal with these behaviors is by being defensive and making your program work correctly regardless if the optimizations happen or not. If you don't know about the existence of this behavior, it's impossible to write correct programs with the tools.

This is different from "random operations" which are written by the programmer to produce random results intentionally. These behaviors are (1) done by optimizer and (2) can randomize execution result regardless of programmer intention. This is done by the language designer's intention for better performance. A sort of trade-off between performance and predictability.

Does Rust have (or consider) any of this kind of behavior? Any optimization that is allowed to change program execution result for better performance. If it has any, what is the behavior and why is it allowed?

I know the term "execution result" could be vague, but I don't know a proper term for this. I'm sorry for that.

I'd like to collect every potential case here, so everyone can be aware of them and be prepared for them. Please post any case as an answer (or comment) if you think your case produces different results.

I think all arguable cases are worth to mention. Because someone can be helped a lot by reading the case details.

答:
There are far fewer foot-guns in Rust when compared to C++. In general, they revolve around unsafe, raw pointers and lifetimes derived from them or any form of undefined behavior, which is really undefined in Rust as well. However, if your code compiles (and, if in doubt, passes cargo miri test), you most likely won't see surprising behavior.

Two examples that come to mind which can be surprising:

The lifetime of a MutexGuard; the example comes from the book:

```<code>while let Ok(job) = receiver.lock().unwrap().recv() {
    job();
}
</code>```

One might think/hope that the Mutex on the receiver is released once a job has been acquired and job() executes while other threads can receive jobs. However, due to the way value-expressions in place-expressions contexts work in conjunction with temporary lifetimes (the MutexGuard needs an anonymous lifetime referencing receiver), the MutexGuard is held for the entirety of the while-block. This means only one thread will ever execute jobs.

If you do

```<code>loop {
    let job = receiver.lock().unwrap().recv().unwrap();
    job();
}
</code>```

this will allow multiple threads to run in parallel. It's not obvious why this is.

Multiple times there have been questions regarding const. There is no guarantee by the compiler if a const actually exists only once (as an optimization) or is instantiated wherever it is used. The second case is the way one should think about const, there is no guarantee that this is what the compiler does, though. So this can happen:

```<code>const EXAMPLE: Option<i32> = Some(42);
fn main() {
    assert_eq!(EXAMPLE.take(), Some(42));
    assert_eq!(EXAMPLE, Some(42)); // Where did this come from?
}
</code>```

Body:
There are far fewer foot-guns in Rust when compared to C++. In general, they revolve around unsafe, raw pointers and lifetimes derived from them or any form of undefined behavior, which is really undefined in Rust as well. However, if your code compiles (and, if in doubt, passes cargo miri test), you most likely won't see surprising behavior.

Two examples that come to mind which can be surprising:

The lifetime of a MutexGuard; the example comes from the book:

while let Ok(job) = receiver.lock().unwrap().recv() {
    job();
}

One might think/hope that the Mutex on the receiver is released once a job has been acquired and job() executes while other threads can receive jobs. However, due to the way value-expressions in place-expressions contexts work in conjunction with temporary lifetimes (the MutexGuard needs an anonymous lifetime referencing receiver), the MutexGuard is held for the entirety of the while-block. This means only one thread will ever execute jobs.

If you do

loop {
    let job = receiver.lock().unwrap().recv().unwrap();
    job();
}

this will allow multiple threads to run in parallel. It's not obvious why this is.

Multiple times there have been questions regarding const. There is no guarantee by the compiler if a const actually exists only once (as an optimization) or is instantiated wherever it is used. The second case is the way one should think about const, there is no guarantee that this is what the compiler does, though. So this can happen:

const EXAMPLE: Option<i32> = Some(42);
fn main() {
    assert_eq!(EXAMPLE.take(), Some(42));
    assert_eq!(EXAMPLE, Some(42)); // Where did this come from?
}


问:
System.NullReferenceException: Object reference not set to an instance of an object

Possible Duplicate:

  System.NullReferenceException: Object reference not set to an instance of an object

look at my code

```<code>if (ViewState["Edit"].ToString() == "new") {
}
else {
      row = _section.GetBannerEntry(ViewState["Edit"].ToString());
}
</code>```

I was getting the error on this line if (ViewState["Edit"].ToString() == "new") I replaced with if (ViewState["Edit"] != null && ViewState["Edit"].ToString() == "new") it works.

Now I am getting the same error here in else row = _section.GetBannerEntry(ViewState["Edit"].ToString());

please help

答: Well, either ViewState is null or ViewState["Edit"] is returning null...

Body:
Possible Duplicate:

  System.NullReferenceException: Object reference not set to an instance of an object

look at my code

if (ViewState["Edit"].ToString() == "new") {
}
else {
      row = _section.GetBannerEntry(ViewState["Edit"].ToString());
}

I was getting the error on this line if (ViewState["Edit"].ToString() == "new") I replaced with if (ViewState["Edit"] != null && ViewState["Edit"].ToString() == "new") it works.

Now I am getting the same error here in else row = _section.GetBannerEntry(ViewState["Edit"].ToString());

please help


问:
How to Programmatically Close a Modal with Materialize.css
I am using materialize.css and have been trying to programmatically close a modal and then immediately open another.

This is the code I am currently using to open/close:

```<code>$('.modal').modal('close', "#modal1");
$('.modal').modal('open', "#modal2");
</code>```

What actually happens is that when I call these functions, #modal1 closes successfully, but its backdrop remains there as it is.

At exactly the same time, #modal2 opens up and then immediately (in about 200 ms or so) closes back. Again, the backdrop stays unchanged.

Can I please get help to solve this?

The documentation calls jQuery old. So, am I using some depreacated method, and should I use a vanilla JavaScript equivalent for the same? What, if yes?

答:
No-JQuery way. First you should get an instance of modal that you intend to close. If e.g. on init you write:

```<code>var elems = document.querySelectorAll(".modal");
M.Modal.init(elems);
</code>```

so in elems we have NodeList of all modals, for example we have three modals, to close second one you can say:

```<code>elems[1].M_Modal.close();
</code>```

to open third:

```<code>elems[2].M_Modal.open();
</code>```

Body:
I am using materialize.css and have been trying to programmatically close a modal and then immediately open another.

This is the code I am currently using to open/close:

$('.modal').modal('close', "#modal1");
$('.modal').modal('open', "#modal2");

What actually happens is that when I call these functions, #modal1 closes successfully, but its backdrop remains there as it is.

At exactly the same time, #modal2 opens up and then immediately (in about 200 ms or so) closes back. Again, the backdrop stays unchanged.

Can I please get help to solve this?

The documentation calls jQuery old. So, am I using some depreacated method, and should I use a vanilla JavaScript equivalent for the same? What, if yes?

Body:
No-JQuery way. First you should get an instance of modal that you intend to close. If e.g. on init you write:

var elems = document.querySelectorAll(".modal");
M.Modal.init(elems);

so in elems we have NodeList of all modals, for example we have three modals, to close second one you can say:

elems[1].M_Modal.close();

to open third:

elems[2].M_Modal.open();


问:
RenderedImage to BufferedImage for multipage-tiff reading
I am using JAI to load in multipage TIFF images

```<code>File file = workArea[0];
SeekableStream s = new FileSeekableStream(file);

TIFFDecodeParam param = null;

ImageDecoder dec = ImageCodec.createImageDecoder("tiff", s, param);

//first page
RenderedImage op1 =
    new NullOpImage(dec.decodeAsRenderedImage(0),
                    null,
                    OpImage.OP_IO_BOUND,
                    null);

BufferedImage pg1 = new BufferedImage(op1.getWidth(), op1.getHeight(),
                                      BufferedImage.TYPE_INT_RGB);
pg1.getGraphics().drawImage((Image) op1, 0, 0, null);
</code>```

However, in the last line I get a runtime error of:

```<code> Exception in thread "main" java.lang.ClassCastException:
      javax.media.jai.MullOpImage cannot be cast to java.awt.Image
</code>```

I clear the RenderedImage after attempting to set the BufferedImage so I don't exactly "need" the RenderedImage if there is another method of doing this.

I attempted:

```<code> pg1.setData(op1.getData());
</code>```

and that gives an ArrayIndexOutOfBoundsException. I'm not sure why exactly as pg1's width and height are set by op1's, but there is probably a very valid reason.

答:
The easiest way to load TIFF is using Twelve Monkey with provide plugin to support TIFF format into Standard Java ImageIO.

Just add below Maven dependency,

```<code><dependency>
<groupId>com.twelvemonkeys.imageio</groupId>
<artifactId>imageio-tiff</artifactId>
<version>3.5</version>
</dependency>
</code>```

Now, you will be able to load TIFF file directly Using ImageIO.

```<code>ImageReader imageReader1 = SPI.createReaderInstance();
ImageInputStream iis1 = ImageIO.createImageInputStream(new File("1.tif"));
imageReader1.setInput(iis1);
BufferedImage = imageReader1.read(0);
</code>```

It is very easy and reliable because it uses standard Java ImageIO API for all processing.

Only the Plugin from Twelve Monkey provide the SPI plugin to provide support of TIFF.

Adding here one example program which is running is Java 8 and it reads TIFF files and create a single multi-page TIFF file:

```<code>BufferedImage b1 = null;
BufferedImage b2 = null;

TIFFImageReaderSpi SPI = new TIFFImageReaderSpi();

ImageReader imageReader1 = SPI.createReaderInstance();
ImageInputStream iis1 = ImageIO.createImageInputStream(new File("1.tif"));
imageReader1.setInput(iis1);
b1 = imageReader1.read(0);

ImageReader imageReader2 = SPI.createReaderInstance();
ImageInputStream iis2 = ImageIO.createImageInputStream(new File("2.tif"));
imageReader2.setInput(iis2);
b2 = imageReader2.read(0);

ImageWriter writer = ImageIO.getImageWritersByFormatName("TIFF").next();

writer.setOutput(ImageIO.createImageOutputStream(new File("3.tif")));

ImageWriteParam writeParam = writer.getDefaultWriteParam();
//writeParam.setTilingMode(ImageWriteParam.MODE_EXPLICIT);
//writeParam.setCompressionType("Deflate");

writer.prepareWriteSequence(null);

IIOImage i1 = new IIOImage(b1, null, null);
IIOImage i2 = new IIOImage(b2, null, null);

writer.writeToSequence(i1, writeParam);
writer.writeToSequence(i2, writeParam);

writer.endWriteSequence();
writer.dispose();
</code>```

It is working with Java 8, if someone wants to add compression just comment the line and add appropriate compression name.

Body:
I am using JAI to load in multipage TIFF images

File file = workArea[0];
SeekableStream s = new FileSeekableStream(file);

TIFFDecodeParam param = null;

ImageDecoder dec = ImageCodec.createImageDecoder("tiff", s, param);

//first page
RenderedImage op1 =
    new NullOpImage(dec.decodeAsRenderedImage(0),
                    null,
                    OpImage.OP_IO_BOUND,
                    null);

BufferedImage pg1 = new BufferedImage(op1.getWidth(), op1.getHeight(),
                                      BufferedImage.TYPE_INT_RGB);
pg1.getGraphics().drawImage((Image) op1, 0, 0, null);

However, in the last line I get a runtime error of:

 Exception in thread "main" java.lang.ClassCastException:
      javax.media.jai.MullOpImage cannot be cast to java.awt.Image

I clear the RenderedImage after attempting to set the BufferedImage so I don't exactly "need" the RenderedImage if there is another method of doing this.

I attempted:

 pg1.setData(op1.getData());

and that gives an ArrayIndexOutOfBoundsException. I'm not sure why exactly as pg1's width and height are set by op1's, but there is probably a very valid reason.

Body:
The easiest way to load TIFF is using Twelve Monkey with provide plugin to support TIFF format into Standard Java ImageIO.

Just add below Maven dependency,

<dependency>
<groupId>com.twelvemonkeys.imageio</groupId>
<artifactId>imageio-tiff</artifactId>
<version>3.5</version>
</dependency>

Now, you will be able to load TIFF file directly Using ImageIO.

ImageReader imageReader1 = SPI.createReaderInstance();
ImageInputStream iis1 = ImageIO.createImageInputStream(new File("1.tif"));
imageReader1.setInput(iis1);
BufferedImage = imageReader1.read(0);

It is very easy and reliable because it uses standard Java ImageIO API for all processing.

Only the Plugin from Twelve Monkey provide the SPI plugin to provide support of TIFF.

Adding here one example program which is running is Java 8 and it reads TIFF files and create a single multi-page TIFF file:

BufferedImage b1 = null;
BufferedImage b2 = null;

TIFFImageReaderSpi SPI = new TIFFImageReaderSpi();

ImageReader imageReader1 = SPI.createReaderInstance();
ImageInputStream iis1 = ImageIO.createImageInputStream(new File("1.tif"));
imageReader1.setInput(iis1);
b1 = imageReader1.read(0);

ImageReader imageReader2 = SPI.createReaderInstance();
ImageInputStream iis2 = ImageIO.createImageInputStream(new File("2.tif"));
imageReader2.setInput(iis2);
b2 = imageReader2.read(0);

ImageWriter writer = ImageIO.getImageWritersByFormatName("TIFF").next();

writer.setOutput(ImageIO.createImageOutputStream(new File("3.tif")));

ImageWriteParam writeParam = writer.getDefaultWriteParam();
//writeParam.setTilingMode(ImageWriteParam.MODE_EXPLICIT);
//writeParam.setCompressionType("Deflate");

writer.prepareWriteSequence(null);

IIOImage i1 = new IIOImage(b1, null, null);
IIOImage i2 = new IIOImage(b2, null, null);

writer.writeToSequence(i1, writeParam);
writer.writeToSequence(i2, writeParam);

writer.endWriteSequence();
writer.dispose();

It is working with Java 8, if someone wants to add compression just comment the line and add appropriate compression name.


问:
How to Plot Several 3D Trajectories in Julia (using a for-loop, presumably?) -- also, how to animate over time?
I am trying to plot a set of 3D trajectories in a single plot in Julia. By 3-D trajectories I mean: different sets of 3-D coordinates over time. These trajectories are stored in a multidimensional array called positions, where the dimensions respectively correspond to the Trajectory ID, X-Y-Z coordinate and Time. For example, positions[75,2,1:100] refers to the Y (2nd) coordinate of the 75th Trajectory, across the first 100 timesteps of the trajectory.

I am trying to figure out why the following code doesn't work:

```<code>using Plots

plotlyjs()

time_indices = 1:100

ax= scatter3d(positions[1,1,time_indices],positions[1,2,time_indices],positions[1,3,time_indices],label="Trajectory 1 for times 1 to 100")

for n in 2:size(positions,1)
    scatter3d!(ax, positions[n,1,time_indices], positions[n,2,time_indices],positions[n,3,time_indices],label="Trajectory $n for times 1 to 100")
end

</code>```

When I run that code, I don't see anything in the Plots window (I'm using Atom), although I don't get any errors / it appears to run successfully. Any thoughts on what I'm doing wrong? Should I use a different backend? It doesn't work on either gr() or plotlyjs() (those are the only ones I know of, based on tutorials I've completed).

Follow up question: once I can successfully plot such 3-D trajectories in a single static plot, I am wondering how you would go about animating them over time (using @gif or @animate macros, presumably)? I am asking this here, because I wasn't able to understand the documentation / tutorial on 3D animations, unfortunately. Googling / other sources have also not helped :(

答:
How to do the second bit (the animation - see details in comments on the accepted answer):</p>

```<code>gr()
anim = @animate for t in time_indices
    all_positions_t = positions[:,:,t] # positions of all trajectories at time t
    scatter3d(all_positions_t[:,1], all_positions_t[:,2],all_positions_t[:,3],label="")
end
gif(anim, "some_file_name.gif", fps=15)
</code>```

Body:
I am trying to plot a set of 3D trajectories in a single plot in Julia. By 3-D trajectories I mean: different sets of 3-D coordinates over time. These trajectories are stored in a multidimensional array called positions, where the dimensions respectively correspond to the Trajectory ID, X-Y-Z coordinate and Time. For example, positions[75,2,1:100] refers to the Y (2nd) coordinate of the 75th Trajectory, across the first 100 timesteps of the trajectory.

I am trying to figure out why the following code doesn't work:

using Plots

plotlyjs()

time_indices = 1:100

ax= scatter3d(positions[1,1,time_indices],positions[1,2,time_indices],positions[1,3,time_indices],label="Trajectory 1 for times 1 to 100")

for n in 2:size(positions,1)
    scatter3d!(ax, positions[n,1,time_indices], positions[n,2,time_indices],positions[n,3,time_indices],label="Trajectory $n for times 1 to 100")
end

When I run that code, I don't see anything in the Plots window (I'm using Atom), although I don't get any errors / it appears to run successfully. Any thoughts on what I'm doing wrong? Should I use a different backend? It doesn't work on either gr() or plotlyjs() (those are the only ones I know of, based on tutorials I've completed).

Follow up question: once I can successfully plot such 3-D trajectories in a single static plot, I am wondering how you would go about animating them over time (using @gif or @animate macros, presumably)? I am asking this here, because I wasn't able to understand the documentation / tutorial on 3D animations, unfortunately. Googling / other sources have also not helped :(

Body:
How to do the second bit (the animation - see details in comments on the accepted answer):

gr()
anim = @animate for t in time_indices
    all_positions_t = positions[:,:,t] # positions of all trajectories at time t
    scatter3d(all_positions_t[:,1], all_positions_t[:,2],all_positions_t[:,3],label="")
end
gif(anim, "some_file_name.gif", fps=15)


问:
Function to validate pin code, why doesn't this code work?
So I have been trying to teach myself how to do this stuff and have had marginal success so far, I'm working on an exercise I found on codewars.com and I'm kind of stuck. The goal is to make a function that verifies the inputted pin meets the requirements, those requirements being:
PIN must be either 4 or 6 digits long and PIN must be strictly numerical

I ran into a number of problems with it and ultimately came to the code below:

```<code>import re
def validate_pin(pin):
    for x in pin:
        if x.isalpha():
            return False
        elif re.match(".", pin):
            return False
    if len(pin) == 4 or len(pin) == 6:
        return True
    else:
        return False
</code>```

I really, really, really, didn't want to ask for help but I have absolutely positively no idea why the above code doesn't work. It returns false on "1234" as input and I have racked my head over this for 2 days now. I refreshed myself on for loops, read up on regex, I tried searching forums but am completely stumped on what to look for. Any help anyone can provide would be greatly and deeply appreciated.

Edit: Wow! I didn't expect such positive feedback I appreciate it everyone! Thanks for helping me understand I have seen where I went wrong and will study it extra hard. Thanks for all the feedback!

答:
I think we can sort it without import, like this :</p>

```<code>def validate_pin(pin):
    return len(pin) in (4, 6) and pin.isdigit()
</code>```

Body:
So I have been trying to teach myself how to do this stuff and have had marginal success so far, I'm working on an exercise I found on codewars.com and I'm kind of stuck. The goal is to make a function that verifies the inputted pin meets the requirements, those requirements being:
PIN must be either 4 or 6 digits long and PIN must be strictly numerical

I ran into a number of problems with it and ultimately came to the code below:

import re
def validate_pin(pin):
    for x in pin:
        if x.isalpha():
            return False
        elif re.match(".", pin):
            return False
    if len(pin) == 4 or len(pin) == 6:
        return True
    else:
        return False

I really, really, really, didn't want to ask for help but I have absolutely positively no idea why the above code doesn't work. It returns false on "1234" as input and I have racked my head over this for 2 days now. I refreshed myself on for loops, read up on regex, I tried searching forums but am completely stumped on what to look for. Any help anyone can provide would be greatly and deeply appreciated.

Edit: Wow! I didn't expect such positive feedback I appreciate it everyone! Thanks for helping me understand I have seen where I went wrong and will study it extra hard. Thanks for all the feedback!

Body:
I think we can sort it without import, like this :

def validate_pin(pin):
    return len(pin) in (4, 6) and pin.isdigit()


问:
How to print tuples of unicode strings in original language (not u'foo' form)
I have a list of tuples of unicode objects:

```<code>>>> t = [('亀',), ('犬',)]
</code>```

Printing this out, I get:

```<code>>>> print t
[('\xe4\xba\x80',), ('\xe7\x8a\xac',)]
</code>```

which I guess is a list of the utf-8 byte-code representation of those strings?

but what I want to see printed out is, surprise:

```<code>[('亀',), ('犬',)]
</code>```

but I'm having an inordinate amount of trouble getting the bytecode back into a human-readable form.

答:
Try:</p>

```<code>import codecs, sys
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
</code>```

OwnerDisplayName: Daniel H

Body:
I have a list of tuples of unicode objects:

>>> t = [('亀',), ('犬',)]

Printing this out, I get:

>>> print t
[('\xe4\xba\x80',), ('\xe7\x8a\xac',)]

which I guess is a list of the utf-8 byte-code representation of those strings?

but what I want to see printed out is, surprise:

[('亀',), ('犬',)]

but I'm having an inordinate amount of trouble getting the bytecode back into a human-readable form.

Body:
Try:

import codecs, sys
sys.stdout = codecs.getwriter('utf8')(sys.stdout)

OwnerDisplayName: MarkusQ


问:
How does this pointer-based strcat work in C?
I have some basic experience with C, but it usually takes me a little while to figure out how to implement something; using pointers and such is still a bit of a mystery to me.

Then I see an example like strcat implementation and I can't follow along. Would someone mind kindly explaining this to a C newcomer?

```<code>char *
my_strcat(char *dest, const char *src)
{
    char *rdest = dest;

    while (*dest)
      dest++;
    while (*dest++ = *src++)
      ;
    return rdest;
}
</code>```

When I read that, I think "rdest = ?, maybe real destination". So set a pointer to the original destination. Then "while (*dest) dest++;", what is that doing? Same with the next line. I don't follow.

Is it using any additional memory to the original two parts (src and dest)? Like in JS, if you concatenate 2 strings, it creates memory for a third string that combines the two, so you have double the memory. How is this avoided in this C implementation (if it is)?

答:
Let's start with the function declaration:

```<code> char * my_strcat(char *dest, const char *src)
</code>```

This function will return a pointer to char, its arguments are also pointers to char, they will point to the beginning of each one of the char arrays that are passed as arguments. Since the src is not to be altered, it can be passed as const.

This assignment:

```<code>char *rdest = dest;
</code>```

Declaring a pointer and making it point to the beginning of array passed through dest pointer.

The cycle:

```<code>while (*dest)
  dest++;
</code>```

As you might know any string in C is null terminated with '\0', turns out that the ASCII value of that null terminator is 0, so you can use it as a stop condition.

So essentially this pointer, which is pointing to the beginning of dest, is being incremented until it finds the end of the string.

The cycle:

```<code>while (*dest++ = *src++)
  ;
</code>```

Now that the dest pointer is pointing to the end of the dest string, it's just incrementing both pointers, and appending every character in the src string starting from first character in src and the end of the dest string. When a \0 is added, again this will be the stop condition, the expression will evaluate to 0, false, and the string will have the null terminator.

The return:

```<code>return rdest;
</code>```

This pointer remained unaltered through the function and is pointing to the beginning of the dest string, which now has the appended src also. That's what we want to return.

Body:
I have some basic experience with C, but it usually takes me a little while to figure out how to implement something; using pointers and such is still a bit of a mystery to me.

Then I see an example like strcat implementation and I can't follow along. Would someone mind kindly explaining this to a C newcomer?

char *
my_strcat(char *dest, const char *src)
{
    char *rdest = dest;

    while (*dest)
      dest++;
    while (*dest++ = *src++)
      ;
    return rdest;
}

When I read that, I think "rdest = ?, maybe real destination". So set a pointer to the original destination. Then "while (*dest) dest++;", what is that doing? Same with the next line. I don't follow.

Is it using any additional memory to the original two parts (src and dest)? Like in JS, if you concatenate 2 strings, it creates memory for a third string that combines the two, so you have double the memory. How is this avoided in this C implementation (if it is)?

Body:
Let's start with the function declaration:

 char * my_strcat(char *dest, const char *src)

This function will return a pointer to char, its arguments are also pointers to char, they will point to the beginning of each one of the char arrays that are passed as arguments. Since the src is not to be altered, it can be passed as const.

This assignment:

char *rdest = dest;

Declaring a pointer and making it point to the beginning of array passed through dest pointer.

The cycle:

while (*dest)
  dest++;

As you might know any string in C is null terminated with '\0', turns out that the ASCII value of that null terminator is 0, so you can use it as a stop condition.

So essentially this pointer, which is pointing to the beginning of dest, is being incremented until it finds the end of the string.

The cycle:

while (*dest++ = *src++)
  ;

Now that the dest pointer is pointing to the end of the dest string, it's just incrementing both pointers, and appending every character in the src string starting from first character in src and the end of the dest string. When a \0 is added, again this will be the stop condition, the expression will evaluate to 0, false, and the string will have the null terminator.

The return:

return rdest;

This pointer remained unaltered through the function and is pointing to the beginning of the dest string, which now has the appended src also. That's what we want to return.


问:
annotations vs annotationEntries in IntelliJ / Kotlin PSI
I have a Kotlin annotation:

```<code>@Retention(AnnotationRetention.SOURCE)
@Target(AnnotationTarget.CLASS)
annotation class Type(
    val type: String
)
</code>```

It can be used on the Kotlin classes:

```<code>@Type(type = "type")
data class Annotated(
    …
)
</code>```

I am analyzing this source code with detekt which provides access to the Kotlin PSI. To get the annotation I use the code like:

```<code>val annotation = klass
    .annotationEntries
    .find {
        "Type" == it?.shortName?.asString()
    }
</code>```

where, klass has a type of KtClass from Kotlin PSI. I've noticed, that KtClass has two properties: annotations and annotationEntries and that annotations is empty for the annotated class above.

What is the difference between annotations and annotationEntries and when should I use what?

答:
Annotation is a declaration (annotation class).

Annotation Entry is an application of annotation (@).

Body:
I have a Kotlin annotation:

@Retention(AnnotationRetention.SOURCE)
@Target(AnnotationTarget.CLASS)
annotation class Type(
    val type: String
)

It can be used on the Kotlin classes:

@Type(type = "type")
data class Annotated(
    …
)

I am analyzing this source code with detekt which provides access to the Kotlin PSI. To get the annotation I use the code like:

val annotation = klass
    .annotationEntries
    .find {
        "Type" == it?.shortName?.asString()
    }

where, klass has a type of KtClass from Kotlin PSI. I've noticed, that KtClass has two properties: annotations and annotationEntries and that annotations is empty for the annotated class above.

What is the difference between annotations and annotationEntries and when should I use what?