问:
Is it a good practice to make a DAO class Comparable type
This is my sample mapping in hibernate

```<code>class ApplnDoc {
    AdmAppln admAppln;
    // getters and setters
}
</code>```

```<code>class AdmAppln {
    Set<Student> student;
    // getters and setters
}
</code>```

```<code>class Student {
    int id;
    String registerNo;
    AdmAppln admAppln;
    // getters and setters
}
</code>```

In ApplnDoc table we are storing images of all candidates. AdmAppln is for storing admission details, Student is for storing student details. Even if AdmAppln is having a Set of Student, only one record of Student will be present for a particular AdmAppln id (under one AdmAppln only one Student).

Now I want to write few data from to these tables, into an Excel file, whose records must be sorted in the order of registerNo (if it is present), otherwise using id of the Student. We are using XSSFWorkbook class under org.apache.poi.xssf.usermodel package for doing operations on Excel sheet. Here I found a way to sort the excel sheet, but I tried and found a way in code itself using Comparable interface.

This is what I did in ApplnDoc class

```<code>public int compareTo(ApplnDoc otherData) {
    if(new ArrayList<Student>(this.admAppln.getStudents()).get(0).getRegisterNo() != null &&
       !new ArrayList<Student>(this.admAppln.getStudents()).get(0).getRegisterNo().isEmpty() &&
       new ArrayList<Student>(otherData.admAppln.getStudents()).get(0).getRegisterNo() != null &&
       !new ArrayList<Student>(otherData.admAppln.getStudents()).get(0).getRegisterNo().isEmpty()) {

            return new ArrayList<Student>(this.admAppln.getStudents()).get(0).getRegisterNo()
                   .compareTo
                   (new ArrayList<Student>(otherData.admAppln.getStudents()).get(0).getRegisterNo());
    } else {
            return new ArrayList<Student>(this.admAppln.getStudents()).get(0).getId() -
                   new ArrayList<Student>(otherData.admAppln.getStudents()).get(0).getId();
    }
}
</code>```

Since there is no get() method in Set interface the only way to get Student's registerNo from AdmAppln was to convert it to a list. Then I sorted the list and then it was iterated to generate the excel file.

Is the above mentioned comparison mechanism a proper one or is there a better way? Why I am asking this question because when the Hibernate session is closed and in my compareTo if I'm accessing the child table columns, then I will be getting Invocation exception.

答: You need to load the entire object tree before closing the session else you will get Exception. By the way you can always sort records with the query itself.</p>

Body:
This is my sample mapping in hibernate

class ApplnDoc {
    AdmAppln admAppln;
    // getters and setters
}

class AdmAppln {
    Set<Student> student;
    // getters and setters
}

class Student {
    int id;
    String registerNo;
    AdmAppln admAppln;
    // getters and setters
}

In ApplnDoc table we are storing images of all candidates. AdmAppln is for storing admission details, Student is for storing student details. Even if AdmAppln is having a Set of Student, only one record of Student will be present for a particular AdmAppln id (under one AdmAppln only one Student).

Now I want to write few data from to these tables, into an Excel file, whose records must be sorted in the order of registerNo (if it is present), otherwise using id of the Student. We are using XSSFWorkbook class under org.apache.poi.xssf.usermodel package for doing operations on Excel sheet. Here I found a way to sort the excel sheet, but I tried and found a way in code itself using Comparable interface.

This is what I did in ApplnDoc class

public int compareTo(ApplnDoc otherData) {
    if(new ArrayList<Student>(this.admAppln.getStudents()).get(0).getRegisterNo() != null &&
       !new ArrayList<Student>(this.admAppln.getStudents()).get(0).getRegisterNo().isEmpty() &&
       new ArrayList<Student>(otherData.admAppln.getStudents()).get(0).getRegisterNo() != null &&
       !new ArrayList<Student>(otherData.admAppln.getStudents()).get(0).getRegisterNo().isEmpty()) {

            return new ArrayList<Student>(this.admAppln.getStudents()).get(0).getRegisterNo()
                   .compareTo
                   (new ArrayList<Student>(otherData.admAppln.getStudents()).get(0).getRegisterNo());
    } else {
            return new ArrayList<Student>(this.admAppln.getStudents()).get(0).getId() -
                   new ArrayList<Student>(otherData.admAppln.getStudents()).get(0).getId();
    }
}

Since there is no get() method in Set interface the only way to get Student's registerNo from AdmAppln was to convert it to a list. Then I sorted the list and then it was iterated to generate the excel file.

Is the above mentioned comparison mechanism a proper one or is there a better way? Why I am asking this question because when the Hibernate session is closed and in my compareTo if I'm accessing the child table columns, then I will be getting Invocation exception.


来源: stackexchange

问:
Override settings of Fancybox
I'm my project i need to overwrite default setting for fancybox. Thumbnails autostart into true, like below. How I should do it.

```<code>thumbs : {
            autoStart   : true,   // Display thumbnails on opening
            hideOnClose : true     // Hide thumbnail grid when closing animation starts
        },
</code>```

答:
It would be best to override defaults using JS:</p>

```<code>$.fancybox.defaults.thumbs.autoStart = true;
</code>```

ContentLicense: CC BY-SA 3.0

Title: Override settings of Fancybox

Body:
I'm my project i need to overwrite default setting for fancybox. Thumbnails autostart into true, like below. How I should do it.

thumbs : {
            autoStart   : true,   // Display thumbnails on opening
            hideOnClose : true     // Hide thumbnail grid when closing animation starts
        },

Body:
It would be best to override defaults using JS:

$.fancybox.defaults.thumbs.autoStart = true;


问:
Add a string to each line that the user won't be able to mark
I want to add the string ">>>" to each line of text, but I don't want my user to be able to mark it when he copies the text.

The only way I could think of is replacing a bullet list with the string. But it doesn't work properly:

ul.codeline {
  margin-left: 0;
  padding-left: 0;
  list-style-type: none;
}

ul.codeline li {
  position: relative;
  margin-left: 2em;
}

ul.codeline li:before {
  position: absolute;
  left: -2em;
  content: ">>> ";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="codeline">
  <li>function foo() {</li>
  <li>console.log('bar')</li>
  <li>}</li>
</ul></code>```

Any other suggestions?

Many thanks!

答:
The simplest solution is probably using the list and including a pseudo-element for each li, which can't be selected:

CSS:

```<code>ul.codeline li::before
  content: '>>> ';
}
</code>```

Another solution using JavaScript could look like this:

```<code>document.addEventListener('copy', function(e) {
  var str = window.getSelection().toString().replace(/>/g, '');

  e.clipboardData.setData('text/plain', str);
  e.preventDefault();
});
</code>```

This code allows you to modify the user's selection and filter out >>>, so it doesn't show when they paste their selection again.

Body:
I want to add the string ">>>" to each line of text, but I don't want my user to be able to mark it when he copies the text.

The only way I could think of is replacing a bullet list with the string. But it doesn't work properly:

ul.codeline {
  margin-left: 0;
  padding-left: 0;
  list-style-type: none;
}

ul.codeline li {
  position: relative;
  margin-left: 2em;
}

ul.codeline li:before {
  position: absolute;
  left: -2em;
  content: ">>> ";
}

function foo() {

console.log('bar')

}

Any other suggestions?

Many thanks!

Body:
The simplest solution is probably using the list and including a pseudo-element for each li, which can't be selected:

CSS:

ul.codeline li::before
  content: '>>> ';
}

Another solution using JavaScript could look like this:

document.addEventListener('copy', function(e) {
  var str = window.getSelection().toString().replace(/>/g, '');

  e.clipboardData.setData('text/plain', str);
  e.preventDefault();
});

This code allows you to modify the user's selection and filter out >>>, so it doesn't show when they paste their selection again.


问:
How to use ajax in reactjs on localhost
Below is my code:
While using local url I am getting the error

"Failed to load http://localhost/reactjs/my-app/lib/ajax.php: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access"

But when I used live url such as "https://jsonplaceholder.typicode.com/todos" its working fine.

```<code>$.ajax({
url: 'http://localhost/reactjs/lib/ajax.php',
//url: 'https://jsonplaceholder.typicode.com/todos',
 type: 'GET',
dataType: 'jsonp',
//contentType: "application/json; charset=utf-8",
//jsonp: "json_callback",
crossOrigin: true,
//cors: true,
//data: {user_name:username, user_type: usertype, password: password,mode: 'Login' },
success: function(data){
alert(data);
},
error: function(error){
console.log(error);
 }
});
</code>```

答:
You are calling different host so that's why you have CORS issue. Your application is running on localhost:3000 and you are calling your service on localhost.

You can do what Vivek suggests (if it is different host) or you just need to have proper port referenced (if both applications are on localhost:3000).

Note that you don't have to write absolute url in ajax. Instead, if it is on same host, you could just write /reactjs/lib/ajax.php.

Title: How to use ajax in reactjs on localhost

Body:
Below is my code:
While using local url I am getting the error

"Failed to load http://localhost/reactjs/my-app/lib/ajax.php: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access"

But when I used live url such as "https://jsonplaceholder.typicode.com/todos" its working fine.

$.ajax({
url: 'http://localhost/reactjs/lib/ajax.php',
//url: 'https://jsonplaceholder.typicode.com/todos',
 type: 'GET',
dataType: 'jsonp',
//contentType: "application/json; charset=utf-8",
//jsonp: "json_callback",
crossOrigin: true,
//cors: true,
//data: {user_name:username, user_type: usertype, password: password,mode: 'Login' },
success: function(data){
alert(data);
},
error: function(error){
console.log(error);
 }
});


问:
Add Image on the Button
Any one help me. How to add the image on the button? I am using following code for create a button. I want to display the image instead of "refresh". is it possible to do this?
Thanks in advance.</p>

```<code><div data-role="button" data-iconpos="right" id="searchResultRefresh" data-icon="refresh">
 refresh </div>
</code>```

答:
That's not a button, it's a div element.

To have button with image, have such HTML:

```<code><button type="button"><img src="Refresh.gif" /></button>
</code>```

ContentLicense: CC BY-SA 2.5

Title: Add Image on the Button

Body:
Any one help me. How to add the image on the button? I am using following code for create a button. I want to display the image instead of "refresh". is it possible to do this?
Thanks in advance.

 refresh

Body:
That's not a button, it's a div element.

To have button with image, have such HTML:

<button type="button"><img src="Refresh.gif" /></button>


问:
send a local email with codeIgniter
I try to send a local email with codeIgniter.

```<code>// envoi du mail
 public function envoiMail(){
    $config = Array(
        'protocol' => 'smtp',
        'smtp_host' => 'ssl://smtp.googlemail.com',
        'smtp_port' => 465,
        'smtp_user' => 'xxxxxxx@gmail.cm',
        'smtp_pass' => 'XXXXXX',
        'mailtype'  => 'html',
        'charset'   => 'iso-8859-1',
        'crlf'   => '\r\n',
        'newline'   => '\r\n',
    );
    $sujet = $this->input->post('sujet');
    $message = $this->input->post('message');
    $this->load->library('email', $config);
    $this->email->set_newline("\r\n");
    $this->email->from('xxxx@gmail.com', 'Name');
    $this->email->to('xxxx@yahoo.fr');
    $this->email->subject($sujet);
    $this->email->message($message);
    $this->email->send();
  if($this->email->send()){
      // mail transmis
       echo "ok";
  }else{
      // erreur de transmission
      echo"erreur d'envoi";
  }
 }
</code>```

when I test I get this error:  Message: fsockopen(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed.

答:
If you are using Avast Antivirus disable it.

In my case the Avast Antivirus was blocking the port, I was using the SMTP Port 465 for sending an email from my Codeigniter Project.

Simply disabling the avast antivirus solves the situation.

Title: send a local email with codeIgniter

Body:
I try to send a local email with codeIgniter.

// envoi du mail
 public function envoiMail(){
    $config = Array(
        'protocol' => 'smtp',
        'smtp_host' => 'ssl://smtp.googlemail.com',
        'smtp_port' => 465,
        'smtp_user' => 'xxxxxxx@gmail.cm',
        'smtp_pass' => 'XXXXXX',
        'mailtype'  => 'html',
        'charset'   => 'iso-8859-1',
        'crlf'   => '\r\n',
        'newline'   => '\r\n',
    );
    $sujet = $this->input->post('sujet');
    $message = $this->input->post('message');
    $this->load->library('email', $config);
    $this->email->set_newline("\r\n");
    $this->email->from('xxxx@gmail.com', 'Name');
    $this->email->to('xxxx@yahoo.fr');
    $this->email->subject($sujet);
    $this->email->message($message);
    $this->email->send();
  if($this->email->send()){
      // mail transmis
       echo "ok";
  }else{
      // erreur de transmission
      echo"erreur d'envoi";
  }
 }

when I test I get this error:  Message: fsockopen(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed.


问:
implement JS in shopware site
So, i want to implement some javasript for example

```<code><script>console.log("Hello World")</script>
</code>```

in my shopware website, which is not the index (home) site.

Things i already tried

1) add the js over the body of the Website

2)  added follwing block in header.tpl of my theme

```<code>{block name="frontend_index_header_javascript_jquery" append}
   <script>console.log("Hello World")</script>
{/block}
</code>```

3) added follwing block in header.tpl of my theme and created an alternative .js file and loaded it into the tpl

```<code>{block name="frontend_index_header_javascript_jquery" append}
   <script src="{link file='frontend/_resources/JavaScript/test.js'}"></script>
{/block}
</code>```

What could be possibly wrong´or what do i have to change? Im using shopware 5.3.

答:
the tpl files are just markup.
A correct way to add custom Javascript or Less/css is to add it to the Events which compile the Javascript and Less/css files.
In my Example I create a subscriber(ThemeCompiler) to keep the bootstrap clean.

I assume that the subscriber is located in the folder

Subscriber

within the plugins root and your Javascript files in

Views/common/frontend/_public/src/js/

Please keep in mind once your file is added its present on all sides within shopware.

```<code><?php

namespace ShopwarePlugins\MyPlugin\Subscriber;

use \Shopware\Components\Theme\LessDefinition;
use Doctrine\Common\Collections\ArrayCollection;

class ThemeCompiler implements \Enlight\Event\SubscriberInterface
{

  public static function getSubscribedEvents()
  {
    return array(
        'Theme_Compiler_Collect_Plugin_Less' => 'onCollectLessFiles',
        'Theme_Compiler_Collect_Plugin_Javascript' => 'onCollectJavascriptFiles'
    );
  }

  private function path(){
    return __DIR__ . '/../';
  }

  public function onCollectLessFiles()
  {
    return new LessDefinition(
        [],
        [$this->path(). 'Views/common/frontend/_public/src/less/myLessFile.less']
    );
  }

  public function onCollectJavascriptFiles()
  {
    $jsFiles = array(
        $this->path() . 'Views/common/frontend/_public/src/js/myJsFile.js'
    );
    return new ArrayCollection($jsFiles);
  }

}
</code>```

To register the ThemeCompiler as Subscriber add the following lines to your Bootstrap:

```<code>use ShopwarePlugins\MyPlugin\Subscriber\ThemeCompiler;

...

private function registerSubscriber(){
    $this->subscribeEvent('Enlight_Controller_Front_StartDispatch', 'onRegisterSubscriber');
    $this->subscribeEvent('Shopware_Console_Add_Command', 'onRegisterSubscriber');
}

public function onRegisterSubscriber(Enlight_Event_EventArgs $args){
    Shopware()->Events()->addSubscriber(new ThemeCompiler());
}
</code>```

After you added these changes clear the shop cache and recompile it using the backend-ui.

Title: implement JS in shopware site

Body:
So, i want to implement some javasript for example

in my shopware website, which is not the index (home) site.

Things i already tried

1) add the js over the body of the Website

2)  added follwing block in header.tpl of my theme

{block name="frontend_index_header_javascript_jquery" append}

{/block}

3) added follwing block in header.tpl of my theme and created an alternative .js file and loaded it into the tpl

{block name="frontend_index_header_javascript_jquery" append}

{/block}

What could be possibly wrong´or what do i have to change? Im using shopware 5.3.

Body:
the tpl files are just markup.
A correct way to add custom Javascript or Less/css is to add it to the Events which compile the Javascript and Less/css files.
In my Example I create a subscriber(ThemeCompiler) to keep the bootstrap clean.

I assume that the subscriber is located in the folder

Subscriber

within the plugins root and your Javascript files in

Views/common/frontend/_public/src/js/

Please keep in mind once your file is added its present on all sides within shopware.

<?php

namespace ShopwarePlugins\MyPlugin\Subscriber;

use \Shopware\Components\Theme\LessDefinition;
use Doctrine\Common\Collections\ArrayCollection;

class ThemeCompiler implements \Enlight\Event\SubscriberInterface
{

  public static function getSubscribedEvents()
  {
    return array(
        'Theme_Compiler_Collect_Plugin_Less' => 'onCollectLessFiles',
        'Theme_Compiler_Collect_Plugin_Javascript' => 'onCollectJavascriptFiles'
    );
  }

  private function path(){
    return __DIR__ . '/../';
  }

  public function onCollectLessFiles()
  {
    return new LessDefinition(
        [],
        [$this->path(). 'Views/common/frontend/_public/src/less/myLessFile.less']
    );
  }

  public function onCollectJavascriptFiles()
  {
    $jsFiles = array(
        $this->path() . 'Views/common/frontend/_public/src/js/myJsFile.js'
    );
    return new ArrayCollection($jsFiles);
  }

}

To register the ThemeCompiler as Subscriber add the following lines to your Bootstrap:

use ShopwarePlugins\MyPlugin\Subscriber\ThemeCompiler;

...

private function registerSubscriber(){
    $this->subscribeEvent('Enlight_Controller_Front_StartDispatch', 'onRegisterSubscriber');
    $this->subscribeEvent('Shopware_Console_Add_Command', 'onRegisterSubscriber');
}

public function onRegisterSubscriber(Enlight_Event_EventArgs $args){
    Shopware()->Events()->addSubscriber(new ThemeCompiler());
}

After you added these changes clear the shop cache and recompile it using the backend-ui.


问:
Get iOS ID not FCM Id in Ionic 2 with Phonegap Push Plugin
I'm developing app in Ionic 2. I installed phonegap push plugin https://github.com/phonegap/phonegap-plugin-push to get notifications and get device ID.

When I'm in Android App the device ID of return is a GCM ID, but when I'm in iOS he return FCM Id, and I don't need that, I want get Push Plugin register:

This is example of my issue:

FCM Registration Token: cqs2H3ED5u8:APA91bEVQGi0SfbC1Yau1xN_PJB0SOmB50PgHMNG2zCqw4bzWfLruXfqKoIT7DeJnz5K37CqQLIs9F-CXfwurC-UhZjfLNUvnEfCZDpIleW_6xGZYZKokNcIPouGHdvdSnVMhHu6mITh

```<code>Push Plugin register success: <5c27c9a8 87e28030 735f8bc7 e27ab8de e6d6538f c9759e70 26c306a6 fa0ac2cc>
</code>```

How to configure push plugin init to make this change?

答:
I open issue on Phonegap project. https://github.com/phonegap/phonegap-plugin-push/issues/1982

The answer was
 “Yes, when you remove the GoogleService-Info.plist from iOS it uses APNS but as long as you keep delivering google-service.json it uses FCM. Actually, Android won't work without the google-service.json file”

If you want use APNS on iOS platform you have to remove GoogleService-info.plist (is optional on iOS and necessary on Android)

Body:
I'm developing app in Ionic 2. I installed phonegap push plugin https://github.com/phonegap/phonegap-plugin-push to get notifications and get device ID.

When I'm in Android App the device ID of return is a GCM ID, but when I'm in iOS he return FCM Id, and I don't need that, I want get Push Plugin register:

This is example of my issue:

FCM Registration Token: cqs2H3ED5u8:APA91bEVQGi0SfbC1Yau1xN_PJB0SOmB50PgHMNG2zCqw4bzWfLruXfqKoIT7DeJnz5K37CqQLIs9F-CXfwurC-UhZjfLNUvnEfCZDpIleW_6xGZYZKokNcIPouGHdvdSnVMhHu6mITh

Push Plugin register success: <5c27c9a8 87e28030 735f8bc7 e27ab8de e6d6538f c9759e70 26c306a6 fa0ac2cc>

How to configure push plugin init to make this change?


问:
How to remove margin-left and margin-right of col class in bootstrap?
I am new to bootstrap. I put 3 images side by side but they are not adjacent. There is a margin between them. This is picture

I want to eliminate the margins so that the images are adjacent. The center image size is 1200x400 and both left and right images size is 600x400. And also I've used img-responsive class. what is the actual problem?
Here is the code

```<code><div class="container">
    <div class="row">
        <div class="col-sm-3">
            <asp:Image CssClass="img-responsive" ImageUrl="images/right.jpeg" runat="server" />
        </div>
        <div class="col-sm-6">
            <asp:Image CssClass="img-responsive" ImageUrl="images/center1.jpg" runat="server" />
        </div>
        <div class="col-sm-3">
            <asp:Image CssClass="img-responsive" ImageUrl="images/right.jpeg" runat="server" />
        </div>
    </div>
</div>
</code>```

Also you notice in picture, these pictures are not vertically aligned properly how to fix it.

Thanks!

答:
<row class='no-gutters'>...</row>

I realize you've tagged your question with version 3, however, Bootstrap 4 includes a class of no-gutters for grids. Eliminates the padding from the columns that you're seeing. that you're seeing (as well as the negative margin on the row).

https://v4-alpha.getbootstrap.com/layout/grid/#no-gutters

As an example, 1 container with a standard row. And the same container with a row with the no-gutters class.

It's worth mentioning that when you're working within a framework (Bootstrap, Foundation, etc.) and you have a need for something simple like this, check the documentation.  Most likely it's been thought of and built in.  Oh and run from anyone telling you to put !important rules in your CSS.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>

```

Body:
I am new to bootstrap. I put 3 images side by side but they are not adjacent. There is a margin between them. This is picture

I want to eliminate the margins so that the images are adjacent. The center image size is 1200x400 and both left and right images size is 600x400. And also I've used img-responsive class. what is the actual problem?
Here is the code

            <asp:Image CssClass="img-responsive" ImageUrl="images/right.jpeg" runat="server" />

            <asp:Image CssClass="img-responsive" ImageUrl="images/center1.jpg" runat="server" />

            <asp:Image CssClass="img-responsive" ImageUrl="images/right.jpeg" runat="server" />

Also you notice in picture, these pictures are not vertically aligned properly how to fix it.

Thanks!

Body:
<row class='no-gutters'>...</row>

I realize you've tagged your question with version 3, however, Bootstrap 4 includes a class of no-gutters for grids. Eliminates the padding from the columns that you're seeing. that you're seeing (as well as the negative margin on the row).

https://v4-alpha.getbootstrap.com/layout/grid/#no-gutters

As an example, 1 container with a standard row. And the same container with a row with the no-gutters class.

It's worth mentioning that when you're working within a framework (Bootstrap, Foundation, etc.) and you have a need for something simple like this, check the documentation.  Most likely it's been thought of and built in.  Oh and run from anyone telling you to put !important rules in your CSS.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>

<div class="container">
    <div class="row">
        <div class="col-sm-3">
           <img src="//fillmurray.com/300/300" class="img-fluid"/>
        </div>
        <div class="col-sm-3">
            <img src="//fillmurray.com/300/300" class="img-fluid"/>
        </div>
        <div class="col-sm-3">
            <img src="//fillmurray.com/300/300" class="img-fluid"/>
        </div>
        <div class="col-sm-3">
            <img src="//fillmurray.com/300/300" class="img-fluid"/>
        </div>
    </div>
</div>

<div class="container">
    <div class="row no-gutters">
        <div class="col-sm-3">
           <img src="//fillmurray.com/300/300" class="img-fluid"/>
        </div>
        <div class="col-sm-3">
            <img src="//fillmurray.com/300/300" class="img-fluid"/>
        </div>
        <div class="col-sm-3">
            <img src="//fillmurray.com/300/300" class="img-fluid"/>
        </div>
        <div class="col-sm-3">
            <img src="//fillmurray.com/300/300" class="img-fluid"/>
        </div>
    </div>
</div>


问:
Proper way to restrict text input values (e.g. only numbers)
Is it possible to implement an input that allows to type only numbers inside without manual handling of event.target.value?

In React, it is possible to define value property and afterwards input change will be basically bound to the value (not possible to modify it without value change). See example. And it works just fine without any efforts.

In Angular 2 it is possible to define [value], but it will just set the value initially, and afterwards input is not prevented from the modifications.

I was playing around with ngModel and [value] / (input), see example.

But in both implementation there is essential problem:

when you type 10 (model value is 10; input value is 10) - correct

when you type 10d afterwards (model value is 10 - not modified, all non-digits has been removed; input value is 10d) - incorrect, because the model value is the same as before

when you type 10d3 - (model value is 103; input value is 103) - correct

How to do that simple (from the first glance) component, without manually handling event.target.value?...

UPDATE I am not looking for native HTML5 input[number] element here. Numbers input here is just for the example - there could be way more tasks when i need to restrict input text.

Moreover, input[number] is 1) not restricting me from typing 10ddd and 2) (less important) contains arrows that i do not need.

And the problem here is to prevent user from typing something beyond the restricted values, instead of allow to input anything and validate it afterwards

答:
A few of the answers did not work for me so I took the best bits from some of the answers (thanks guys) and created an Angular 5 Directive that should do the job (and more) for you. It maybe not perfect but it offers flexibility.

```<code>import { Directive, HostListener, ElementRef, Input, Renderer2 } from '@angular/core';

@Directive({
selector: '[appInputMask]'
})
export class InputMaskDirective {
@Input('appInputMask') inputType: string;

showMsg = false;
pattern: RegExp;

private regexMap = { // add your own
integer: /^[0-9 ]*$/g,
float: /^[+-]?([0-9]*[.])?[0-9]+$/g,
words: /([A-z]*\\s)*/g,
point25: /^\-?[0-9]*(?:\\.25|\\.50|\\.75|)$/g,
badBoys: /^[^{}*+£$%\\^-_]+$/g
};

constructor(public el: ElementRef, public renderer: Renderer2) { };

@HostListener('keypress', ['$event']) onInput(e) {
this.pattern = this.regexMap[this.inputType]
const inputChar = e.key;
this.pattern.lastIndex = 0; // dont know why but had to add this

if (this.pattern.test(inputChar)) {
   // success
  this.renderer.setStyle(this.el.nativeElement, 'color', 'green');
  this.badBoyAlert('black');
} else {

  this.badBoyAlert('black');
   //do something her to indicate invalid character
  this.renderer.setStyle(this.el.nativeElement, 'color', 'red');
  e.preventDefault();

}

  }
  badBoyAlert(color: string) {
    setTimeout(() => {
      this.showMsg = true;
      this.renderer.setStyle(this.el.nativeElement, 'color', color);
    }, 2000)
  }

  }
</code>```

HTML
    <input class="form-control" appInputMask="badBoys">

ContentLicense: CC BY-SA 4.0

Body:
A few of the answers did not work for me so I took the best bits from some of the answers (thanks guys) and created an Angular 5 Directive that should do the job (and more) for you. It maybe not perfect but it offers flexibility.

import { Directive, HostListener, ElementRef, Input, Renderer2 } from '@angular/core';

@Directive({
selector: '[appInputMask]'
})
export class InputMaskDirective {
@Input('appInputMask') inputType: string;

showMsg = false;
pattern: RegExp;

private regexMap = { // add your own
integer: /^[0-9 ]*$/g,
float: /^[+-]?([0-9]*[.])?[0-9]+$/g,
words: /([A-z]*\\s)*/g,
point25: /^\-?[0-9]*(?:\\.25|\\.50|\\.75|)$/g,
badBoys: /^[^{}*+£$%\\^-_]+$/g
};

constructor(public el: ElementRef, public renderer: Renderer2) { };

@HostListener('keypress', ['$event']) onInput(e) {
this.pattern = this.regexMap[this.inputType]
const inputChar = e.key;
this.pattern.lastIndex = 0; // dont know why but had to add this

if (this.pattern.test(inputChar)) {
   // success
  this.renderer.setStyle(this.el.nativeElement, 'color', 'green');
  this.badBoyAlert('black');
} else {

  this.badBoyAlert('black');
   //do something her to indicate invalid character
  this.renderer.setStyle(this.el.nativeElement, 'color', 'red');
  e.preventDefault();

}

  }
  badBoyAlert(color: string) {
    setTimeout(() => {
      this.showMsg = true;
      this.renderer.setStyle(this.el.nativeElement, 'color', color);
    }, 2000)
  }

  }

HTML
    <input class="form-control" appInputMask="badBoys">


问:
Display all Ghost tags
I would like to add all my tags to a footer section. {{tags}} seems to only work within a post, but not somewhere in the default template.

How can I display a full list of all tags created?

答:
You should use the get helper:

```<code>{{#get "tags" limit="all"}}
    <ul class="tags">
        {{#foreach tags}}
            <li>
                <a href="{{url}}">{{name}}</a>
            </li>
        {{/foreach}}
    </ul>
{{/get}}
</code>```

You can read more about get helper on docs.

Title: Display all Ghost tags

Body:
You should use the get helper:

{{#get "tags" limit="all"}}
    <ul class="tags">
        {{#foreach tags}}
            <li>
                <a href="{{url}}">{{name}}</a>
            </li>
        {{/foreach}}
    </ul>
{{/get}}

You can read more about get helper on docs.


问:
How do I access a value from machine.config in classic asp?
How do I access a value from machine.config in classic asp?
I can't find the answer anywhere....
I don't even know how to begin to try to find a solution....</p>

答:
Use TextStream object.

Example:

```<code><%
Set fs=Server.CreateObject("Scripting.FileSystemObject")

Set f=fs.OpenTextFile(Server.MapPath("testread.txt"), 1)
Response.Write(f.ReadAll)
f.Close

Set f=Nothing
Set fs=Nothing
%>
</code>```

https://www.w3schools.com/asp/asp_ref_textstream.asp

Body:
Use TextStream object.

Example:

<%
Set fs=Server.CreateObject("Scripting.FileSystemObject")

Set f=fs.OpenTextFile(Server.MapPath("testread.txt"), 1)
Response.Write(f.ReadAll)
f.Close

Set f=Nothing
Set fs=Nothing
%>

https://www.w3schools.com/asp/asp_ref_textstream.asp


问:
How many arguments takes the foldr function of Haskell?
I am new to Haskell and I am reading the book  "Real World Haskell". In the Chapter 4 of the book the author asks as an exercise to rewrite the groupBy function using fold. One of the readers of the book (Octavian Voicu ) gave the following solution:

```<code>
theCoolGroupBy :: (a -> a -> Bool) -> [a] -> [[a]]
theCoolGroupBy eq xs = tail $ foldr step (\_ -> [[]]) xs $ (\_ -> False)
                       where step x acc = \p -> if p x then rest p else []:rest (eq x)
                                          where rest q = let y:ys = acc q in (x:y):ys
</code>```

My question is simple: I know that foldr takes 3 arguments: a function, an initial value and a list. But in the second line of the code foldr takes 4 arguments. Why this happens?
Thank you.

答:
All functions in Haskell take just one argument. When we have a function with type a -> b -> c, it is just a shorter way to write a -> (b -> c), i.e. a function, which takes one argument and produces a function which takes another argument. See Currying for more information.

In this case, see the @sepp2k's answer. foldr produces a function and it needs another ("the 4th") argument.

Body:
I am new to Haskell and I am reading the book  "Real World Haskell". In the Chapter 4 of the book the author asks as an exercise to rewrite the groupBy function using fold. One of the readers of the book (Octavian Voicu ) gave the following solution:

theCoolGroupBy :: (a -> a -> Bool) -> [a] -> [[a]]
theCoolGroupBy eq xs = tail $ foldr step (\_ -> [[]]) xs $ (\_ -> False)
                       where step x acc = \p -> if p x then rest p else []:rest (eq x)
                                          where rest q = let y:ys = acc q in (x:y):ys

My question is simple: I know that foldr takes 3 arguments: a function, an initial value and a list. But in the second line of the code foldr takes 4 arguments. Why this happens?
Thank you.


问:
How to show PDF file in MigraDoc.Rendering.Forms.DocumentPreview (in WinForms)?
I have a simple questions. How can you show a PDf file by using PagePreview?

I have a full pathname document.FileName = "c:\scans\Insurance_34345.pdf";

pagePreview.Preview(document.FileName); or something...

If there another way for showing a pdf. It's okay. I want to show it on a WinForms Form.

I tried this. I don't know what I have to do...

in the Designer

```<code>private MigraDoc.Rendering.Forms.DocumentPreview dpvScannedDoc;
</code>```

Part of the code

```<code>                string fullPadnaam = Path.Combine(defaultPath, document.FileName);
                //PdfDocument pdfDocument = new PdfDocument(fullPadnaam);
                //PdfPage page = new PdfPage(pdfDocument);
                //XGraphics gfx = XGraphics.FromPdfPage(page);
                MigraDoc.DocumentObjectModel.Document pdfDocument = new MigraDoc.DocumentObjectModel.Document();
                pdfDocument.ImagePath = fullPadnaam;

                 var docRenderer = new DocumentRenderer(pdfDocument);
                 docRenderer.PrepareDocument();

                 var inPdfDoc = PdfReader.Open(fullPadnaam, PdfDocumentOpenMode.ReadOnly);
                 for (var i = 0; i < inPdfDoc.PageCount; i++)
                 {
                     pdfDocument.AddSection();
                     docRenderer.PrepareDocument();

                     var page = inPdfDoc.Pages[i];

                     var gfx = XGraphics.FromPdfPage(page);

                     docRenderer.RenderPage(gfx, i + 1);
                 }

                 var renderer = new PdfDocumentRenderer();

                 renderer.Document = pdfDocument;

                 renderer.RenderDocument();

                // MigraDoc.DocumentObjectModel.IO.DdlWriter dw = new MigraDoc.DocumentObjectModel.IO.DdlWriter("HelloWorld.mdddl");
                // dw.WriteDocument(pdfDocument);
                // dw.Close();

                //renderer.PdfDocument.rea(outFilePath);
                //string ddl = MigraDoc.DocumentObjectModel.IO.DdlWriter.WriteToString(document1);
                dpvScannedDoc.Show( pdfDocument);
</code>```

答:
PDFsharp does not render PDF files. You cannot show PDF files using the PagePreview.

If you use the XGraphics class for drawing then you can use shared code that draws on the PagePreview and on PDF pages.

The PagePreview sample can be found in the sample package and here:

http://www.pdfsharp.net/wiki/Preview-sample.ashx

If you have code that creates a new PDF file using PDFsharp then you can use the PagePreview to show on screen what you would otherwise draw on PDF pages. You cannot draw existing PDF pages using the PagePreview because PDF does not render PDF.

Body:
I have a simple questions. How can you show a PDf file by using PagePreview?

I have a full pathname document.FileName = "c:\scans\Insurance_34345.pdf";

pagePreview.Preview(document.FileName); or something...

If there another way for showing a pdf. It's okay. I want to show it on a WinForms Form.

I tried this. I don't know what I have to do...

in the Designer

private MigraDoc.Rendering.Forms.DocumentPreview dpvScannedDoc;

Part of the code

                string fullPadnaam = Path.Combine(defaultPath, document.FileName);
                //PdfDocument pdfDocument = new PdfDocument(fullPadnaam);
                //PdfPage page = new PdfPage(pdfDocument);
                //XGraphics gfx = XGraphics.FromPdfPage(page);
                MigraDoc.DocumentObjectModel.Document pdfDocument = new MigraDoc.DocumentObjectModel.Document();
                pdfDocument.ImagePath = fullPadnaam;

                 var docRenderer = new DocumentRenderer(pdfDocument);
                 docRenderer.PrepareDocument();

                 var inPdfDoc = PdfReader.Open(fullPadnaam, PdfDocumentOpenMode.ReadOnly);
                 for (var i = 0; i < inPdfDoc.PageCount; i++)
                 {
                     pdfDocument.AddSection();
                     docRenderer.PrepareDocument();

                     var page = inPdfDoc.Pages[i];

                     var gfx = XGraphics.FromPdfPage(page);

                     docRenderer.RenderPage(gfx, i + 1);
                 }

                 var renderer = new PdfDocumentRenderer();

                 renderer.Document = pdfDocument;

                 renderer.RenderDocument();

                // MigraDoc.DocumentObjectModel.IO.DdlWriter dw = new MigraDoc.DocumentObjectModel.IO.DdlWriter("HelloWorld.mdddl");
                // dw.WriteDocument(pdfDocument);
                // dw.Close();

                //renderer.PdfDocument.rea(outFilePath);
                //string ddl = MigraDoc.DocumentObjectModel.IO.DdlWriter.WriteToString(document1);
                dpvScannedDoc.Show( pdfDocument);


问:
Value < of type java.lang.String cannot be converted to JSONArray In Android
I'm trying to upload the image in Samsung j7 camera. I get some server response with
 tag.

How can I resolve this error and what is the way to get the image from the response?

Error Image Form Android Server Response

My code

protected void Upload_Server() {
    // TODO Auto-generated method stub
    String urlServer = null;
    System.out.println("After call progress");
    try{

```<code>    Log.e("Image Upload", "Inside Upload");

    HttpURLConnection connection = null;
    DataOutputStream outputStream = null;
    DataInputStream inputStream = null;

    String pathToOurFile = imagepath;
    //   String pathToOurFile1 = imagepathcam;

    System.out.println("Before Image Upload" + imagepath);
    if(Videoboolean){
        urlServer = Constants.IMAGEVIDEOURL+"videopostUpload/";
    }else {
        urlServer = Constants.IMAGEVIDEOURL+"imagepostUpload/";
    }

    System.out.println("URL SETVER" + urlServer);
    System.out.println("After Image Upload" + imagepath);
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary =  "*****";

    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1*1024*1024;
    System.out.println("enter the file path in android"+pathToOurFile);
    FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile));
    //  FileInputStream fileInputStream1 = new FileInputStream(new File(pathToOurFile1));

    URL url = new URL(urlServer);
    connection = (HttpURLConnection) url.openConnection();
    System.out.println("URL is "+url);
    System.out.println("connection is "+connection);
    // Allow Inputs & Outputs
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setUseCaches(false);

    // Enable POST method
    connection.setRequestMethod("POST");

    connection.setRequestProperty("Connection", "Keep-Alive");
    connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

    outputStream = new DataOutputStream( connection.getOutputStream() );
    outputStream.writeBytes(twoHyphens + boundary + lineEnd);
    outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile +"\"" + lineEnd);
    outputStream.writeBytes(lineEnd);
    System.out.println("enter the image upload response"+outputStream.getClass().getCanonicalName());
    bytesAvailable = fileInputStream.available();
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    buffer = new byte[bufferSize];

    // Read file
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

    while (bytesRead > 0)
    {
        outputStream.write(buffer, 0, bufferSize);
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    }

    outputStream.writeBytes(lineEnd);
    outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

    // Responses from the server (code and message)
    int serverResponseCode = connection.getResponseCode();
    String serverResponseMessage = connection.getResponseMessage();

    System.out.println("image"+serverResponseMessage);

    fileInputStream.close();
    outputStream.flush();
    outputStream.close();

    DataInputStream inputStream1 = null;
    inputStream1 = new DataInputStream (connection.getInputStream());
    String str="";
    String Str1_imageurl="";

    while ((  str = inputStream1.readLine()) != null)
    {
        Log.e("Debug","Server Response "+str);

        Str1_imageurl = str;
        Log.e("Debug","Server Response String imageurl"+str);
    }
    inputStream1.close();
    System.out.println("image url"+Str1_imageurl);

    PostImVD = Str1_imageurl.trim();
    JSONArray array = new JSONArray(PostImVD);
    JSONObject jsonObj = array.getJSONObject(0);
    if(Videoboolean){
        ImageVideo = jsonObj.optString("video_name");
    }else {
        ImageVideo = jsonObj.optString("image_name");
    }
    System.out.println("Profile Picture Path" + PostImVD);
    System.out.println("Profile Picture Path" + ImageVideo);
}

catch(Exception e){

    e.printStackTrace();

}
</code>```

};

1: Error Image Form Android Server Response

答:
First, try to validate your JSON response in this page for example:

https://jsonlint.com/

If your JSON is correct, then determine if is an array or an object, depends of that use the correct parsing :

If it's an array:

```<code> JSONArray array = new JSONArray(your_string_json);
</code>```

If it's an object

```<code> JSONObject object = new JSONObject(your_string_json);
</code>```

Body:
I'm trying to upload the image in Samsung j7 camera. I get some server response with
 tag.

How can I resolve this error and what is the way to get the image from the response?

Error Image Form Android Server Response

My code

protected void Upload_Server() {
    // TODO Auto-generated method stub
    String urlServer = null;
    System.out.println("After call progress");
    try{

    Log.e("Image Upload", "Inside Upload");

    HttpURLConnection connection = null;
    DataOutputStream outputStream = null;
    DataInputStream inputStream = null;

    String pathToOurFile = imagepath;
    //   String pathToOurFile1 = imagepathcam;

    System.out.println("Before Image Upload" + imagepath);
    if(Videoboolean){
        urlServer = Constants.IMAGEVIDEOURL+"videopostUpload/";
    }else {
        urlServer = Constants.IMAGEVIDEOURL+"imagepostUpload/";
    }

    System.out.println("URL SETVER" + urlServer);
    System.out.println("After Image Upload" + imagepath);
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary =  "*****";

    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1*1024*1024;
    System.out.println("enter the file path in android"+pathToOurFile);
    FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile));
    //  FileInputStream fileInputStream1 = new FileInputStream(new File(pathToOurFile1));

    URL url = new URL(urlServer);
    connection = (HttpURLConnection) url.openConnection();
    System.out.println("URL is "+url);
    System.out.println("connection is "+connection);
    // Allow Inputs & Outputs
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setUseCaches(false);

    // Enable POST method
    connection.setRequestMethod("POST");

    connection.setRequestProperty("Connection", "Keep-Alive");
    connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

    outputStream = new DataOutputStream( connection.getOutputStream() );
    outputStream.writeBytes(twoHyphens + boundary + lineEnd);
    outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile +"\"" + lineEnd);
    outputStream.writeBytes(lineEnd);
    System.out.println("enter the image upload response"+outputStream.getClass().getCanonicalName());
    bytesAvailable = fileInputStream.available();
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    buffer = new byte[bufferSize];

    // Read file
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

    while (bytesRead > 0)
    {
        outputStream.write(buffer, 0, bufferSize);
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    }

    outputStream.writeBytes(lineEnd);
    outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

    // Responses from the server (code and message)
    int serverResponseCode = connection.getResponseCode();
    String serverResponseMessage = connection.getResponseMessage();

    System.out.println("image"+serverResponseMessage);

    fileInputStream.close();
    outputStream.flush();
    outputStream.close();

    DataInputStream inputStream1 = null;
    inputStream1 = new DataInputStream (connection.getInputStream());
    String str="";
    String Str1_imageurl="";

    while ((  str = inputStream1.readLine()) != null)
    {
        Log.e("Debug","Server Response "+str);

        Str1_imageurl = str;
        Log.e("Debug","Server Response String imageurl"+str);
    }
    inputStream1.close();
    System.out.println("image url"+Str1_imageurl);

    PostImVD = Str1_imageurl.trim();
    JSONArray array = new JSONArray(PostImVD);
    JSONObject jsonObj = array.getJSONObject(0);
    if(Videoboolean){
        ImageVideo = jsonObj.optString("video_name");
    }else {
        ImageVideo = jsonObj.optString("image_name");
    }
    System.out.println("Profile Picture Path" + PostImVD);
    System.out.println("Profile Picture Path" + ImageVideo);
}

catch(Exception e){

    e.printStackTrace();

}

};

1: Error Image Form Android Server Response

Body:
First, try to validate your JSON response in this page for example:

https://jsonlint.com/

If your JSON is correct, then determine if is an array or an object, depends of that use the correct parsing :

If it's an array:

 JSONArray array = new JSONArray(your_string_json);

If it's an object

 JSONObject object = new JSONObject(your_string_json);


问:
jQuery .load div inside toggle
I have a div with css display none that is displayed with .toggle function clicking a button.

That div contains blog comments. When I send a new comment I refresh that div with .load function but it toggles the div so I have to click again the button to show it.

Is there any way to avoid this?

CSS:

```<code>.comments-container {
    width: 100%;
    display: none;
}
</code>```

HTML:

```<code><div class="row" id="criticas-wrapper">
    <h4 class="media-title" id="toggle_criticas" onclick="ver_criticas()">&#x25BC CRÍTICAS</h4>
    <button type="button" class="reply">Nuevo comentario</button>
    <div class="comments-container">
     // Here are all the comments
    </div>
</div>
</code>```

JS:

```<code><script>
    function ver_criticas() {
        $(".comments-container").toggle("slow");

  }
</script>

<script>

  jQuery(document).on('submit', '.comment_form', function(e){
  event.preventDefault();

$.ajax({

type: "POST",
url: $(this).attr("action"),
data: $(this).serialize(),

success:function(data){
 var json = JSON.parse(data);

      $(".errormensaje,.correctomensaje").html("").css({"display":"none"});

$("#comment").val("");
    $('#parent_comment').val("");

if(json.resultado =="correcto"){

    if(json.mensaje){
var notification = alertify.notify('¡Mensaje publicado!', 'success', 3, function(){  console.log('dismissed'); });
 $('#criticas-wrapper').load('<?php echo base_url(uri_string());?> #criticas-wrapper');

    }

}
if(json.resultado =="error"){

    if(json.mensaje){
      //$(".errormensaje").append(json.mensaje).css({"display":"block"});
      var notification = alertify.notify(json.mensaje, 'error', 3, function(){  console.log('dismissed'); });

    }

}
else
{
console.log(data);
}
},
error:function(xhr,exception)
{

}
})
e.preventDefault();

  });

</script>
</code>```

答:
The easiest way would be to just add a show() to the div after you reload it.

```<code>...load(url, function(){
   ...show();
})
</code>```

So right after the load is finished you show it.

Title: jQuery .load div inside toggle

Body:
I have a div with css display none that is displayed with .toggle function clicking a button.

That div contains blog comments. When I send a new comment I refresh that div with .load function but it toggles the div so I have to click again the button to show it.

Is there any way to avoid this?

CSS:

.comments-container {
    width: 100%;
    display: none;
}

HTML:

&#x25BC CRÍTICAS

    <button type="button" class="reply">Nuevo comentario</button>

     // Here are all the comments

JS:

Body:
The easiest way would be to just add a show() to the div after you reload it.

...load(url, function(){
   ...show();
})

So right after the load is finished you show it.


问:
Calculation order of bitwise operators in Kotlin
I can't find information about calculation order of bitwise operators in Kotlin. Is it same as in Java or they compute from left to right without any priority? </p>

答:
The and, or xor and other infix functions for bitwise operations are not operators per se, and their execution order is the same as that of other infix functions, i.e. from left to right, so these two lines are equivalent:

```<code>a or b and c or d and e
</code>```

```<code>(((a or b) and c) or d) and e
</code>```

Also note that the precedence of the infix functions is lower than that of operators:

```<code>1 + 2 and 3 + 4
</code>```

```<code>(1 + 2) and (3 + 4)
</code>```

Body:
The and, or xor and other infix functions for bitwise operations are not operators per se, and their execution order is the same as that of other infix functions, i.e. from left to right, so these two lines are equivalent:

a or b and c or d and e

(((a or b) and c) or d) and e

Also note that the precedence of the infix functions is lower than that of operators:

1 + 2 and 3 + 4

(1 + 2) and (3 + 4)


问:
Plugin “Hello World!” for User onUserAuthorisation
I am trying to create a plugin to make some database queries from the event onUserAuthorisation.  Right now I am just trying to set up a "Hello World" style plugin, because I am not sure yet that my plugin function is even firing correctly.  Right now the plugin should just send out an email when a new user gains authorisation.

I can confirm that the joomla emails work for user registration and administration.

Files: autoextranet.php,autoextranet.xml,index.html(empty)

autoextranet.php

```<code><?php

// no direct access
defined('_JEXEC') or die;

class plgUserAutoextranet extends JPlugin
{
    public function onUserAuthorisation($user, $options)
        {
        $mailer = JFactory::getMailer();
        $config = JFactory::getConfig();

        $sender = array(
            $config->get( 'mailfrom' ),
            $config->get( 'fromname' )
            );
        $mailer->setSender($sender);

        $recipient = array( 'email1@gmail.com', 'email2@some.com' );
        $mailer->addRecipient($recipient);

        $body = "New User: ".$user->username;
        $mailer->setBody($body);

        $mailer->setSubject('You got a new user.');

        $mailer->Send();
        }
}

?>
</code>```

autoextranet.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<extension version="3.8.2" type="plugin" group="user">
        <name>PLG_USER_AUTOEXTRANET</name>
        <author>Tim DeLise</author>
        <creationDate>Nov 14, 2017</creationDate>
        <copyright>Tim D</copyright>
        <license>GNU General Public License</license>
        <authorEmail>your email</authorEmail>
        <authorUrl>your website</authorUrl>
        <version>1.0</version>
        <description>.</description>
        <files>
                <filename plugin="autoextranet">autoextranet.php</filename>
                <filename>index.html</filename>
        </files>
</extension>
</code>```

The problem now is that I have installed and activated the plugin.  When I create and activate a new user, I just get nothing.

Unfortunately I have limited access to the server, and haven't been able to view the PHP error logs.  I am looking for some way to confirm that the event is firing my code.  Any suggestion is welcome.  Also this is the first plugin I am making so maybe there is something wrong with my files.

Any help is greatly appreciated.

Joomla Version 3.8.2

答:
The function onUserAuthorisation is triggered once the user is in the login process. Make sure you really log in to Joomla :)

I'm sure you're aware of this. But this function is triggered even if the login fails.

Body:
I am trying to create a plugin to make some database queries from the event onUserAuthorisation.  Right now I am just trying to set up a "Hello World" style plugin, because I am not sure yet that my plugin function is even firing correctly.  Right now the plugin should just send out an email when a new user gains authorisation.

I can confirm that the joomla emails work for user registration and administration.

Files: autoextranet.php,autoextranet.xml,index.html(empty)

autoextranet.php

<?php

// no direct access
defined('_JEXEC') or die;

class plgUserAutoextranet extends JPlugin
{
    public function onUserAuthorisation($user, $options)
        {
        $mailer = JFactory::getMailer();
        $config = JFactory::getConfig();

        $sender = array(
            $config->get( 'mailfrom' ),
            $config->get( 'fromname' )
            );
        $mailer->setSender($sender);

        $recipient = array( 'email1@gmail.com', 'email2@some.com' );
        $mailer->addRecipient($recipient);

        $body = "New User: ".$user->username;
        $mailer->setBody($body);

        $mailer->setSubject('You got a new user.');

        $mailer->Send();
        }
}

?>

autoextranet.xml

<?xml version="1.0" encoding="utf-8"?>
<extension version="3.8.2" type="plugin" group="user">
        <name>PLG_USER_AUTOEXTRANET</name>
        <author>Tim DeLise</author>
        <creationDate>Nov 14, 2017</creationDate>
        <copyright>Tim D</copyright>
        <license>GNU General Public License</license>
        <authorEmail>your email</authorEmail>
        <authorUrl>your website</authorUrl>
        <version>1.0</version>
        <description>.</description>
        <files>
                <filename plugin="autoextranet">autoextranet.php</filename>
                <filename>index.html</filename>
        </files>
</extension>

The problem now is that I have installed and activated the plugin.  When I create and activate a new user, I just get nothing.

Unfortunately I have limited access to the server, and haven't been able to view the PHP error logs.  I am looking for some way to confirm that the event is firing my code.  Any suggestion is welcome.  Also this is the first plugin I am making so maybe there is something wrong with my files.

Any help is greatly appreciated.

Joomla Version 3.8.2


问:
Retain and lag function in R as SAS
I am looking for a function in R similar to lag1, lag2 and retain functions in SAS which I can use with data.tables.

I know there are functions like embed and lag in R but they don't return a single value or the previous value . They return a complete set of vectors.

Is there anything in R which I can use with data.table?

More info on the SAS functions :

Retain

Lag

答:
here's an example: cumulate value with sqldf:

```<code>> w_cum <-
 sqldf("select t1.id, t1.SomeNumt, SUM(t2.SomeNumt) as cum_sum
       from w_cum       t1
       inner join w_cum t2 on t1.id >= t2.id
       group by t1.id, t1.SomeNumt
       order by t1.id
</code>```

")

```<code>   id SomeNumt cum_sum
</code>```

1       11      11

2       12      23

3       13      36

4       14      50

5       15      65

6       16      81

7       17      98

8       18     116

9       19     135

10       20     155

Title: Retain and lag function in R as SAS

Body:
here's an example: cumulate value with sqldf:

> w_cum <-
 sqldf("select t1.id, t1.SomeNumt, SUM(t2.SomeNumt) as cum_sum
       from w_cum       t1
       inner join w_cum t2 on t1.id >= t2.id
       group by t1.id, t1.SomeNumt
       order by t1.id

")

   id SomeNumt cum_sum

1       11      11

2       12      23

3       13      36

4       14      50

5       15      65

6       16      81

7       17      98

8       18     116

9       19     135

10       20     155


问:
Cannot change the row height of TableViewCells - Swift
I am attempting to set the height of a custom tableViewCell, but the code below does not work. What is the better way to do this?

Programmatically:

```<code>override func viewDidLoad() {
  super.viewDidLoad()
  self.tableView.rowHeight = 140
}
</code>```

via storyboard:

Selected on tableView -> size Inspector -> set row height to 140.

I have also tried the following:

Selected the custom UITableViewCell -> size Inspector -> set row height to 140.

答:
if you are using UITableViewController like this:

```<code>override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 140.0
}
</code>```

if you are using UIViewController, you must implement UITableViewDelegate

```<code>func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 140.0
}
</code>```

Body:
I am attempting to set the height of a custom tableViewCell, but the code below does not work. What is the better way to do this?

Programmatically:

override func viewDidLoad() {
  super.viewDidLoad()
  self.tableView.rowHeight = 140
}

via storyboard:

Selected on tableView -> size Inspector -> set row height to 140.

I have also tried the following:

Selected the custom UITableViewCell -> size Inspector -> set row height to 140.

Body:
if you are using UITableViewController like this:

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 140.0
}

if you are using UIViewController, you must implement UITableViewDelegate

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 140.0
}


问:
Touched position and erased position not matched
I am making photo editing application, in my activity I have bitmap that is going to erase on touch when it's not zoomed or rotated its drawing perfectly but after I zoom or rotate bitmap, eraser is not erased at touched points.its erased on some other position according bitmap scaled.

how can I resolve this, please help me.

Drawingview.java

```<code>public class DrawingView extends ImageView implements View.OnTouchListener,MatrixGestureDetector.OnMatrixChangeListener {

private int ERASE = 1;
private int ZOOMTOUCH = 5;

private Matrix matrix = new Matrix();
Matrix inverse = new Matrix();
MatrixGestureDetector mgd = new MatrixGestureDetector(matrix, this);
@Override
public void onChange(Matrix matrix) {
invalidate();
}
public interface ActionListener {
    void onActionCompleted(int i);
}
public void setImageBitmap(Bitmap bm) {
    if (bm != null) {
        bmp = bm;
        orgBit = bm.copy(Bitmap.Config.ARGB_8888, true);
        Bitmap2 = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(), Bitmap.Config.ARGB_8888);
        c2 = new Canvas();
        c2.setBitmap(Bitmap2);

        c2.drawBitmap(bmp, 0, 0, null);

    }

}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    canvas.concat(matrix);
    canvas.drawBitmap(Bitmap2,0,0, null);

    if (c2 != null) {
        Paint p;

        if (!updateOnly) {

            if (isTouched) {

                paint = getPaintByMode(MODE, brushSize);
                c2.drawPath(tPath, paint);

                isTouched = false;
            } else if (curIndx >= 0 && drawOnLasso) {
                redrawCanvas();
            }
        }

        if (MODE == ERASE) {
            p = new Paint();
            p.setColor(SupportMenu.CATEGORY_MASK);
            erPaint.setStrokeWidth(updatebrushsize(erps, scale));
            canvas.drawCircle(f887X, f888Y, (float) (brushSize / 2), erPaint);
            canvas.drawCircle(f887X, f888Y + ((float) offset), updatebrushsize(ImageUtils.dpToPx(getContext(), 7), scale), p);
        }
        if (MODE == ZOOMTOUCH) {

        }
        updateOnly = false;
    }
}

@Override
public boolean onTouch(View v, MotionEvent event) {

    if (MODE == ERASE) {
        f887X = event.getX();
        f888Y = event.getY() - ((float) offset);
        isTouched = true;
        switch (event.getAction()) {
            case 0:
                paint.setStrokeWidth((float) brushSize);
                tPath = new Path();
                tPath.moveTo(f887X, f888Y);
                drawPath.moveTo(f887X, f888Y);
                invalidate();
                break;
            case 1:
                drawPath.lineTo(f887X, f888Y);
                tPath.lineTo(f887X, f888Y);
                invalidate();
                changesIndx.add(curIndx + 1, new Path(tPath));
                brushIndx.add(curIndx + 1, Integer.valueOf(brushSize));
                modeIndx.add(curIndx + 1, Integer.valueOf(MODE));
                vectorPoints.add(curIndx + 1, null);
                lassoIndx.add(curIndx + 1, Boolean.valueOf(insidCutEnable));
                tPath.reset();
                curIndx++;
                clearNextChanges();
                break;
            case 2:
                drawPath.lineTo(f887X, f888Y);
                tPath.lineTo(f887X, f888Y);
                invalidate();
                break;
            default:
                return false;
        }
    }
    if (MODE == ZOOMTOUCH) {
       matrix.invert(inverse);
        float[] pts = {event.getX(), event.getY()};
        inverse.mapPoints(pts);
        mgd.onTouchEvent(event);
    }

    return true;
}

}
class MatrixGestureDetector {
        private static final String TAG = "MatrixGestureDetector";

        private int ptpIdx = 0;
        private Matrix mTempMatrix = new Matrix();
        private Matrix mMatrix;
        private OnMatrixChangeListener mListener;
        private float[] mSrc = new float[4];
        private float[] mDst = new float[4];
        private int mCount;

        interface OnMatrixChangeListener {
            void onChange(Matrix matrix);
        }

        public MatrixGestureDetector(Matrix matrix, MatrixGestureDetector.OnMatrixChangeListener listener) {
            this.mMatrix = matrix;
            this.mListener = listener;
        }

        public void onTouchEvent(MotionEvent event) {
            if (event.getPointerCount() > 2) {
                return;
            }

            int action = event.getActionMasked();
            int index = event.getActionIndex();

            switch (action) {
                case MotionEvent.ACTION_DOWN:
                case MotionEvent.ACTION_POINTER_DOWN:
                    int idx = index * 2;
                    mSrc[idx] = event.getX(index);
                    mSrc[idx + 1] = event.getY(index);
                    mCount++;
                    ptpIdx = 0;
                    break;

                case MotionEvent.ACTION_MOVE:
                    for (int i = 0; i < mCount; i++) {
                        idx = ptpIdx + i * 2;
                        mDst[idx] = event.getX(i);
                        mDst[idx + 1] = event.getY(i);
                    }
                    mTempMatrix.setPolyToPoly(mSrc, ptpIdx, mDst, ptpIdx, mCount);
                    mMatrix.postConcat(mTempMatrix);
                    if (mListener != null) {
                        mListener.onChange(mMatrix);
                    }
                    System.arraycopy(mDst, 0, mSrc, 0, mDst.length);
                    break;

                case MotionEvent.ACTION_UP:
                case MotionEvent.ACTION_POINTER_UP:
                    if (event.getPointerId(index) == 0) ptpIdx = 2;
                    mCount--;
                    break;
            }
        }
    }
</code>```

答:
found the solution thanx to pskink, on this link Android ImageView Scaling and translating issue

by using invert matrix in layer#contain method.

Body:
I am making photo editing application, in my activity I have bitmap that is going to erase on touch when it's not zoomed or rotated its drawing perfectly but after I zoom or rotate bitmap, eraser is not erased at touched points.its erased on some other position according bitmap scaled.

how can I resolve this, please help me.

Drawingview.java

public class DrawingView extends ImageView implements View.OnTouchListener,MatrixGestureDetector.OnMatrixChangeListener {

private int ERASE = 1;
private int ZOOMTOUCH = 5;

private Matrix matrix = new Matrix();
Matrix inverse = new Matrix();
MatrixGestureDetector mgd = new MatrixGestureDetector(matrix, this);
@Override
public void onChange(Matrix matrix) {
invalidate();
}
public interface ActionListener {
    void onActionCompleted(int i);
}
public void setImageBitmap(Bitmap bm) {
    if (bm != null) {
        bmp = bm;
        orgBit = bm.copy(Bitmap.Config.ARGB_8888, true);
        Bitmap2 = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(), Bitmap.Config.ARGB_8888);
        c2 = new Canvas();
        c2.setBitmap(Bitmap2);

        c2.drawBitmap(bmp, 0, 0, null);

    }

}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    canvas.concat(matrix);
    canvas.drawBitmap(Bitmap2,0,0, null);

    if (c2 != null) {
        Paint p;

        if (!updateOnly) {

            if (isTouched) {

                paint = getPaintByMode(MODE, brushSize);
                c2.drawPath(tPath, paint);

                isTouched = false;
            } else if (curIndx >= 0 && drawOnLasso) {
                redrawCanvas();
            }
        }

        if (MODE == ERASE) {
            p = new Paint();
            p.setColor(SupportMenu.CATEGORY_MASK);
            erPaint.setStrokeWidth(updatebrushsize(erps, scale));
            canvas.drawCircle(f887X, f888Y, (float) (brushSize / 2), erPaint);
            canvas.drawCircle(f887X, f888Y + ((float) offset), updatebrushsize(ImageUtils.dpToPx(getContext(), 7), scale), p);
        }
        if (MODE == ZOOMTOUCH) {

        }
        updateOnly = false;
    }
}

@Override
public boolean onTouch(View v, MotionEvent event) {

    if (MODE == ERASE) {
        f887X = event.getX();
        f888Y = event.getY() - ((float) offset);
        isTouched = true;
        switch (event.getAction()) {
            case 0:
                paint.setStrokeWidth((float) brushSize);
                tPath = new Path();
                tPath.moveTo(f887X, f888Y);
                drawPath.moveTo(f887X, f888Y);
                invalidate();
                break;
            case 1:
                drawPath.lineTo(f887X, f888Y);
                tPath.lineTo(f887X, f888Y);
                invalidate();
                changesIndx.add(curIndx + 1, new Path(tPath));
                brushIndx.add(curIndx + 1, Integer.valueOf(brushSize));
                modeIndx.add(curIndx + 1, Integer.valueOf(MODE));
                vectorPoints.add(curIndx + 1, null);
                lassoIndx.add(curIndx + 1, Boolean.valueOf(insidCutEnable));
                tPath.reset();
                curIndx++;
                clearNextChanges();
                break;
            case 2:
                drawPath.lineTo(f887X, f888Y);
                tPath.lineTo(f887X, f888Y);
                invalidate();
                break;
            default:
                return false;
        }
    }
    if (MODE == ZOOMTOUCH) {
       matrix.invert(inverse);
        float[] pts = {event.getX(), event.getY()};
        inverse.mapPoints(pts);
        mgd.onTouchEvent(event);
    }

    return true;
}

}
class MatrixGestureDetector {
        private static final String TAG = "MatrixGestureDetector";

        private int ptpIdx = 0;
        private Matrix mTempMatrix = new Matrix();
        private Matrix mMatrix;
        private OnMatrixChangeListener mListener;
        private float[] mSrc = new float[4];
        private float[] mDst = new float[4];
        private int mCount;

        interface OnMatrixChangeListener {
            void onChange(Matrix matrix);
        }

        public MatrixGestureDetector(Matrix matrix, MatrixGestureDetector.OnMatrixChangeListener listener) {
            this.mMatrix = matrix;
            this.mListener = listener;
        }

        public void onTouchEvent(MotionEvent event) {
            if (event.getPointerCount() > 2) {
                return;
            }

            int action = event.getActionMasked();
            int index = event.getActionIndex();

            switch (action) {
                case MotionEvent.ACTION_DOWN:
                case MotionEvent.ACTION_POINTER_DOWN:
                    int idx = index * 2;
                    mSrc[idx] = event.getX(index);
                    mSrc[idx + 1] = event.getY(index);
                    mCount++;
                    ptpIdx = 0;
                    break;

                case MotionEvent.ACTION_MOVE:
                    for (int i = 0; i < mCount; i++) {
                        idx = ptpIdx + i * 2;
                        mDst[idx] = event.getX(i);
                        mDst[idx + 1] = event.getY(i);
                    }
                    mTempMatrix.setPolyToPoly(mSrc, ptpIdx, mDst, ptpIdx, mCount);
                    mMatrix.postConcat(mTempMatrix);
                    if (mListener != null) {
                        mListener.onChange(mMatrix);
                    }
                    System.arraycopy(mDst, 0, mSrc, 0, mDst.length);
                    break;

                case MotionEvent.ACTION_UP:
                case MotionEvent.ACTION_POINTER_UP:
                    if (event.getPointerId(index) == 0) ptpIdx = 2;
                    mCount--;
                    break;
            }
        }
    }


问:
Mark fields as dirty in Linq To Sql
One of my entities in my LinqToSql model has a field of type XElement, mapped to an XML column in SQL Server.

When I do the following:

```<code>myEntity.MyXmlField.Add(new XAttribute("attribute", "value"));
...
DataContext.SubmitChanges();
</code>```

The field does not get updated in the database (but other fields do).
I take it that the DataContext cannot track changes made inside the XElement and thus this field is not marked as dirty and does not get updated.

Is this the correct assumption and how can I fix it?

EDIT

After reading the link that The Scrum Meister provided, it looks like

```<code>myEntity.MyXmlField = new XElement(myEntity.MyXmlField);
</code>```

will solve the issue.

However this solution is quite specific to XElement (as it's easy to clone it), and involves a lot of processing if the XElement is large.

There's got to be a general way of letting the DataContext know that a field has changed.

答:
You can get hold of Linq-to-SQL's internal change tracker using reflection. Not pretty, but it works unless your app is running with limited trust. See the following threads for samples:

What's the cleanest way to make a Linq object "dirty"?

Can you convince a DataContext to treat a column as always dirty?

Title: Mark fields as dirty in Linq To Sql

Body:
One of my entities in my LinqToSql model has a field of type XElement, mapped to an XML column in SQL Server.

When I do the following:

myEntity.MyXmlField.Add(new XAttribute("attribute", "value"));
...
DataContext.SubmitChanges();

The field does not get updated in the database (but other fields do).
I take it that the DataContext cannot track changes made inside the XElement and thus this field is not marked as dirty and does not get updated.

Is this the correct assumption and how can I fix it?

EDIT

After reading the link that The Scrum Meister provided, it looks like

myEntity.MyXmlField = new XElement(myEntity.MyXmlField);

will solve the issue.

However this solution is quite specific to XElement (as it's easy to clone it), and involves a lot of processing if the XElement is large.

There's got to be a general way of letting the DataContext know that a field has changed.


问:
Layout files naming conventions?
What are some layout file naming conventions people have come up with.

I haven't found anything online, but thought about using the following convention.

What does everyone think?

```<code> - activity_*
 - dialog_*
 - list_item_*
</code>```

That's all I have worked with so far.

Also, what about the naming of the activity against its layout? For example:

```<code>-> res
    -> layout
        -> activity_about_us.xml
-> src
    -> activity
        -> AboutUs.java
</code>```

答:
This is a good read https://jeroenmols.com/blog/2016/03/07/resourcenaming/

Basically, you follow WHAT WHERE DESCRIPTION SIZE

For example, layout file

activity_main: content view of the MainActivity

fragment_articledetail: view for the ArticleDetailFragment

strings

articledetail_title: title of ArticleDetailFragment

feedback_explanation: feedback explanation in FeedbackFragment

drawable
 - all_infoicon_large: large version of generic info icon
 - all_infoicon_24dp: 24dp version of generic info icon

Title: Layout files naming conventions?

Body:
What are some layout file naming conventions people have come up with.

I haven't found anything online, but thought about using the following convention.

What does everyone think?

 - activity_*
 - dialog_*
 - list_item_*

That's all I have worked with so far.

Also, what about the naming of the activity against its layout? For example:

-> res
    -> layout
        -> activity_about_us.xml
-> src
    -> activity
        -> AboutUs.java


问:
Convert EditText to TextView after inputting a name
I want to input a name through EditText and then after inputting it should set itself as permanent so that there can't be anymore editing on the EditText. Basically, convert it to TextView and display the inputted name.

答:
Able to Edit

editText.setEnabled(true);

Unable to edit

editText.setEnabled(false);


问:
Qt Segmentation fault at exec()
I have a very strange problem while trying to run a QProcess in a class HmiApplication, which is derived from QApplication.

The application throws a SIGSEGV in line 6 of main.cpp. This occurs only if line 11 of hmiapplication.cpp is commented out (If I don't qDebug() the stdout of the QProcess).

For the sake of simplicity and clarity, I didn't handle any return values while creating the QProcess.

main.cpp

```<code>#include "hmiapplication.h"

int main(int argc, char **argv)
{
    HmiApplication hmi(argc, argv);
    return hmi.exec(); // LINE 6 - SIGSEGV
}
</code>```

hmiapplication.h

```<code>#ifndef HMIAPPLICATION_H
#define HMIAPPLICATION_H

#include <QApplication>
#include <QProcess>

class HmiApplication : public QApplication
{
    Q_OBJECT
public:
    HmiApplication(int argc, char **argv);
    virtual ~HmiApplication();

private:
    QProcess *macFinder = nullptr;
};

#endif // HMIAPPLICATION_H
</code>```

hmiapplication.cpp

```<code>#include "hmiapplication.h"

HmiApplication::HmiApplication(int argc, char **argv) : QApplication(argc, argv)
{
    macFinder = new QProcess(this);
    macFinder->start("arping", QStringList() << "-c 2" << "192.168.1.1");
    macFinder->waitForReadyRead();
    QString ret(macFinder->readAllStandardOutput());
    ret = ret.mid(ret.indexOf('[') + 1, 17);
    qDebug() << ret; // LINE 11
}

HmiApplication::~HmiApplication()
{
}
</code>```

EDIT:
If I add QVector<Camera*> cameras; to the header and

```<code>for(quint8 i = 0; i < 10; i++) {
    Camera *cam = new Camera(i);
    cameras.append(cam);
}
</code>```

to the source file, it doesn't matter whether or not I remove the qDebug() line and will throw a segmentation fault in both cases.

Camera is a derived class of QLabel and is perfectly working without the QProcess mentionened above.

答:
The QApplication constructor accepts its first parameter by reference...

```<code>QApplication::QApplication(int &argc, char **argv)
</code>```

With the documentation also warning that...

The data referred to by argc and argv must stay valid for the entire
  lifetime of the QApplication object. In addition, argc must be greater
  than zero and argv must contain at least one valid character string.

However, you pass argc by value to the HmiApplication.  Hence the QApplication constructor receives a non-const reference to the local copy which will go out of scope at the end of the HmiApplication ctor leading to undefined behaviour later on.

Change the signature of your constructor to...

```<code>HmiApplication::HmiApplication(int &argc, char **argv)
</code>```

Title: Qt Segmentation fault at exec()

Body:
I have a very strange problem while trying to run a QProcess in a class HmiApplication, which is derived from QApplication.

The application throws a SIGSEGV in line 6 of main.cpp. This occurs only if line 11 of hmiapplication.cpp is commented out (If I don't qDebug() the stdout of the QProcess).

For the sake of simplicity and clarity, I didn't handle any return values while creating the QProcess.

main.cpp

#include "hmiapplication.h"

int main(int argc, char **argv)
{
    HmiApplication hmi(argc, argv);
    return hmi.exec(); // LINE 6 - SIGSEGV
}

hmiapplication.h

#ifndef HMIAPPLICATION_H
#define HMIAPPLICATION_H

#include <QApplication>
#include <QProcess>

class HmiApplication : public QApplication
{
    Q_OBJECT
public:
    HmiApplication(int argc, char **argv);
    virtual ~HmiApplication();

private:
    QProcess *macFinder = nullptr;
};

#endif // HMIAPPLICATION_H

hmiapplication.cpp

#include "hmiapplication.h"

HmiApplication::HmiApplication(int argc, char **argv) : QApplication(argc, argv)
{
    macFinder = new QProcess(this);
    macFinder->start("arping", QStringList() << "-c 2" << "192.168.1.1");
    macFinder->waitForReadyRead();
    QString ret(macFinder->readAllStandardOutput());
    ret = ret.mid(ret.indexOf('[') + 1, 17);
    qDebug() << ret; // LINE 11
}

HmiApplication::~HmiApplication()
{
}

EDIT:
If I add QVector<Camera*> cameras; to the header and

for(quint8 i = 0; i < 10; i++) {
    Camera *cam = new Camera(i);
    cameras.append(cam);
}

to the source file, it doesn't matter whether or not I remove the qDebug() line and will throw a segmentation fault in both cases.

Camera is a derived class of QLabel and is perfectly working without the QProcess mentionened above.

Body:
The QApplication constructor accepts its first parameter by reference...

QApplication::QApplication(int &argc, char **argv)

With the documentation also warning that...

The data referred to by argc and argv must stay valid for the entire
  lifetime of the QApplication object. In addition, argc must be greater
  than zero and argv must contain at least one valid character string.

However, you pass argc by value to the HmiApplication.  Hence the QApplication constructor receives a non-const reference to the local copy which will go out of scope at the end of the HmiApplication ctor leading to undefined behaviour later on.

Change the signature of your constructor to...

HmiApplication::HmiApplication(int &argc, char **argv)


问:
Unable to create a list that is able to dinstinguish between integer and float based on user input
The code is supposed to create a list of five list's, with each list created from the numbers the user input each time (of five). So e.g. if user key in

```<code>1 2 3 4 5

1 2

1.5 2

2.2

1
</code>```

The output should be : [[1, 2, 3, 4, 5], [1, 2], [1.5, 2], [2,2], [1]]
Any help is appreciated. I understand that to solve this problem, you need to convert the string into a int or float, but cannot seem to get it to work.

```<code>nlist = []
n = len(nlist)

while n < 5:
    num = input("Enter a Number: ").split()

    for x in num:

        if '.' in num[x]:
            num[x] = float(num[x])
        else:
            num[x] = int(num[x])

    nlist.append(num)
    n = n + 1
print(nlist)
</code>```

答:
This method accomplishes the effect you are after, and in much fewer lines:

```<code>nList = []

for n in range(5):
    #Takes an input "5 3.5 5 2 3" converts it to [5, 3.5, 5, 2, 3]
    listItems = list(map(eval, input("Numbers for sub-list: ").split()))

    #Append the list to the nList
    nList.append(listItems)

print(nList)
</code>```

So instead of nesting two loops, in the 'listItem' variable it simply takes the input as a string:

```<code>"5 3.5 2"
</code>```

Splits it:

```<code>input().split()

["5", "3.5", "2"]
</code>```

Then maps each item to 'eval' which chooses float or integer depending on the string:

```<code>list(map(eval, input().split()))

[5, 3.5, 2]
</code>```

Important note: 'eval' can be a dangerous command to use, be sure to look up the documentation on it extensively before using it further. Check the comments below for more details.

Alternatively
If you'd rather not use eval, consider this solution:

```<code>nList = []

for n in range(5):
    itemList = input("Numbers to add: ").split()
    subList = []

    for item in itemList:

        if "." in item:
            item = float(item)
        else:
            item = int(item)

        subList.append(item)

    nList.append(subList)

print(nList)
</code>```

Body:
The code is supposed to create a list of five list's, with each list created from the numbers the user input each time (of five). So e.g. if user key in

1 2 3 4 5

1 2

1.5 2

2.2

1

The output should be : [[1, 2, 3, 4, 5], [1, 2], [1.5, 2], [2,2], [1]]
Any help is appreciated. I understand that to solve this problem, you need to convert the string into a int or float, but cannot seem to get it to work.

nlist = []
n = len(nlist)

while n < 5:
    num = input("Enter a Number: ").split()

    for x in num:

        if '.' in num[x]:
            num[x] = float(num[x])
        else:
            num[x] = int(num[x])

    nlist.append(num)
    n = n + 1
print(nlist)

Body:
This method accomplishes the effect you are after, and in much fewer lines:

nList = []

for n in range(5):
    #Takes an input "5 3.5 5 2 3" converts it to [5, 3.5, 5, 2, 3]
    listItems = list(map(eval, input("Numbers for sub-list: ").split()))

    #Append the list to the nList
    nList.append(listItems)

print(nList)

So instead of nesting two loops, in the 'listItem' variable it simply takes the input as a string:

"5 3.5 2"

Splits it:

input().split()

["5", "3.5", "2"]

Then maps each item to 'eval' which chooses float or integer depending on the string:

list(map(eval, input().split()))

[5, 3.5, 2]

Important note: 'eval' can be a dangerous command to use, be sure to look up the documentation on it extensively before using it further. Check the comments below for more details.

Alternatively
If you'd rather not use eval, consider this solution:

nList = []

for n in range(5):
    itemList = input("Numbers to add: ").split()
    subList = []

    for item in itemList:

        if "." in item:
            item = float(item)
        else:
            item = int(item)

        subList.append(item)

    nList.append(subList)

print(nList)


问:
Assertion: exportArchive: "Test.app" requires a provisioning profile
When I tried to integrate continuous integration using Xcode server in my Xcode9. I can successfully create the BOT and I tried to integrate then I always got the error like
“Assertion: exportArchive: "Test.app" requires a provisioning profile.”

How can solve this issue?

答:
I was experiencing the same problem and got it fixed following below steps.

Though you get the error "exportArchive: requires a provisioning profile", successfully creates Archive but fails to create IPA.

Assuming the issue is faced creating Distribution IPA, Xcode 9 has introduced continuous integration for Distribution IPA's which is great.

As part of that, Xcode Bot CI requires ExportOptions.plist for generating Distribution IPA's.

Create ExportOptions.plist

One way to get ExportOptions.plist file (Refer the below link for direct Apple's steps), Try manually creating a Distribution IPA once, with valid Distribution certificates and Profiles which will create an IPA with "ExportOptions.plist" file along with IPA.

Configure changes in Bot

Go back to Bot integration and edit the configuration section of your created bot. Choose

Use Custom Export Options Plist

from Export Options dropdown (Refer attached screen shot) and refer to the created "ExportOptions.plist" file. Now Integrating will create both Archive and IPA with no error.

Refer Apple's Xcode 9 + Xcode Bot documentation for Xcode 9 + Xcode Bot changes


问:
Rails jsonb with store_accessor using multiple fields with same subfield names
I am using Rails 5.1.4 and Postgresql 9.6, and I do have a model named Car with some jsonb fields, but those jsonb fields have same subfields name, for example acceleration has subfields [gasoline,ethanol,diesel] and max_speed has [gasoline,ethanol,diesel] too, also power and torque has these same subfields, I would like to know how to create an edit form and how to use the store_accessor for it.</p>

答:
I got it, instead of using store_accessor I did it using fields_for and OpenStruct to edit the data...

<%= f.fields_for :power, OpenStruct.new(@car.power) do |power| %>

Then the fields just like:

<%= power.text_field :gasoline %>
<%= power.text_field :ethanol %>

And do the same for other fields like max_speed, acceleration, and torque.


问:
Why missing terminating " character is a warning?
When, for example,  we compile the following code:

```<code>printf("hello);
</code>```

we get a warning then an error about the missing " character. In my opinion, warnings inform us about a code that can be compiled but whose behaviour may be probably different from what the developper expects. Therefore my comprehension missed up two things:

Is there a complete code that can be compiled without errors while containing such a portion of code.

If such a code does not exist, why this missing character situation does not give us only an error (not a warning+error).

EDIT (I am doing my best to cope with off-topic votes recommendations):

1. Desired behavior : only one error diagnostic message, there is no need for a warning for the same thing.

Other related issues that do not let me accept the first answer:

2.1 Does printf_s() have the same issue? I tried to enable -c11 option with no success.

2.2 The historical reason to emit the warning does not seem to me to be plausible since why this double message was not used too in similar cases (old accepted constructions being forbidden in new c versions).

答:
Your compiler probably issues errors when it detects the program is ill-formed, and describes the immediate reason the program failed to be well formed at the location it happened.

This is often useless, because the mistake could have been many lines away.

It also issues warnings that are guesses (often educated guesses) what actually caused your problem.  Maybe you forgot a ; on a previous line, failed to close a { or a (.  The warning is not "this token is the point of error", but rather "this is where it all went wrong".

In reality, the C++ standard itself does not distinguish between warnings and errors; they are both diagnostics.  It mandates some things cause diagnostics, and does not bar compilers from issuing additional diagnostics.  Compilers are even free to compile ill formed programs with a warning.

I would expect an error for "newline in string", then a warning pointing at the open quote.

Body:
When, for example,  we compile the following code:

printf("hello);

we get a warning then an error about the missing " character. In my opinion, warnings inform us about a code that can be compiled but whose behaviour may be probably different from what the developper expects. Therefore my comprehension missed up two things:

Is there a complete code that can be compiled without errors while containing such a portion of code.

If such a code does not exist, why this missing character situation does not give us only an error (not a warning+error).

EDIT (I am doing my best to cope with off-topic votes recommendations):

1. Desired behavior : only one error diagnostic message, there is no need for a warning for the same thing.

Other related issues that do not let me accept the first answer:

2.1 Does printf_s() have the same issue? I tried to enable -c11 option with no success.

2.2 The historical reason to emit the warning does not seem to me to be plausible since why this double message was not used too in similar cases (old accepted constructions being forbidden in new c versions).