问:
Can't Display HTML context into the Text Area
Hi everyone I have been trying to display HTML context into the TinyMCE text area. When I choose the line for editing first time it displays the data but,  after I choose different row it can't get the context. Any Help would be appreciated. Here are my component and HTML that I have created. I am trying to display context when clicking the edit button.

import { Component, AfterViewInit, OnDestroy, Input, Output, EventEmitter, ElementRef, provide } from 'angular2/core';
import { RdComponent, RdLib } from '../../../../../node_modules/mulberry/core';

declare let tinymce: any;

@Component({
  selector: 'aril-mail-template',
  template: `<textarea contentEditable="true" style="height:30em"><p>{{model}}</p></textarea>`
})

export class MailTemplatesComponent extends RdComponent {

  @Input("rd-model") model;
  @Input("rd-default") default;
  @Input("rd-required") required;
  @Output("mail-template-save") mailTemplateSave: EventEmitter<any> = new EventEmitter<any>();

  editor;
  elementRef: ElementRef;

  constructor(elementRef: ElementRef) {
    super()
    this.elementRef = elementRef;
  }

  ngOnChanges() {
    tinymce.init({
      selector: 'textarea',
      height: "30em",
      menubar: true,
      plugins: [
        'advlist autolink lists link image charmap print preview anchor',
        'searchreplace visualblocks code fullscreen hr',
        'insertdatetime media table contextmenu paste',
        'wordcount'
      ],
      toolbar: 'bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image code',
      table_toolbar: "tableprops cellprops tabledelete | tableinsertrowbefore tableinsertrowafter tabledeleterow | tableinsertcolbefore tableinsertcolafter tabledeletecol",
      powerpaste_allow_local_images: true,
      powerpaste_word_import: 'prompt',
      powerpaste_html_import: 'prompt',
      content_css: [
        '//fonts.googleapis.com/css?family=Lato:300,300i,400,400i',
        '//www.tinymce.com/css/codepen.min.css'],

      setup: editor => {
        this.editor = editor;
        editor.on('init', () => {
          this.model && this.editor.setContent(this.model, { format: 'raw' });
        });
        editor.on('change', () => {
          const content = editor.getContent();
          this.mailTemplateSave.emit(content);
        });
      }
    });
  }

  ngOnDestroy() {
    tinymce.remove(this.editor);
  }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><rd-service-provider #mailTemplateProvider rd-client-side-paging [rd-service-proxy]="clientSideProxy" [rd-page-size]="25"
  (rd-init)="mailTemplateProvider.call(getMailTemplates())">
</rd-service-provider>
<rd-service-provider #deleteMailTemplateProvider [rd-service-proxy]="serviceProxy" (rd-success)="toastr.info(translate('İşlem Başarıyla Sonlandırıldı')); mailTemplateProvider.call(getMailTemplates())"></rd-service-provider>
<rd-service-provider #saveMailTemplateProvider [rd-service-proxy]="serviceProxy" (rd-success)="toastr.info(translate('Mail Şablonu Başarıyla Oluşturuldu.')); mailTemplateProvider.call(getMailTemplates())"></rd-service-provider>

<div class="row">
  <div class="col-md-4">
    <rd-portlet [rd-text]="translate('Mail Şablonları')" rd-color="green" rd-icon="fa fa-envelope">
      <rd-tools>
        <rd-tool rd-icon="icon-plus" rd-color="white" [rd-tooltip]="translate('Yeni Şablon Ekle')" rd-animate="flash infinite" (rd-click)="data;showMailTemplate=true;console.log(data)"></rd-tool>
        <rd-tool rd-type="refresh" *ngIf="mailTemplateProvider.content.state.serviceCalled"></rd-tool>
        <rd-tool rd-type="collapse" [rd-default-collapse]="false"></rd-tool>
      </rd-tools>

      <rd-body>
        <rd-grid #grid [rd-provider]="mailTemplateProvider" rd-enableSorting="true" [rd-block]="mailTemplateProvider.content.state.waitigForResponse">
          <rd-grid-column [rd-text]="translate('Mail Türü')" rd-key="EmailType">
            <template #item>
              <rd-value rd-type="text" [rd-model]="item.EmailType"></rd-value>
            </template>
          </rd-grid-column>
          <rd-grid-column [rd-text]="translate('Mail Konusu')" rd-key="MailSubject">
            <template #item>
              <rd-value rd-type="text" [rd-model]="item.MailSubject"></rd-value>
            </template>
          </rd-grid-column>
          <rd-grid-column rd-type="operations">
            <template #item>
              <rd-button rd-icon="fa fa-pencil" rd-icon-color="yellow" rd-size="small" [rd-tooltip]="translate('Düzenle')" (rd-click)="data = item;showMailTemplate=true;console.log(data)"></rd-button>
              <rd-button rd-icon="fa fa-trash-o" rd-icon-color="red" rd-size="small" [rd-tooltip]="translate('Sil')" (rd-confirm-popover)="$event ? deleteMailTemplateProvider.call(deleteMailTemplates(item.Serno)) : null"></rd-button>
            </template>
          </rd-grid-column>
        </rd-grid>
      </rd-body>
    </rd-portlet>
  </div>

  <div class="col-md-8" *ngIf="showMailTemplate">
    <rd-portlet [rd-text]="translate('Mail Şablonu Tanımlama')" rd-color="green" rd-icon="fa fa-envelope">
      <rd-body>
        <rd-form>
          <rd-body>
            <div class="row">
              <div class="col-md-12">
                <div class="col-md-12">
                  <div class="col-md-6" style="padding:0%">
                    <rd-field [rd-text]="translate('Mail Türü')"></rd-field>
                    <rd-input-select [(rd-model)]="data.EmailType" rd-form-data="EmailType" rd-display="Value" rd-value="Key" [rd-items]="mailTemplatesList">
                    </rd-input-select>
                  </div>
                  <div class="col-md-6">
                    <rd-field [rd-text]="translate('Mail Konusu')"></rd-field>
                    <rd-input-text [(rd-model)]="data.MailSubject" rd-form-data="MailSubject" [rd-required]="true"></rd-input-text>
                  </div>
                </div>
                <div class="col-md-12">
                  <rd-field [rd-text]="translate('Mail İçeriği')"></rd-field>
                  <aril-mail-template [(rd-model)]="data.MailContent" (mail-template-save)="mailContent = $event" [rd-required]="true"></aril-mail-template>
                </div>
              </div>
            </div>
          </rd-body>
          <rd-footer>
            <rd-submit [rd-text]="translate('Kaydet')" rd-size="medium" (rd-click)="saveMailTemplateProvider.call(saveMailTemplates($event, mailContent))"></rd-submit>
            <rd-clean [rd-text]="translate('Temizle')" rd-size="medium"></rd-clean>
          </rd-footer>
        </rd-form>
      </rd-body>
    </rd-portlet>
  </div>
</div></code>```

答: You can't define what the editor does on init inside the editor you're trying to initialize. That doesn't make sense.

Body:
Hi everyone I have been trying to display HTML context into the TinyMCE text area. When I choose the line for editing first time it displays the data but,  after I choose different row it can't get the context. Any Help would be appreciated. Here are my component and HTML that I have created. I am trying to display context when clicking the edit button.

import { Component, AfterViewInit, OnDestroy, Input, Output, EventEmitter, ElementRef, provide } from 'angular2/core';
import { RdComponent, RdLib } from '../../../../../node_modules/mulberry/core';

declare let tinymce: any;

@Component({
  selector: 'aril-mail-template',
  template: `<textarea contentEditable="true" style="height:30em"><p>{{model}}</p></textarea>`
})

export class MailTemplatesComponent extends RdComponent {

  @Input("rd-model") model;
  @Input("rd-default") default;
  @Input("rd-required") required;
  @Output("mail-template-save") mailTemplateSave: EventEmitter<any> = new EventEmitter<any>();

  editor;
  elementRef: ElementRef;

  constructor(elementRef: ElementRef) {
    super()
    this.elementRef = elementRef;
  }

  ngOnChanges() {
    tinymce.init({
      selector: 'textarea',
      height: "30em",
      menubar: true,
      plugins: [
        'advlist autolink lists link image charmap print preview anchor',
        'searchreplace visualblocks code fullscreen hr',
        'insertdatetime media table contextmenu paste',
        'wordcount'
      ],
      toolbar: 'bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image code',
      table_toolbar: "tableprops cellprops tabledelete | tableinsertrowbefore tableinsertrowafter tabledeleterow | tableinsertcolbefore tableinsertcolafter tabledeletecol",
      powerpaste_allow_local_images: true,
      powerpaste_word_import: 'prompt',
      powerpaste_html_import: 'prompt',
      content_css: [
        '//fonts.googleapis.com/css?family=Lato:300,300i,400,400i',
        '//www.tinymce.com/css/codepen.min.css'],

      setup: editor => {
        this.editor = editor;
        editor.on('init', () => {
          this.model && this.editor.setContent(this.model, { format: 'raw' });
        });
        editor.on('change', () => {
          const content = editor.getContent();
          this.mailTemplateSave.emit(content);
        });
      }
    });
  }

  ngOnDestroy() {
    tinymce.remove(this.editor);
  }

}

<rd-service-provider #mailTemplateProvider rd-client-side-paging [rd-service-proxy]="clientSideProxy" [rd-page-size]="25"
  (rd-init)="mailTemplateProvider.call(getMailTemplates())">
</rd-service-provider>
<rd-service-provider #deleteMailTemplateProvider [rd-service-proxy]="serviceProxy" (rd-success)="toastr.info(translate('İşlem Başarıyla Sonlandırıldı')); mailTemplateProvider.call(getMailTemplates())"></rd-service-provider>
<rd-service-provider #saveMailTemplateProvider [rd-service-proxy]="serviceProxy" (rd-success)="toastr.info(translate('Mail Şablonu Başarıyla Oluşturuldu.')); mailTemplateProvider.call(getMailTemplates())"></rd-service-provider>

    <rd-portlet [rd-text]="translate('Mail Şablonları')" rd-color="green" rd-icon="fa fa-envelope">
      <rd-tools>
        <rd-tool rd-icon="icon-plus" rd-color="white" [rd-tooltip]="translate('Yeni Şablon Ekle')" rd-animate="flash infinite" (rd-click)="data;showMailTemplate=true;console.log(data)"></rd-tool>
        <rd-tool rd-type="refresh" *ngIf="mailTemplateProvider.content.state.serviceCalled"></rd-tool>
        <rd-tool rd-type="collapse" [rd-default-collapse]="false"></rd-tool>
      </rd-tools>

      <rd-body>
        <rd-grid #grid [rd-provider]="mailTemplateProvider" rd-enableSorting="true" [rd-block]="mailTemplateProvider.content.state.waitigForResponse">
          <rd-grid-column [rd-text]="translate('Mail Türü')" rd-key="EmailType">
            <template #item>
              <rd-value rd-type="text" [rd-model]="item.EmailType"></rd-value>
            </template>
          </rd-grid-column>
          <rd-grid-column [rd-text]="translate('Mail Konusu')" rd-key="MailSubject">
            <template #item>
              <rd-value rd-type="text" [rd-model]="item.MailSubject"></rd-value>
            </template>
          </rd-grid-column>
          <rd-grid-column rd-type="operations">
            <template #item>
              <rd-button rd-icon="fa fa-pencil" rd-icon-color="yellow" rd-size="small" [rd-tooltip]="translate('Düzenle')" (rd-click)="data = item;showMailTemplate=true;console.log(data)"></rd-button>
              <rd-button rd-icon="fa fa-trash-o" rd-icon-color="red" rd-size="small" [rd-tooltip]="translate('Sil')" (rd-confirm-popover)="$event ? deleteMailTemplateProvider.call(deleteMailTemplates(item.Serno)) : null"></rd-button>
            </template>
          </rd-grid-column>
        </rd-grid>
      </rd-body>
    </rd-portlet>

    <rd-portlet [rd-text]="translate('Mail Şablonu Tanımlama')" rd-color="green" rd-icon="fa fa-envelope">
      <rd-body>
        <rd-form>
          <rd-body>

                    <rd-field [rd-text]="translate('Mail Türü')"></rd-field>
                    <rd-input-select [(rd-model)]="data.EmailType" rd-form-data="EmailType" rd-display="Value" rd-value="Key" [rd-items]="mailTemplatesList">
                    </rd-input-select>

                    <rd-field [rd-text]="translate('Mail Konusu')"></rd-field>
                    <rd-input-text [(rd-model)]="data.MailSubject" rd-form-data="MailSubject" [rd-required]="true"></rd-input-text>

                  <rd-field [rd-text]="translate('Mail İçeriği')"></rd-field>
                  <aril-mail-template [(rd-model)]="data.MailContent" (mail-template-save)="mailContent = $event" [rd-required]="true"></aril-mail-template>

          </rd-body>
          <rd-footer>
            <rd-submit [rd-text]="translate('Kaydet')" rd-size="medium" (rd-click)="saveMailTemplateProvider.call(saveMailTemplates($event, mailContent))"></rd-submit>
            <rd-clean [rd-text]="translate('Temizle')" rd-size="medium"></rd-clean>
          </rd-footer>
        </rd-form>
      </rd-body>
    </rd-portlet>


来源: stackexchange

问:
create a trigger to alter table add column based on inserted row
I have two tables in a database named as follows:

```<code>1. state_master
+---------------+-------------------+
|      state_id |        state_name |
+---------------+-------------------+
|             1 |               new |
|             2 |          assigned |
|             3 |       in_progress |
|             4 |           on_hold |
|             5 |            closed |
+---------------+-------------------+

2. store_complaint_state_count
+----------+-----+--------+------------+-------+------+
| store_id | new |assigned| in_progress|on_hold|closed|
| 101      | 1   |2       | 2          |0      |0     |
| 102      | 5   |4       | 1          |0      |2     |
+----------+-----+--------+------------+-------+------+
</code>```

Now I want to add another row in state_master state_id =6 and state_name=reopen.
I want to create a trigger which can alter table store_complaint_state_count and add column reopen in it.

I've created a procedure:

```<code>CREATE DEFINER=`root`@`localhost` PROCEDURE `alterTablestorewisecomplaintcount`(in state int )
BEGIN
    alter table storewisecomplaintcount
    add column state INT UNSIGNED ZEROFILL NOT NULL DEFAULT 0;

END
</code>```

And a trigger:

```<code>CREATE DEFINER = CURRENT_USER
    TRIGGER `nxtlife_sfcms_db_v2`.`complaint_state_AFTER_INSERT`
    AFTER INSERT ON `complaint_state`

FOR EACH ROW

BEGIN

call alterTablestorewisecomplaintcount(new.state_value);

END
</code>```

But it throws an error at the time of insertion:

ERROR 1422: 1422: Explicit or implicit commit is not allowed in stored function or trigger.

答:
Hi you can create table and log all events in table.</p>

```<code>create table dbLOG (Id Int Identity(1,1),PostTime
VARCHAR(50),ServerName VARCHAR(25),UserName VARCHAR(15),CommandText
   VARCHAR(MAX))
        go

                CREATE TRIGGER [db_LOG]
                ON DATABASE
                FOR create_table,alter_table,drop_table
                ,create_PROCEDURE, alter_PROCEDURE,drop_PROCEDURE
                ,ALTER_function,create_function,drop_function
                ,ALTER_trigger,create_trigger,drop_trigger
               AS
               SET NOCOUNT ON
               DECLARE @xEvent XML
            SET @xEvent = eventdata() --capture eventdata regarding SQL statement user have fired
            INSERT INTO dbLOG VALUES(
            REPLACE(CONVERT(VARCHAR(50), @xEvent.query('data(/EVENT_INSTANCE/PostTime)')),'T', ' '),
            CONVERT(VARCHAR(25), @xEvent.query('data(/EVENT_INSTANCE/ServerName)')),
            CONVERT(VARCHAR(15), @xEvent.query('data(/EVENT_INSTANCE/UserName)')),
            CONVERT(VARCHAR(MAX), @xEvent.query('data(/EVENT_INSTANCE/TSQLCommand/CommandText)'))
            )
</code>```

OwnerDisplayName: dhyanandra singh

ContentLicense: CC BY-SA 3.0

Body:
I have two tables in a database named as follows:

1. state_master
+---------------+-------------------+
|      state_id |        state_name |
+---------------+-------------------+
|             1 |               new |
|             2 |          assigned |
|             3 |       in_progress |
|             4 |           on_hold |
|             5 |            closed |
+---------------+-------------------+

2. store_complaint_state_count
+----------+-----+--------+------------+-------+------+
| store_id | new |assigned| in_progress|on_hold|closed|
| 101      | 1   |2       | 2          |0      |0     |
| 102      | 5   |4       | 1          |0      |2     |
+----------+-----+--------+------------+-------+------+

Now I want to add another row in state_master state_id =6 and state_name=reopen.
I want to create a trigger which can alter table store_complaint_state_count and add column reopen in it.

I've created a procedure:

CREATE DEFINER=`root`@`localhost` PROCEDURE `alterTablestorewisecomplaintcount`(in state int )
BEGIN
    alter table storewisecomplaintcount
    add column state INT UNSIGNED ZEROFILL NOT NULL DEFAULT 0;

END

And a trigger:

CREATE DEFINER = CURRENT_USER
    TRIGGER `nxtlife_sfcms_db_v2`.`complaint_state_AFTER_INSERT`
    AFTER INSERT ON `complaint_state`

FOR EACH ROW

BEGIN

call alterTablestorewisecomplaintcount(new.state_value);

END

But it throws an error at the time of insertion:

ERROR 1422: 1422: Explicit or implicit commit is not allowed in stored function or trigger.

Body:
Hi you can create table and log all events in table.

create table dbLOG (Id Int Identity(1,1),PostTime
VARCHAR(50),ServerName VARCHAR(25),UserName VARCHAR(15),CommandText
   VARCHAR(MAX))
        go

                CREATE TRIGGER [db_LOG]
                ON DATABASE
                FOR create_table,alter_table,drop_table
                ,create_PROCEDURE, alter_PROCEDURE,drop_PROCEDURE
                ,ALTER_function,create_function,drop_function
                ,ALTER_trigger,create_trigger,drop_trigger
               AS
               SET NOCOUNT ON
               DECLARE @xEvent XML
            SET @xEvent = eventdata() --capture eventdata regarding SQL statement user have fired
            INSERT INTO dbLOG VALUES(
            REPLACE(CONVERT(VARCHAR(50), @xEvent.query('data(/EVENT_INSTANCE/PostTime)')),'T', ' '),
            CONVERT(VARCHAR(25), @xEvent.query('data(/EVENT_INSTANCE/ServerName)')),
            CONVERT(VARCHAR(15), @xEvent.query('data(/EVENT_INSTANCE/UserName)')),
            CONVERT(VARCHAR(MAX), @xEvent.query('data(/EVENT_INSTANCE/TSQLCommand/CommandText)'))
            )


问:
Difference between drop table and truncate table?
I have some tables that I build as a part of my report rollup. I don't need them afterwards at all. Someone mentioned to truncate them as it would be faster. </p>

答:
DROP Table

```<code>DROP TABLE [table_name];
</code>```

The DROP command is used to remove a table from the database. It is a DDL command. All the rows, indexes and privileges of the table will also be removed. DROP operation cannot be rolled back.

DELETE Table

```<code>DELETE FROM [table_name]
WHERE [condition];

DELETE FROM [table_name];
</code>```

The DELETE command is a DML command. It can be used to delete all the rows or some rows from the table based on the condition specified in WHERE clause. It is executed using a row lock, each row in the table is locked for deletion. It maintain the transaction log, so it is slower than TRUNCATE.
  DELETE operations can be rolled back.

TRUNCATE Table

```<code>TRUNCATE TABLE [table_name];
</code>```

The TRUNCATE command removes all rows from a table. It won't log the deletion of each row, instead it logs the deallocation of the data pages of the table, which makes it faster than DELETE. It is executed using a table lock and whole table is locked for remove all records. It is a DDL command. TRUNCATE operations cannot be rolled back.

OwnerDisplayName: Brian

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Juan Manuel

Body:
DROP Table

DROP TABLE [table_name];

The DROP command is used to remove a table from the database. It is a DDL command. All the rows, indexes and privileges of the table will also be removed. DROP operation cannot be rolled back.

DELETE Table

DELETE FROM [table_name]
WHERE [condition];

DELETE FROM [table_name];

The DELETE command is a DML command. It can be used to delete all the rows or some rows from the table based on the condition specified in WHERE clause. It is executed using a row lock, each row in the table is locked for deletion. It maintain the transaction log, so it is slower than TRUNCATE.
  DELETE operations can be rolled back.

TRUNCATE Table

TRUNCATE TABLE [table_name];

The TRUNCATE command removes all rows from a table. It won't log the deletion of each row, instead it logs the deallocation of the data pages of the table, which makes it faster than DELETE. It is executed using a table lock and whole table is locked for remove all records. It is a DDL command. TRUNCATE operations cannot be rolled back.


问:
String Swap Before and After Comma
I have the table below

```<code>AdviserName
-----------
Tearle, Michael Hearn
Hearn Tearle, Michael
Van Der Welden, Luke
Welden, Luke Van Der
Brennan, Sony G
G Brennan, Sony
Rhammasamysundaran, Vishnu Brahma Kuma
Brahma Kuma Rhammasamysundaran, Vishnu
</code>```

Basically I need to re-arrange so it become FirstName MiddleName LastName. For example Michael Hearn Tearle or Sony G Brennan or Luke Van Der Welden.

I used below syntax but somehow it doesn't like if the middle name is before the comma like Hearn Tearle, Michael.

```<code>If(OBJECT_ID('tempdb..#tempX') Is Not Null)

Drop Table #tempX

create table #tempX (AdviserName varchar(max))

insert into #tempX (AdviserName)
values ('Tearle, Michael Hearn'),('Hearn Tearle, Michael'),('Van Der Welden, Luke'),('Welden, Luke Van Der'),('Brennan, Sony G'),('G Brennan, Sony'),('Rhammasamysundaran, Vishnu Brahma Kuma '), ('Brahma Kuma Rhammasamysundaran, Vishnu ')

--select * from #tempX

select substring(advisername, charindex(',', replace(advisername, ' ', '')) + 1, len(advisername))+' '+ left(advisername, charindex(',', advisername) -1) as AdviserName from #tempX
</code>```

Below is the result.

```<code>AdviserName
--------------------------------------
 Michael Hearn Tearle
, Michael Hearn Tearle
n, Luke Van Der Welden
 Luke Van Der Welden
 Sony G Brennan
, Sony G Brennan
 Vishnu Brahma Kuma  Rhammasamysundaran
n, Vishnu  Brahma Kuma Rhammasamysundaran
</code>```

How do you make a query to cater both middle name before comma and after comma?

I'm using SQL Server 2012.

Thanks all.

答:
Try this</p>

```<code>If(OBJECT_ID('tempdb..#tempX') Is Not Null)

Drop Table #tempX

create table #tempX (AdviserName varchar(max))

insert into #tempX (AdviserName)
values ('Tearle, Michael Hearn'),('Hearn Tearle, Michael'),('Van Der Welden, Luke'),('Welden, Luke Van Der'),('Brennan, Sony G'),('G Brennan, Sony'),('Rhammasamysundaran, Vishnu Brahma Kuma '), ('Brahma Kuma Rhammasamysundaran, Vishnu ')

select
    AdviserName,
    replace(replace(
    SUBSTRING(AdviserName,charindex(',',AdviserName),len(AdviserName))
    +' '+
     SUBSTRING(AdviserName,1,charindex(',',AdviserName))
     ,',',''),'  ',' ')
from #tempX
</code>```

Title: String Swap Before and After Comma

Body:
I have the table below

AdviserName
-----------
Tearle, Michael Hearn
Hearn Tearle, Michael
Van Der Welden, Luke
Welden, Luke Van Der
Brennan, Sony G
G Brennan, Sony
Rhammasamysundaran, Vishnu Brahma Kuma
Brahma Kuma Rhammasamysundaran, Vishnu

Basically I need to re-arrange so it become FirstName MiddleName LastName. For example Michael Hearn Tearle or Sony G Brennan or Luke Van Der Welden.

I used below syntax but somehow it doesn't like if the middle name is before the comma like Hearn Tearle, Michael.

If(OBJECT_ID('tempdb..#tempX') Is Not Null)

Drop Table #tempX

create table #tempX (AdviserName varchar(max))

insert into #tempX (AdviserName)
values ('Tearle, Michael Hearn'),('Hearn Tearle, Michael'),('Van Der Welden, Luke'),('Welden, Luke Van Der'),('Brennan, Sony G'),('G Brennan, Sony'),('Rhammasamysundaran, Vishnu Brahma Kuma '), ('Brahma Kuma Rhammasamysundaran, Vishnu ')

--select * from #tempX

select substring(advisername, charindex(',', replace(advisername, ' ', '')) + 1, len(advisername))+' '+ left(advisername, charindex(',', advisername) -1) as AdviserName from #tempX

Below is the result.

AdviserName
--------------------------------------
 Michael Hearn Tearle
, Michael Hearn Tearle
n, Luke Van Der Welden
 Luke Van Der Welden
 Sony G Brennan
, Sony G Brennan
 Vishnu Brahma Kuma  Rhammasamysundaran
n, Vishnu  Brahma Kuma Rhammasamysundaran

How do you make a query to cater both middle name before comma and after comma?

I'm using SQL Server 2012.

Thanks all.

Body:
Try this

If(OBJECT_ID('tempdb..#tempX') Is Not Null)

Drop Table #tempX

create table #tempX (AdviserName varchar(max))

insert into #tempX (AdviserName)
values ('Tearle, Michael Hearn'),('Hearn Tearle, Michael'),('Van Der Welden, Luke'),('Welden, Luke Van Der'),('Brennan, Sony G'),('G Brennan, Sony'),('Rhammasamysundaran, Vishnu Brahma Kuma '), ('Brahma Kuma Rhammasamysundaran, Vishnu ')

select
    AdviserName,
    replace(replace(
    SUBSTRING(AdviserName,charindex(',',AdviserName),len(AdviserName))
    +' '+
     SUBSTRING(AdviserName,1,charindex(',',AdviserName))
     ,',',''),'  ',' ')
from #tempX


问:
Append table data from controller in blade through ajax
My table is designed for the controller, I want to append this table to the table in the blade of laravel.

This is my table in controller:

```<code>        $subLaws='';
          $n=1;
          foreach($sublaw as $sLaw)
          {
             $govt_no='';
             $eventType='';
             $status='Inactive';
             $url=url('admin/sublawmaster/'.$sLaw->id);
             $lmsid=$sLaw->lms_id;
             $view_url=url('admin/sublawmaster/view/' .$sLaw->id);
             if($sLaw->status=='1'){$status='Active';}
             $subLaws .= '<tr class="odd">
                          <td></td>
                          <td><a href="'.$view_url.'">'.$lmsid.'</a></td>
                          <td>'.$sLaw->sub_law_name.'</td>
                          <td>'.$eventType.'</td>
                          <td><span class="label label-success
 btn_status">'.$status.'</span></td>
           $n++;
    }
           return json_encode($subLaws);
</code>```

this is my ajax code:

```<code>$.ajax({
                type: 'GET',
                dataType: "json",
                data: {law_id:id},
                url: "{{ URL::to('admin/postlawid/') }}",
                success: function (data) {

                }
            });
</code>```

this is my table in blade file:

```<code><table class="table table-striped table-bordered table-hover" id="sublawmasterdata">
<thead>
            <tr id="header">
            <th align="center" width="80" style="text-align:center;">S NO</th>
                 <th>LMS ID</th>
                 <th>LMS Name</th>
                 <th>LMS Type</th>
                 <th>Status</th>
                 <th>Action</th>
             </tr>
             </thead>
             <tbody>

             </tbody>
            </table>
</code>```

I have a dropdown when the value is selected from this dropdown the table in the controller should get appended to the table in blade file.
how should I append the table in the controller to the table in blade file?

答:
If the data you are returning is plain html then there is no reason to json encode it. simply return the data

controller:

```<code>return $subLaws;
</code>```

ajax:

```<code>$.ajax({
    type: 'GET',
    dataType: "html",
    data: {law_id:id},
    url: "{{ URL::to('admin/postlawid/') }}",
    success: function (data) {
        $('table#sublawmasterdata tbody').append(data);
    }
});
</code>```

You could take it a step further and place the html code in a blade view and return that. But honestly I prefer to just return a json object with the necessary data and build the html from javascript

Body:
My table is designed for the controller, I want to append this table to the table in the blade of laravel.

This is my table in controller:

        $subLaws='';
          $n=1;
          foreach($sublaw as $sLaw)
          {
             $govt_no='';
             $eventType='';
             $status='Inactive';
             $url=url('admin/sublawmaster/'.$sLaw->id);
             $lmsid=$sLaw->lms_id;
             $view_url=url('admin/sublawmaster/view/' .$sLaw->id);
             if($sLaw->status=='1'){$status='Active';}
             $subLaws .= '

                          '.$lmsid.'
                          '.$sLaw->sub_law_name.'
                          '.$eventType.'
                          '.$status.'
           $n++;
    }
           return json_encode($subLaws);

this is my ajax code:

$.ajax({
                type: 'GET',
                dataType: "json",
                data: {law_id:id},
                url: "{{ URL::to('admin/postlawid/') }}",
                success: function (data) {

                }
            });

this is my table in blade file:

            S NO
                 LMS ID
                 LMS Name
                 LMS Type
                 Status
                 Action

I have a dropdown when the value is selected from this dropdown the table in the controller should get appended to the table in blade file.
how should I append the table in the controller to the table in blade file?

Body:
If the data you are returning is plain html then there is no reason to json encode it. simply return the data

controller:

return $subLaws;

ajax:

$.ajax({
    type: 'GET',
    dataType: "html",
    data: {law_id:id},
    url: "{{ URL::to('admin/postlawid/') }}",
    success: function (data) {
        $('table#sublawmasterdata tbody').append(data);
    }
});

You could take it a step further and place the html code in a blade view and return that. But honestly I prefer to just return a json object with the necessary data and build the html from javascript


问:
Can I roll back a JTA transcation after I commit it?
I have a JTA transcation which I commit.  Can I roll it back after I commit?  If yes, how? I have following situation.

I have a backend layer which updated 3 DBs.  I have used JTA user transcation for it.  If update in any DB fails all updates to 3 DBs are rolled back using utx.rollback

Now I have a layer on top of backend layer which updates some other DB.  Now I want that step 1 and step 2 should both succeed or both fail, so I want to roll back JTA transcation of step 1 in case step 2 fails.

It's difficult for me to put code of step 2 into 1 as we are using some existing APIs to update DB in step 2.

答:
As far as I know you cannot rollback a committed transaction. The underlying database will not support it. For instance oracle will not allow committed transaction to  rollback.

Of course there is a way to return to previous state and the terminology is called "point in time recovery". Oracle's point in time recovery mechanism is called FlashBack.

http://download.oracle.com/docs/cd/B28359_01/appdev.111/b28424/adfns_flashback.htm

This will allow you to revert your database state to a previous snapshot.

But the catch is, there is no JTA interface to perform this. (Infact it is outside the scope of Transaction Manager.)

The Best bet is to register savepoints in your transaction without committing and rolling back to the save point if one or more operation fails.


问:
Android Radio Button Group, why I need this?
Why i need to add if (null != rb && checkedId > -1), if I remove the code, the program still work. What's the benefit of this line of code?

```<code>radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            RadioButton rb = (RadioButton) group.findViewById(checkedId);
            if (null != rb && checkedId > -1) {

                switch (rb.getId()){

                    case R.id.radioFast:
                        mAnimOption = FAST;
                        break;

                    case R.id.radioSlow:
                        mAnimOption = SLOW;
                        break;

                    case R.id.radioNone:
                        mAnimOption = NONE;
                        break;

                }
                // End switch block

                mEditor.putInt("anim option", mAnimOption);

            }

        }
    });
</code>```

答: Benefit is to avoid nullpointerexception which can cause your android app to crash.</p>

Body:
Why i need to add if (null != rb && checkedId > -1), if I remove the code, the program still work. What's the benefit of this line of code?

radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            RadioButton rb = (RadioButton) group.findViewById(checkedId);
            if (null != rb && checkedId > -1) {

                switch (rb.getId()){

                    case R.id.radioFast:
                        mAnimOption = FAST;
                        break;

                    case R.id.radioSlow:
                        mAnimOption = SLOW;
                        break;

                    case R.id.radioNone:
                        mAnimOption = NONE;
                        break;

                }
                // End switch block

                mEditor.putInt("anim option", mAnimOption);

            }

        }
    });


问:
Python 3- Multiple Assignment in a single statement
Why does the following code produce the result? The LHS and RHS structure is different yet,this is the result..

[[w,x],[[y],z]]=[{10,20},[(30,),40]]

w

10

x

20

y

30

z

40

答:
It's actually not guaranteed that w and x will always produce the same result, in dependence of your Python interpreter. Try switching it to:

```<code>>>> [[w,x],[[y],z]]=[{20,10},[(30,),40]]
>>> w
10
</code>```

That's because the first 'entry' is a set and sets are not guaranteed to be ordered. The rest will work pretty much as expected because tuples and lists are ordered. It doesn't matter of the actual type on both sides so long as there is a parity, i.e. (x, y) = [p, q] will work the same as [x, y] = (p, q).

Body:
It's actually not guaranteed that w and x will always produce the same result, in dependence of your Python interpreter. Try switching it to:

>>> [[w,x],[[y],z]]=[{20,10},[(30,),40]]
>>> w
10

That's because the first 'entry' is a set and sets are not guaranteed to be ordered. The rest will work pretty much as expected because tuples and lists are ordered. It doesn't matter of the actual type on both sides so long as there is a parity, i.e. (x, y) = [p, q] will work the same as [x, y] = (p, q).


问:
How to get project name from Gitlab webhook event payload
I am using event payload at Jenkins side to run sonar scan, for this, I need project name variable. In Gitlab request, I can see that project details are sent to Jenkins but in Jenkins when I echo environment I can only see below properties.

gitlabActionType

gitlabBranch

gitlabMergedByUser

gitlabMergeRequestId

gitlabMergeRequestIid

gitlabMergeRequestLastCommit

gitlabMergeRequestState

gitlabMergeRequestTargetProjectId

gitlabMergeRequestTitle

gitlabSourceBranch

gitlabSourceNamespace

gitlabSourceRepoHomepage

gitlabSourceRepoHttpUrl

gitlabSourceRepoName

gitlabSourceRepoSshUrl

gitlabSourceRepoURL

gitlabTargetBranch

gitlabTargetNamespace

gitlabTargetRepoHttpUrl

gitlabTargetRepoName

gitlabTargetRepoSshUrl

gitlabUserEmail

gitlabUserName

How can I get project name?

答:
You won't have it through a JSON payload send by a (GitLab) webhook, since GitLab knows nothing about Sonar (natively).

You need to deduce the Sonar project name from the files of the project themselves.

Typically (for instance) a Maven project would use the pom.xml project name as its Sonar project name: see "Is it possible to tell Sonar the project name from the command line?".


问:
How to build instances after extracting a CSV file containing multiples values
I am trying to make multiples instance of the class Employee from a CSV file that contains employees and extracted from a static method. From now I just can get a list of those employees but what I want is Instantly assign those values to an instance variable.

Here is my code:

class Employees():

```<code>nums_of_employees = 0

def __init__(self, name, last, salary):

    self.name = name
    self.last = last
    self.salary = salary
    Employees.nums_of_employees +=1

def data(self):
    print(f'Name: {self.name} LastName: {self.last} Salary: {self.salary}')

@staticmethod
def extract_csv():
    new_emp = []
    with open('Employees.csv', 'r') as data_file:
        csv_data = csv.DictReader(data_file)
        next(csv_data)

        for line in csv_data:
            new_emp += line['Name'], line['Last'], line['Salary']

        return new_emp
</code>```

答:
Hope this helps.

You can use pandas.DataFrame.sample to extract row wise data.

This is example in the official documentation of the link above

Generate an example Series

```<code>>>> s = pd.Series(np.random.randn(50))
>>> s.head()
0   -0.038497
1    1.820773
2   -0.972766
3   -1.598270
4   -1.095526
</code>```

Extraction of 3 random elements from the Series:

```<code>>>> s.sample(n=3)
27   -0.994689
55   -1.049016
67   -0.224565
dtype: float64
</code>```

You can also use this on DataFrame of pandas, to extract elements in the entire row.

Body:
I am trying to make multiples instance of the class Employee from a CSV file that contains employees and extracted from a static method. From now I just can get a list of those employees but what I want is Instantly assign those values to an instance variable.

Here is my code:

class Employees():

nums_of_employees = 0

def __init__(self, name, last, salary):

    self.name = name
    self.last = last
    self.salary = salary
    Employees.nums_of_employees +=1

def data(self):
    print(f'Name: {self.name} LastName: {self.last} Salary: {self.salary}')

@staticmethod
def extract_csv():
    new_emp = []
    with open('Employees.csv', 'r') as data_file:
        csv_data = csv.DictReader(data_file)
        next(csv_data)

        for line in csv_data:
            new_emp += line['Name'], line['Last'], line['Salary']

        return new_emp

Body:
Hope this helps.

You can use pandas.DataFrame.sample to extract row wise data.

This is example in the official documentation of the link above

Generate an example Series

>>> s = pd.Series(np.random.randn(50))
>>> s.head()
0   -0.038497
1    1.820773
2   -0.972766
3   -1.598270
4   -1.095526

Extraction of 3 random elements from the Series:

>>> s.sample(n=3)
27   -0.994689
55   -1.049016
67   -0.224565
dtype: float64

You can also use this on DataFrame of pandas, to extract elements in the entire row.


问:
Key keeps pressing many times
I am trying to create a program that will:

Take live chat messages from a livestream

If the live chat message is a certain control, press and hold that key for two seconds

Take note of that live chat ID and do not press the key again.

Here is what I have so far. When I run the program and enter a value in the chat box, it presses the key infinitely and does not stop, freezing the computer.

```<code>import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

class Game {
    String[] rawCommands = { "up", "down", "left", "right", "start", "select", "a", "b", "x", "y", "l", "r" };
    int[] transCommands = { KeyEvent.VK_A, KeyEvent.VK_B, KeyEvent.VK_C, KeyEvent.VK_D, KeyEvent.VK_E, KeyEvent.VK_F,
            KeyEvent.VK_G, KeyEvent.VK_H, KeyEvent.VK_I, KeyEvent.VK_J, KeyEvent.VK_K, KeyEvent.VK_L };
    ArrayList<String> seen = new ArrayList<String>();

    void main() {
        while (true) {
            HashMap<Integer, String[]> messages = listChatMessages();

            for (int i = 0; i < messages.size(); i++) {
                String[] full = messages.get(i);
                String id = full[0];
                String msg = full[1];

                Result r = oneOfManyIgnoreCase(msg, rawCommands);
                if (r.bool) {
                    if (!oneOfManyIgnoreCase(id, seen.toArray(new String[seen.size()])).bool) {
                        int key = transCommands[Arrays.asList(rawCommands).indexOf(r.msg)];
                        keyPress(key);
                        if (seen.size() > 90) {
                            seen.remove(0);
                        }
                        seen.add(id);
                    }
                }
            }
        }
    }

    void deleteChatMessage(String id) {

    }

    HashMap<Integer, String[]> listChatMessages() {
        HashMap<Integer, String[]> messages = new HashMap<>();
        try {
            URL response = new URL("https://www.googleapis.com/youtube/v3/liveChat/m"
                    + "essages?liveChatId=EiEKGFVDaUxwMWJTNFpvc2JlaHA5bHppbGNJQRIFL2xpdmU&part=sn"
                    + "ippet&key=AIzaSyAYFLriWHDy8MJZ_zblU-GuovOoqg6L-28&maxResults=200&pageToken=GKf04s3c7tcCILjGoM7c7tcC");
            ReadableByteChannel rbc = Channels.newChannel(response.openStream());
            FileOutputStream fos = new FileOutputStream("messages.json");
            fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
            fos.close();

            JSONParser parser = new JSONParser();
            Object obj = parser.parse(new FileReader("messages.json"));
            JSONObject jObj = (JSONObject) obj;
            JSONArray jArr = (JSONArray) jObj.get("items");
            for (int i = 0; i < jArr.size(); i++) {
                JSONObject msg = (JSONObject) jArr.get(i);
                JSONObject snippet = (JSONObject) msg.get("snippet");
                JSONObject txtDetails = (JSONObject) snippet.get("textMessageDetails");
                String[] full = new String[2];
                full[1] = (String) txtDetails.get("messageText");
                full[0] = (String) msg.get("id");

                messages.put(i, full);

            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return messages;
    }

    void keyPress(int key) {
        new Thread(new Runnable() {
            public void run() {
                try {
                    Robot bot = new Robot();
                    bot.setAutoDelay(1);

                    int duration = 3000;
                    long start = System.currentTimeMillis();
                    while (System.currentTimeMillis() - start < duration) {
                        bot.keyPress(key);
                        bot.keyRelease(key);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }).start();
    }

    Result oneOfManyIgnoreCase(String one, String[] many) {
        Boolean match = false;
        String message = "";
        for (String man : many) {
            if (one.equalsIgnoreCase(man)) {
                match = true;
                message = man;
                break;
            }
        }
        Result r = new Result(match, message);
        return r;
    }
}
</code>```

答:
The code below is not a good way to handle key presses. Generally if you want to hold down a key programatically, then you should make the key press occur until the time is up and then after the time is complete wait for like 2 milliseconds and then release the key. I don't think that you are giving the keyboard driver enough time to process the release. Additionally. Try only doing the keypress once, or at least as few times as you need. Usually I think that you only have to press it once and release it once the time is complete if I'm not mistaken.</p>

```<code>while (System.currentTimeMillis() - start < duration) {
    bot.keyPress(key);
    bot.keyRelease(key);
}
</code>```

Title: Key keeps pressing many times

Body:
I am trying to create a program that will:

Take live chat messages from a livestream

If the live chat message is a certain control, press and hold that key for two seconds

Take note of that live chat ID and do not press the key again.

Here is what I have so far. When I run the program and enter a value in the chat box, it presses the key infinitely and does not stop, freezing the computer.

import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

class Game {
    String[] rawCommands = { "up", "down", "left", "right", "start", "select", "a", "b", "x", "y", "l", "r" };
    int[] transCommands = { KeyEvent.VK_A, KeyEvent.VK_B, KeyEvent.VK_C, KeyEvent.VK_D, KeyEvent.VK_E, KeyEvent.VK_F,
            KeyEvent.VK_G, KeyEvent.VK_H, KeyEvent.VK_I, KeyEvent.VK_J, KeyEvent.VK_K, KeyEvent.VK_L };
    ArrayList<String> seen = new ArrayList<String>();

    void main() {
        while (true) {
            HashMap<Integer, String[]> messages = listChatMessages();

            for (int i = 0; i < messages.size(); i++) {
                String[] full = messages.get(i);
                String id = full[0];
                String msg = full[1];

                Result r = oneOfManyIgnoreCase(msg, rawCommands);
                if (r.bool) {
                    if (!oneOfManyIgnoreCase(id, seen.toArray(new String[seen.size()])).bool) {
                        int key = transCommands[Arrays.asList(rawCommands).indexOf(r.msg)];
                        keyPress(key);
                        if (seen.size() > 90) {
                            seen.remove(0);
                        }
                        seen.add(id);
                    }
                }
            }
        }
    }

    void deleteChatMessage(String id) {

    }

    HashMap<Integer, String[]> listChatMessages() {
        HashMap<Integer, String[]> messages = new HashMap<>();
        try {
            URL response = new URL("https://www.googleapis.com/youtube/v3/liveChat/m"
                    + "essages?liveChatId=EiEKGFVDaUxwMWJTNFpvc2JlaHA5bHppbGNJQRIFL2xpdmU&part=sn"
                    + "ippet&key=AIzaSyAYFLriWHDy8MJZ_zblU-GuovOoqg6L-28&maxResults=200&pageToken=GKf04s3c7tcCILjGoM7c7tcC");
            ReadableByteChannel rbc = Channels.newChannel(response.openStream());
            FileOutputStream fos = new FileOutputStream("messages.json");
            fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
            fos.close();

            JSONParser parser = new JSONParser();
            Object obj = parser.parse(new FileReader("messages.json"));
            JSONObject jObj = (JSONObject) obj;
            JSONArray jArr = (JSONArray) jObj.get("items");
            for (int i = 0; i < jArr.size(); i++) {
                JSONObject msg = (JSONObject) jArr.get(i);
                JSONObject snippet = (JSONObject) msg.get("snippet");
                JSONObject txtDetails = (JSONObject) snippet.get("textMessageDetails");
                String[] full = new String[2];
                full[1] = (String) txtDetails.get("messageText");
                full[0] = (String) msg.get("id");

                messages.put(i, full);

            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return messages;
    }

    void keyPress(int key) {
        new Thread(new Runnable() {
            public void run() {
                try {
                    Robot bot = new Robot();
                    bot.setAutoDelay(1);

                    int duration = 3000;
                    long start = System.currentTimeMillis();
                    while (System.currentTimeMillis() - start < duration) {
                        bot.keyPress(key);
                        bot.keyRelease(key);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }).start();
    }

    Result oneOfManyIgnoreCase(String one, String[] many) {
        Boolean match = false;
        String message = "";
        for (String man : many) {
            if (one.equalsIgnoreCase(man)) {
                match = true;
                message = man;
                break;
            }
        }
        Result r = new Result(match, message);
        return r;
    }
}

Body:
The code below is not a good way to handle key presses. Generally if you want to hold down a key programatically, then you should make the key press occur until the time is up and then after the time is complete wait for like 2 milliseconds and then release the key. I don't think that you are giving the keyboard driver enough time to process the release. Additionally. Try only doing the keypress once, or at least as few times as you need. Usually I think that you only have to press it once and release it once the time is complete if I'm not mistaken.

while (System.currentTimeMillis() - start < duration) {
    bot.keyPress(key);
    bot.keyRelease(key);
}


问:
Opening spinner by clicking on EditText
Sorry to bother you guys, but I've been strangling to get this to work.

What I want it to do:

EditText to display hint.

User clicks on EditText, opens spinner and selects their sex. That then get's turned into a string and put inside the EditText(gender)

What it is actually doing:
"Male" the first element in my spinner is already put inside my EditText before the user even clicks on it.(I never see my hint: "Sex")....and the spinner won't open at all when I try clicking on the EditText(gender)

What's going on?

My code:

```<code>    private Spinner sexSpinner;
    String[] arrayForSpinner = {"Male", "Female"};

    //Inside OnCreate method:
    sexSpinner = (Spinner)findViewById(R.id.spinner);
    adapter = new ArrayAdapter<String>(this, R.layout.spinner_row, arrayForSpinner);
    sexSpinner.setAdapter(adapter);

sexSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view,int position, long id) {
            gender.setText(sexSpinner.getSelectedItem().toString());

        }

gender.setOnFocusChangeListener(new View.OnFocusChangeListener() {

        @Override
        public void onFocusChange(View arg0, boolean hasFocus) {
            // TODO Auto-generated method stub
            if(hasFocus){
                sexSpinner.performClick();
            }
        }
    });
</code>```

Layout:

```<code><EditText
        android:layout_width="75dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="12dp"
        android:focusable="false"
        android:longClickable="false"
        android:clickable="true"
        android:inputType="date"
        android:maxLines="1"
        android:singleLine="true"
        android:hint="Gender"
        android:textColorHint="@color/white"
        android:textColor="@color/white"
        android:ems="10"
        android:id="@+id/signup_input_gender"
        android:layout_below="@+id/signup_input_birthday"
        android:layout_centerHorizontal="true"
        android:backgroundTint="@android:color/white"/>

<Spinner
        android:background="@color/Blue"
        android:id="@+id/spinner"
        android:paddingLeft="0dp"
        android:layout_width="75dp"
        android:layout_height="40dp"
        android:layout_marginRight="40dp"
        android:layout_marginBottom="6dp"
        android:layout_below="@+id/linearlayout"
        android:visibility="invisible" />
</code>```

答:
Here, I'm showing how to use an AutoCompleteTextView for this. Additionally, as I'm copying all the code from my project, I'm also adding the Imageview (delete button) I use to reset the AutoCompleteTextView.

First the XML code (Working with ConstraintLayout):

```<code><AutoCompleteTextView
        android:layout_width="200dp"
        android:layout_height="30dp"
        android:hint="Select Gender"
        android:id="@+id/acT1"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:background="#ffffff"
        android:textAlignment="center"
        android:dropDownHeight="155dp"
        android:cursorVisible="false"
        android:maxLines="1"
        android:focusable="false"
        android:clickable="true"
        android:inputType="none"
        />
    <ImageView
        android:src="@drawable/clear"
        android:layout_width="wrap_content"
        android:layout_height="20dp"
        app:layout_constraintRight_toRightOf="@+id/acT1"
        app:layout_constraintBottom_toBottomOf="@+id/acT1"
        app:layout_constraintTop_toTopOf="@+id/acT1"
        android:alpha=".2"
        android:id="@+id/delButton"
        android:contentDescription="Delete Button" />
</code>```

Now the Java Code:

```<code>        AutoCompleteTextView acTV1 = findViewById(R.id.acT1);
        ImageView delButton = findViewById(R.id.delButton);
        final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(
            this, android.R.layout.simple_list_item_1, getResources()
            .getStringArray(R.array.Gender_Names));
        String selection;
        acTV1.setAdapter(arrayAdapter);
        acTV1.setCursorVisible(false);
        acTV1.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                acTV1.showDropDown();
                selection = (String) parent.getItemAtPosition(position);
                Toast.makeText(getApplicationContext(), selection,
                Toast.LENGTH_SHORT);
                delButton.setAlpha(.8f);
            }
        });

        acTV1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View arg0) {
                acTV1.showDropDown();
            }
        });

        delButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                acTV1.setText(null);
                delButton.setAlpha(.2f);
                selection = null;
            }
        });
</code>```

And the Gender_Names Array, define it in strings.xml:

```<code> <string-array name="Gender_Names">
    <item>Male</item>
    <item>Female</item>
    <item>Other</item>
</string-array>
</code>```

This is how it looks:

Empty

With some data selected

The whole thing is a copy-paste unless you're not using ConstraintLayout.

Title: Opening spinner by clicking on EditText

Body:
Sorry to bother you guys, but I've been strangling to get this to work.

What I want it to do:

EditText to display hint.

User clicks on EditText, opens spinner and selects their sex. That then get's turned into a string and put inside the EditText(gender)

What it is actually doing:
"Male" the first element in my spinner is already put inside my EditText before the user even clicks on it.(I never see my hint: "Sex")....and the spinner won't open at all when I try clicking on the EditText(gender)

What's going on?

My code:

    private Spinner sexSpinner;
    String[] arrayForSpinner = {"Male", "Female"};

    //Inside OnCreate method:
    sexSpinner = (Spinner)findViewById(R.id.spinner);
    adapter = new ArrayAdapter<String>(this, R.layout.spinner_row, arrayForSpinner);
    sexSpinner.setAdapter(adapter);

sexSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view,int position, long id) {
            gender.setText(sexSpinner.getSelectedItem().toString());

        }

gender.setOnFocusChangeListener(new View.OnFocusChangeListener() {

        @Override
        public void onFocusChange(View arg0, boolean hasFocus) {
            // TODO Auto-generated method stub
            if(hasFocus){
                sexSpinner.performClick();
            }
        }
    });

Layout:

<EditText
        android:layout_width="75dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="12dp"
        android:focusable="false"
        android:longClickable="false"
        android:clickable="true"
        android:inputType="date"
        android:maxLines="1"
        android:singleLine="true"
        android:hint="Gender"
        android:textColorHint="@color/white"
        android:textColor="@color/white"
        android:ems="10"
        android:id="@+id/signup_input_gender"
        android:layout_below="@+id/signup_input_birthday"
        android:layout_centerHorizontal="true"
        android:backgroundTint="@android:color/white"/>

<Spinner
        android:background="@color/Blue"
        android:id="@+id/spinner"
        android:paddingLeft="0dp"
        android:layout_width="75dp"
        android:layout_height="40dp"
        android:layout_marginRight="40dp"
        android:layout_marginBottom="6dp"
        android:layout_below="@+id/linearlayout"
        android:visibility="invisible" />

Body:
Here, I'm showing how to use an AutoCompleteTextView for this. Additionally, as I'm copying all the code from my project, I'm also adding the Imageview (delete button) I use to reset the AutoCompleteTextView.

First the XML code (Working with ConstraintLayout):

<AutoCompleteTextView
        android:layout_width="200dp"
        android:layout_height="30dp"
        android:hint="Select Gender"
        android:id="@+id/acT1"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:background="#ffffff"
        android:textAlignment="center"
        android:dropDownHeight="155dp"
        android:cursorVisible="false"
        android:maxLines="1"
        android:focusable="false"
        android:clickable="true"
        android:inputType="none"
        />
    <ImageView
        android:src="@drawable/clear"
        android:layout_width="wrap_content"
        android:layout_height="20dp"
        app:layout_constraintRight_toRightOf="@+id/acT1"
        app:layout_constraintBottom_toBottomOf="@+id/acT1"
        app:layout_constraintTop_toTopOf="@+id/acT1"
        android:alpha=".2"
        android:id="@+id/delButton"
        android:contentDescription="Delete Button" />

Now the Java Code:

        AutoCompleteTextView acTV1 = findViewById(R.id.acT1);
        ImageView delButton = findViewById(R.id.delButton);
        final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(
            this, android.R.layout.simple_list_item_1, getResources()
            .getStringArray(R.array.Gender_Names));
        String selection;
        acTV1.setAdapter(arrayAdapter);
        acTV1.setCursorVisible(false);
        acTV1.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                acTV1.showDropDown();
                selection = (String) parent.getItemAtPosition(position);
                Toast.makeText(getApplicationContext(), selection,
                Toast.LENGTH_SHORT);
                delButton.setAlpha(.8f);
            }
        });

        acTV1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View arg0) {
                acTV1.showDropDown();
            }
        });

        delButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                acTV1.setText(null);
                delButton.setAlpha(.2f);
                selection = null;
            }
        });

And the Gender_Names Array, define it in strings.xml:

 <string-array name="Gender_Names">
    <item>Male</item>
    <item>Female</item>
    <item>Other</item>
</string-array>

This is how it looks:

Empty

With some data selected

The whole thing is a copy-paste unless you're not using ConstraintLayout.


问:
How to use map function instead of for loop in javascript?
This is my array :

```<code>var filteredData = [{ id: 1, phoneno: '91888888888', sender: 'test' },{ id: 2, phoneno: '9199999999999', sender: 'hel' }]
</code>```

I use for loop

```<code>for (var i = 0; i < filteredData.length; i++) {
   if (filteredData[i].sender === test) {
       console.log('worked');
   }else{
       console.log('not worked');
   }
}
</code>```

How to exactly do this with map ? in javascript instead of for loop.

答:
As mentioned in the comments, forEach is better to be used in your example. But if you insist in using map, just replace forEach with map and the code would still work.

```<code>var filteredData = [{ id: 1, phoneno: '918888888888', sender: 'test' },{ id: 2, phoneno: '918888888888', sender: 'hel' }];

filteredData.forEach(function(item){
   if (item.sender === test) {
       console.log('worked');
   }
   else {
       console.log('not worked');
   }
});
</code>```

Body:
This is my array :

var filteredData = [{ id: 1, phoneno: '91888888888', sender: 'test' },{ id: 2, phoneno: '9199999999999', sender: 'hel' }]

I use for loop

for (var i = 0; i < filteredData.length; i++) {
   if (filteredData[i].sender === test) {
       console.log('worked');
   }else{
       console.log('not worked');
   }
}

How to exactly do this with map ? in javascript instead of for loop.

Body:
As mentioned in the comments, forEach is better to be used in your example. But if you insist in using map, just replace forEach with map and the code would still work.

var filteredData = [{ id: 1, phoneno: '918888888888', sender: 'test' },{ id: 2, phoneno: '918888888888', sender: 'hel' }];

filteredData.forEach(function(item){
   if (item.sender === test) {
       console.log('worked');
   }
   else {
       console.log('not worked');
   }
});


问:
What is the difference between XML and XSD?
What is the difference between Extensible Markup Language (XML) and XML Schema Definition (XSD)?</p>

答:
SIMPLE XML EXAMPLE:

```<code><school>
  <firstname>John</firstname>
  <lastname>Smith</lastname>
</school>
</code>```

XSD OF ABOVE XML(Explained):

```<code><xs:element name="school">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="firstname" type="xs:string"/>
      <xs:element name="lastname" type="xs:string"/>
    </xs:sequence>
  </xs:complexType>
</xs:element>
</code>```

Here:

xs:element : Defines an element.

xs:sequence : Denotes child elements only appear in the order mentioned.

xs:complexType : Denotes it contains other elements.

xs:simpleType : Denotes they do not contain other elements.

type:
string,
decimal,
integer,
boolean,
date,
time,

In simple words, xsd is another way to represent and validate XML data with the specific type.

With the help of extra attributes, we can perform multiple operations.

Performing any task on xsd is simpler than xml.

ContentLicense: CC BY-SA 4.0

Body:
SIMPLE XML EXAMPLE:

<school>
  <firstname>John</firstname>
  <lastname>Smith</lastname>
</school>

XSD OF ABOVE XML(Explained):

<xs:element name="school">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="firstname" type="xs:string"/>
      <xs:element name="lastname" type="xs:string"/>
    </xs:sequence>
  </xs:complexType>
</xs:element>

Here:

xs:element : Defines an element.

xs:sequence : Denotes child elements only appear in the order mentioned.

xs:complexType : Denotes it contains other elements.

xs:simpleType : Denotes they do not contain other elements.

type:
string,
decimal,
integer,
boolean,
date,
time,

In simple words, xsd is another way to represent and validate XML data with the specific type.

With the help of extra attributes, we can perform multiple operations.

Performing any task on xsd is simpler than xml.


答:
Try this:</p>

```<code>$.ajax({
      type: 'GET',
      dataType: "json",
      data: {law_id:id},
      url: "{{ URL::to('admin/postlawid/') }}",
      success: function (data) {
            $("#sublawmasterdata tbody").innerHtml(data.table_html);
      }
});
</code>```

Title: Append table data from controller in blade through ajax

Body:
Try this:

$.ajax({
      type: 'GET',
      dataType: "json",
      data: {law_id:id},
      url: "{{ URL::to('admin/postlawid/') }}",
      success: function (data) {
            $("#sublawmasterdata tbody").innerHtml(data.table_html);
      }
});


问:
how to use subtotal in SQL

I have a table with following data

```<code> CODE  NAME   AMOUNT VAT  TOTALAMT FLAG
  10   test1   100    10    110     1
  08   test2    0     0      0      1
  05   test3   10     0      0      2
  03   test4    0     0      0      2
</code>```

I want a query which give the following output.
(Subtotal according to FLAG)

```<code> CODE  NAME   AMOUNT VAT  TOTALAMT FLAG
  10   test1   100    10    110      1
  08   test2    0     0      0       1
 NULL SUBTOTAL 100    10    110    NULL
  05   test3   10     0      0       2
  03   test4    0     0      0       2
 NULL SUBTOTAL  10    0     10     NULL
TOTAL          110    10    120    NULL
</code>```

答:
```<code>  SELECT Code,
         isNULL(NAME,'SUBTOTAL') AS NAME,
         SUM(Total) AS Total,
         SUM(Vat) AS Vat,
         SUM(TotalAmt) AS
         TotalAmt,
         Flag
   FROM TABLE GROUP BY ROLLUP(Flag,Code,Name);
</code>```

Title: how to use subtotal in SQL

Body:
I have a table with following data

 CODE  NAME   AMOUNT VAT  TOTALAMT FLAG
  10   test1   100    10    110     1
  08   test2    0     0      0      1
  05   test3   10     0      0      2
  03   test4    0     0      0      2

I want a query which give the following output.
(Subtotal according to FLAG)

 CODE  NAME   AMOUNT VAT  TOTALAMT FLAG
  10   test1   100    10    110      1
  08   test2    0     0      0       1
 NULL SUBTOTAL 100    10    110    NULL
  05   test3   10     0      0       2
  03   test4    0     0      0       2
 NULL SUBTOTAL  10    0     10     NULL
TOTAL          110    10    120    NULL


问:
Implementing mathematical theorems

This is a general design question on implementing math theorems.
I am trying to implement some math theorems, from differential geometry, in a programming language (it doesn't matter which; for simplicity I use the python language, but this should not affect the general ideas.). I can describe the question better with an example.

Theorem: Any straight line on a surface of class r>= 2 is an asymptotic curve.

How would be such a theorem implemented. Obviously the function needs a line as an argument and the surface as an argument.

```<code>def theorem (line, surface): pass
</code>```

Should the function return just true, false, or undecidable? Or should the function return "asymptotic". If we name the function "is-asymptotic", then it should return true, false, or undecidable.

The first thing that the function should check is if the line is straight. Let's don't go into details. Then, it should compute the class of the surface

```<code>def theorem (line, surface):
  if not straight(line, surface):
    return "undecidable"
  else:
    if class-of(surface) >= 2:
      ???
</code>```

The above approach drives me to return true/false. On the other hand, if I implement it as a method to a class called line, that asks for all the properties of the given line then it should return a list of properties, including "asymptotic".

Finally, what I did above is to ask for a property of a given line, our argument. The function says nothing about all the other straight lines.

How would you address the whole implementation design of theorems?

Thank you in advance.

PS. In order to further clarify the question in a programming language content, the above question is rephrased as following. Assuming I have an instance "line" of the object "Line". Do I ask the instance if it is asymptotic as in

```<code>is_asymptotic(line) # returns true/false/undecidable
</code>```

or do I ask for its properties and get a list of properties which includes the asymptotic property, as in

```<code>line_properties(line) # returns [..., "asymptotic", ...]
</code>```

or on the creation of the instance I set the attribute asymptotic, after checking if it is straight, as in

```<code>line = Line(surface) # sets line.asymptotic = True
</code>```

答:
use the sympy package.

```<code>In [153]: from sympy import *
In [154]: x = symbols('x')
In [155]: y = symbols('y')
In [156]: z = symbols('z')
In [157]: p = (x+y)**2
In [158]: p
Out[158]: (x + y)**2
In [159]: q = x**2 + 2*x*y + y**2
In [160]: p == q
Out[160]: False
In [161]: p.expand() == q
Out[161]: True
</code>```

you will likely find
https://github.com/sympy/sympy/wiki/Geometry-Module

to be helpful.

good luck!

Title: Implementing mathematical theorems

Body:
This is a general design question on implementing math theorems.
I am trying to implement some math theorems, from differential geometry, in a programming language (it doesn't matter which; for simplicity I use the python language, but this should not affect the general ideas.). I can describe the question better with an example.

Theorem: Any straight line on a surface of class r>= 2 is an asymptotic curve.

How would be such a theorem implemented. Obviously the function needs a line as an argument and the surface as an argument.

def theorem (line, surface): pass

Should the function return just true, false, or undecidable? Or should the function return "asymptotic". If we name the function "is-asymptotic", then it should return true, false, or undecidable.

The first thing that the function should check is if the line is straight. Let's don't go into details. Then, it should compute the class of the surface

def theorem (line, surface):
  if not straight(line, surface):
    return "undecidable"
  else:
    if class-of(surface) >= 2:
      ???

The above approach drives me to return true/false. On the other hand, if I implement it as a method to a class called line, that asks for all the properties of the given line then it should return a list of properties, including "asymptotic".

Finally, what I did above is to ask for a property of a given line, our argument. The function says nothing about all the other straight lines.

How would you address the whole implementation design of theorems?

Thank you in advance.

PS. In order to further clarify the question in a programming language content, the above question is rephrased as following. Assuming I have an instance "line" of the object "Line". Do I ask the instance if it is asymptotic as in

is_asymptotic(line) # returns true/false/undecidable

or do I ask for its properties and get a list of properties which includes the asymptotic property, as in

line_properties(line) # returns [..., "asymptotic", ...]

or on the creation of the instance I set the attribute asymptotic, after checking if it is straight, as in

line = Line(surface) # sets line.asymptotic = True

Body:
use the sympy package.

In [153]: from sympy import *
In [154]: x = symbols('x')
In [155]: y = symbols('y')
In [156]: z = symbols('z')
In [157]: p = (x+y)**2
In [158]: p
Out[158]: (x + y)**2
In [159]: q = x**2 + 2*x*y + y**2
In [160]: p == q
Out[160]: False
In [161]: p.expand() == q
Out[161]: True

you will likely find
https://github.com/sympy/sympy/wiki/Geometry-Module

to be helpful.

good luck!


问:
how retrieve AbpSession in a MVC view
someone know how to retrieve the ApbSession in a mvc view??

i've tried with a session, or accessing the controllers that have the session injected, but there's no way to get the currentSession to get the userId and other properties.

The Asp.net Session is not valid, because ApbSession dont work with it.

Thanks in advice.

答:
Following the suggestion of hikalkan above, here it is the code to add it in class [YourApplication]WebViewPageBase<TModel>:

public abstract class YourAppWebViewPageBase<TModel> : AbpWebViewPage<TModel>
{
    // Gp
    public IAbpSession AppSession { get; private set; }

    protected YourAppWebViewPageBase()
    {
        LocalizationSourceName = YourAppConsts.LocalizationSourceName;
        // Gp - added the AbpSession in the view
        AppSession = Abp.Dependency.SingletonDependency<IAbpSession>.Instance;
    }
}
```

Title: how retrieve AbpSession in a MVC view


问:
Python Regex - find string between html tags
I am trying to extract the string between Html tags. I can see that similar questions have been asked on stack overflow before, but I am completely new to python and I am struggling.

So if I have

```<code><b>Bold Stuff</b>
</code>```

I want to have a regular expression that leaves me with

```<code>Bold Stuff
</code>```

But all of my solutions so far have left me with things like

```<code>>Bold Stuff<
</code>```

I would really appreciate any help with this.

I had

```<code>>.*?<
</code>```

And I have seen a question on stack overflow with suggested solution

```<code>>([^<>]*)<
</code>```

But neither of these are working for me. Please could someone explain how to write a regex that says "find me the string between characters x and y not including x and y".

Thanks for any help

答:
```<code>from bs4 import BeautifulSoup

page = requests.get(url)
soup = BeautifulSoup(page.content,'html.parser')
title = soup.find('b').text
</code>```

Body:
I am trying to extract the string between Html tags. I can see that similar questions have been asked on stack overflow before, but I am completely new to python and I am struggling.

So if I have

Bold Stuff

I want to have a regular expression that leaves me with

Bold Stuff

But all of my solutions so far have left me with things like

>Bold Stuff<

I would really appreciate any help with this.

I had

>.*?<

And I have seen a question on stack overflow with suggested solution

>([^<>]*)<

But neither of these are working for me. Please could someone explain how to write a regex that says "find me the string between characters x and y not including x and y".

Thanks for any help


问:
Error Stream was not readble
I wrote the code below and I got an error (Stream was not readble) while execute this line SR = New StreamReader(FS) why and how to fix it

the code :

```<code>Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim FS As FileStream
    Dim SR As StreamReader
    Dim SW As StreamWriter
    Dim FS_Out As FileStream
    FS = New FileStream("C:\Temp\My Picture.JPG", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write)
    SR = New StreamReader(FS)
    FS_Out = New FileStream("C:\Temp\My Picture Out.JPG", FileMode.Create, FileAccess.ReadWrite)
    SW = New StreamWriter(FS_Out)

    Dim alltext As String
    FS.Seek(0, SeekOrigin.Begin)
    alltext = SR.ReadToEnd()

    'SW.Write (Buffer)

    SR.Close()
    FS.Close()

End Sub
</code>```

答:
Well look at what you've asked for:

```<code>FS = New FileStream("C:\Temp\My Picture.JPG", _
                    FileMode.OpenOrCreate, FileAccess.Write)
</code>```

You've asked to open or create a file for writing. Nothing about reading.

Now, on top of that, you're trying to use StreamReader and StreamWriter for jpeg files. Don't do that. Pictures are binary files; TextReader and TextWriter (and the subclasses) are for text files. What would the string representation of a picture look like?

Next, you ought to use "Using" statements to make sure you close your streams/readers/writers even if an exception occurs.

Next, most of the time it's simplest to use the static methods of the File class to open streams or readers for files. That way, the method you use says what you want to do with the stream - e.g. File.OpenRead, File.OpenWrite, File.ReadAllText etc.

Next, if you really want to copy the file, you can use File.Copy. If you want to read all the data into memory and copy it, you can use File.ReadAllBytes and File.WriteAllBytes which means you don't need to mess around with the streams yourself at all.

Title: Error Stream was not readble

Body:
I wrote the code below and I got an error (Stream was not readble) while execute this line SR = New StreamReader(FS) why and how to fix it

the code :

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim FS As FileStream
    Dim SR As StreamReader
    Dim SW As StreamWriter
    Dim FS_Out As FileStream
    FS = New FileStream("C:\Temp\My Picture.JPG", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write)
    SR = New StreamReader(FS)
    FS_Out = New FileStream("C:\Temp\My Picture Out.JPG", FileMode.Create, FileAccess.ReadWrite)
    SW = New StreamWriter(FS_Out)

    Dim alltext As String
    FS.Seek(0, SeekOrigin.Begin)
    alltext = SR.ReadToEnd()

    'SW.Write (Buffer)

    SR.Close()
    FS.Close()

End Sub

Body:
Well look at what you've asked for:

FS = New FileStream("C:\Temp\My Picture.JPG", _
                    FileMode.OpenOrCreate, FileAccess.Write)

You've asked to open or create a file for writing. Nothing about reading.

Now, on top of that, you're trying to use StreamReader and StreamWriter for jpeg files. Don't do that. Pictures are binary files; TextReader and TextWriter (and the subclasses) are for text files. What would the string representation of a picture look like?

Next, you ought to use "Using" statements to make sure you close your streams/readers/writers even if an exception occurs.

Next, most of the time it's simplest to use the static methods of the File class to open streams or readers for files. That way, the method you use says what you want to do with the stream - e.g. File.OpenRead, File.OpenWrite, File.ReadAllText etc.

Next, if you really want to copy the file, you can use File.Copy. If you want to read all the data into memory and copy it, you can use File.ReadAllBytes and File.WriteAllBytes which means you don't need to mess around with the streams yourself at all.


问:
Calling ASMX Web Service from Javascript
I want to call a webservice from javascript.

This is my code:

```<code>    var method="GetStock";
    var url = "http://www.mywebsite.ro/ServiceGetStock.asmx";
    $.ajax({
        type: "POST",
        url: url + "/GetStock",
        data: "{variant_id='1'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccessCall,
        error: OnErrorCall
    });

    function OnSuccessCall(response) {
        alert(response.d);
    }

    function OnErrorCall(response) {
        alert(response.status + " " + response.statusText);
    }
</code>```

My ServiceGetStock.asmx code:

```<code> [WebMethod]
    public string GetStock(int variant_id)
    {
        try
        {

            ProductVariant variant = ProductVariantManager.GetProductVariantByID(variant_id);

            return variant.Stock.ToString();
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }
</code>```

I got the error message:

POST http://www.mywebsite.ro/ServiceGetStock.asmx/GetStock 500 (Internal Server Error)

[UPDATE]

I forgot to mention that I added in webconfig of project(with webservice) because I got the error:

XMLHttpRequest cannot load http://www.mywebsite.ro/ServiceGetStock.asmx/HelloWorld. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http:// localhost:11300' is therefore not allowed access.

```<code>  <httpProtocol>
          <customHeaders>
              <add name="Access-Control-Allow-Origin" value="*" />
              <add name="Access-Control-Allow-Headers" value="Content-Type" />
          </customHeaders>
  </httpProtocol>
</code>```

答:
use dataType: "jsonp", instead of dataType: "json",
jsonp is for cross domian webservice. hope it will help.</p>

Body:
I want to call a webservice from javascript.

This is my code:

    var method="GetStock";
    var url = "http://www.mywebsite.ro/ServiceGetStock.asmx";
    $.ajax({
        type: "POST",
        url: url + "/GetStock",
        data: "{variant_id='1'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccessCall,
        error: OnErrorCall
    });

    function OnSuccessCall(response) {
        alert(response.d);
    }

    function OnErrorCall(response) {
        alert(response.status + " " + response.statusText);
    }

My ServiceGetStock.asmx code:

 [WebMethod]
    public string GetStock(int variant_id)
    {
        try
        {

            ProductVariant variant = ProductVariantManager.GetProductVariantByID(variant_id);

            return variant.Stock.ToString();
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }

I got the error message:

POST http://www.mywebsite.ro/ServiceGetStock.asmx/GetStock 500 (Internal Server Error)

[UPDATE]

I forgot to mention that I added in webconfig of project(with webservice) because I got the error:

XMLHttpRequest cannot load http://www.mywebsite.ro/ServiceGetStock.asmx/HelloWorld. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http:// localhost:11300' is therefore not allowed access.

  <httpProtocol>
          <customHeaders>
              <add name="Access-Control-Allow-Origin" value="*" />
              <add name="Access-Control-Allow-Headers" value="Content-Type" />
          </customHeaders>
  </httpProtocol>


问:
Implement FileMangerBundle (artgris) using TinyMCE with Symfony3
for my project I use FileManagerBundle of artgris. And i want to implement the windows in my view.twig, but i don't know where I need to create myFileBrowser().

This is my twig.html :

```<code>{% extends 'CoreBundle:Base:base.html.twig' %}

{% block title %}TEST DOWNLOAD{% endblock %}

{% block body %}
    <div class="row">
        <div class="col-md-12 box-blanche-ombre">
            <div class="row boutontitre">
                <div class="col-md-6">
                    <h1>TEST DOWNLOAD</h1>
                </div>
            </div>
            {% for type in ['primary','success', 'info', 'warning','danger'] %}
                {% for message in app.session.flashbag.get(type) %}
                    <p class="message bg-{{ type }}">{{ message|raw }}</p>
                {% endfor %}
            {% endfor %}
            <form method="post" action="dump.php">
                <textarea name="content"></textarea>
            </form>
        </div>
    </div>
{% endblock %}
{% block javascripts %}
    {{ parent() }}
    <script type="text/javascript">
        var BaseURL = "{{ app.request.getBaseURL() }}";
    </script>
    <script src="{{ asset('Bootstrap-Confirmation-master/bootstrap-confirmation.js') }}"></script>
    <script src="{{ asset('bootstrap-datepicker/js/bootstrap-datepicker.min.js') }}"></script>
    <script src="{{ asset('bootstrap-datepicker/locales/bootstrap-datepicker.fr.min.js') }}"></script>
     <script type="text/javascript">
        tinymce.init({
            selector: '#mytextarea',
            file_browser_callback: myFileBrowser,
            theme: 'modern',
            height: 300,
            plugins: [
                'advlist autolink link image lists charmap print preview hr anchor pagebreak spellchecker',
                'searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking',
                'save table contextmenu directionality emoticons template paste textcolor'
            ],
            toolbar: 'insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | print preview media fullpage | forecolor backcolor emoticons'
        });

        function myFileBrowser(field_name, url, type, win) {

        var cmsURL = "{{ path('file_manager', {module:'tiny', conf:'tiny'}) }}";
        if (cmsURL.indexOf("?") < 0) {
            cmsURL = cmsURL + "?type=" + type;
        }
        else {
            cmsURL = cmsURL + "&type=" + type;
        }

        tinyMCE.activeEditor.windowManager.open({
            file: cmsURL,
            title: 'File Manager',
            width: 1024,
            height: 500
        }, {
            window: win,
            input: field_name
        });
        return false;
    }
    </script>
{% endblock %}
</code>```

This is the link to the doc, if you have a idea, thank you !

https://github.com/artgris/FileManagerBundle/blob/master/Resources/doc/tutorials/integrate-tinymce.md

Ho yeah, I can access to mywebsite.com/manager/?conf=default

答:
You'll need to include the id you've tied TinyMCE to in your content. Like this:

<textarea name="content" id="mytextarea"></textarea>

Body:
for my project I use FileManagerBundle of artgris. And i want to implement the windows in my view.twig, but i don't know where I need to create myFileBrowser().

This is my twig.html :

{% extends 'CoreBundle:Base:base.html.twig' %}

{% block title %}TEST DOWNLOAD{% endblock %}

{% block body %}

TEST DOWNLOAD

            {% for type in ['primary','success', 'info', 'warning','danger'] %}
                {% for message in app.session.flashbag.get(type) %}

{{ message|raw }}

                {% endfor %}
            {% endfor %}
            <form method="post" action="dump.php">
                <textarea name="content"></textarea>
            </form>

{% endblock %}
{% block javascripts %}
    {{ parent() }}

{% endblock %}

This is the link to the doc, if you have a idea, thank you !

https://github.com/artgris/FileManagerBundle/blob/master/Resources/doc/tutorials/integrate-tinymce.md

Ho yeah, I can access to mywebsite.com/manager/?conf=default


问:
how to store private key securely in application in android?
i want to store a private key securely in my application. I read a lot of SO question but failed to find proper answer?

Sharedpreference is the way to store securely but rooted phone can easily find it.

Can any one tell me how to store securely a key = "The real world" in android app?

Thanks

答:
Symmetric Encryption Example - AES
Here is one very popular and highly efficient symmetric algorithm called -- Advanced Encryption Standard (AES). Based on the Rijndael cipher developed by two Belgian cryptographers, AES has been adopted by the U.S. government and is now used worldwide.

use as:

initialize

```<code>    private SecretKeySpec secrateKeyInit() {
    SecretKeySpec sks = null;
    try {
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
        sr.setSeed("any data used as random seed".getBytes());
        KeyGenerator kg = KeyGenerator.getInstance("AES");
        kg.init(128, sr);
        sks = new SecretKeySpec((kg.generateKey()).getEncoded(), "AES");
    } catch (Exception e) {
        Log.e(TAG, "AES secret key spec error");
    }
    return sks;
}
</code>```

//for incode data

```<code>private byte[] IncodeData(SecretKeySpec sks, String simplestring) {
    // Encode the original data with AES
    byte[] encodedBytes = null;
    try {
        Cipher c = Cipher.getInstance("AES");
        c.init(Cipher.ENCRYPT_MODE, sks);
        encodedBytes = c.doFinal(simplestring.getBytes());//store this any were
    } catch (Exception e) {
        Log.e(TAG, "AES encryption error");
    }
    return encodedBytes;
}
</code>```

for decode data:

```<code>    private String Decrypt(SecretKeySpec sks, byte[] incodeddata) {
    String value = null;
    // Decode the encoded data with AES
    byte[] decodedBytes = null;
    try {
        Cipher c = Cipher.getInstance("AES");
        c.init(Cipher.DECRYPT_MODE, sks);
        decodedBytes = c.doFinal(incodeddata);
        value = new String(decodedBytes);
    } catch (Exception e) {
        Log.e(TAG, "AES decryption error");
    }
    return value;
}
</code>```

save this were u want and use

OR if u have static string use

use C++ for store your string in app like

```<code>  extern "C"
    jstring
    Java_com_shrinkcom_trackvees_utils_AppController_getLogin(JNIEnv *env, jobject instance) {

        std::string hello = "hello";
        return env->NewStringUTF(hello.c_str());
    }
</code>```

using it by calling public native String stringnameincfile
it returns hello word but its not seen when u Decrypt your apk or any rooted phone

Body:
Symmetric Encryption Example - AES
Here is one very popular and highly efficient symmetric algorithm called -- Advanced Encryption Standard (AES). Based on the Rijndael cipher developed by two Belgian cryptographers, AES has been adopted by the U.S. government and is now used worldwide.

use as:

initialize

    private SecretKeySpec secrateKeyInit() {
    SecretKeySpec sks = null;
    try {
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
        sr.setSeed("any data used as random seed".getBytes());
        KeyGenerator kg = KeyGenerator.getInstance("AES");
        kg.init(128, sr);
        sks = new SecretKeySpec((kg.generateKey()).getEncoded(), "AES");
    } catch (Exception e) {
        Log.e(TAG, "AES secret key spec error");
    }
    return sks;
}

//for incode data

private byte[] IncodeData(SecretKeySpec sks, String simplestring) {
    // Encode the original data with AES
    byte[] encodedBytes = null;
    try {
        Cipher c = Cipher.getInstance("AES");
        c.init(Cipher.ENCRYPT_MODE, sks);
        encodedBytes = c.doFinal(simplestring.getBytes());//store this any were
    } catch (Exception e) {
        Log.e(TAG, "AES encryption error");
    }
    return encodedBytes;
}

for decode data:

    private String Decrypt(SecretKeySpec sks, byte[] incodeddata) {
    String value = null;
    // Decode the encoded data with AES
    byte[] decodedBytes = null;
    try {
        Cipher c = Cipher.getInstance("AES");
        c.init(Cipher.DECRYPT_MODE, sks);
        decodedBytes = c.doFinal(incodeddata);
        value = new String(decodedBytes);
    } catch (Exception e) {
        Log.e(TAG, "AES decryption error");
    }
    return value;
}

save this were u want and use

OR if u have static string use

use C++ for store your string in app like

  extern "C"
    jstring
    Java_com_shrinkcom_trackvees_utils_AppController_getLogin(JNIEnv *env, jobject instance) {

        std::string hello = "hello";
        return env->NewStringUTF(hello.c_str());
    }

using it by calling public native String stringnameincfile
it returns hello word but its not seen when u Decrypt your apk or any rooted phone


问:
How to optimize this method in Scala?
Suppose I've got class A with method foo:

```<code>class A(x: Int) { def foo(): Option[Int] = if (x > 0) Some(x) else None }
</code>```

Now I am writing function bar like this:

```<code>def bar(as: List[A]): Option[(A,  Int)] = for {
  a <- as.view.find(_.foo.nonEmpty)
  foo <- a.foo
} yield (a, foo)
</code>```

The code above works fine but what it invokes the foo method twice for the found A instance. How to re-write bar to invoke method foo only once for the found A instance ?

答:
Use streams. The elements in stream are evaluated lazily.</p>

```<code>def bar(as: List[A]): Option[(A, Int)] = {
  as
    .toStream
    .map(x => (x, x.foo()))
    .find(z => z._2.isDefined)
    .map(p => (p._1, p._2.get))
}
</code>```

Title: How to optimize this method in Scala?

Body:
Suppose I've got class A with method foo:

class A(x: Int) { def foo(): Option[Int] = if (x > 0) Some(x) else None }

Now I am writing function bar like this:

def bar(as: List[A]): Option[(A,  Int)] = for {
  a <- as.view.find(_.foo.nonEmpty)
  foo <- a.foo
} yield (a, foo)

The code above works fine but what it invokes the foo method twice for the found A instance. How to re-write bar to invoke method foo only once for the found A instance ?

Body:
Use streams. The elements in stream are evaluated lazily.

def bar(as: List[A]): Option[(A, Int)] = {
  as
    .toStream
    .map(x => (x, x.foo()))
    .find(z => z._2.isDefined)
    .map(p => (p._1, p._2.get))
}


问:
what does return code 32768 mean in "git clone"
I am having a program continuously downloading projects from GitHub and then processing them. Then I found every now and then my program stuck in the GitHub prompt for typing user account and password.

My exploration about GitHub shows that these projects are no longer valid and that if I add my account and password in to "git clone" (e.g., https://user_name:pwd@github.com/dev/proj.git) I can avoid the password prompt and get a return code 32768.

Thus I use 32768 as a way to distinguish successfully downloads and failed downloads. But it turned out that the "git clone" of many valid GitHub projects also return "32768" as the status code.

So I am likely to have misunderstood "32768". My first problem is what "32768" means as a return code of "git clone".

I need to make the program run without supervision. My second question is how to make my program figure out the "git clone" finishes successfully without typing user account and password.

------add ----
Find some debugging, I found that the return code of git clone command in Linux terminal is 128. I ran the command using os.system(cmd_git_clone), the return code of os.system is 32768.

答:
so I've just run into the same status code and had been puzzled for hours.

Turns out, for me, after debugging and reading the stderror messages, it turns out Git was complaining about not knowing who I am (See: Git: "please tell me who you are" error). I added a few lines in my program to configure my name and email in git, and everything was fine.

This seems to be quite a common error when you have scripts that do your job.


问:
Literal whitespace characters causing pattern to fail (sometimes)
I have this RegEx from my previous question. The problem is that sometimes it works, Sometimes it doesn't. I tried pasting it on an online simulator and got this: https://regex101.com/r/I3tnY4/3

The text is from a file I read using

file_get_contents

The contents of the file are complete but when I run it through the RegEx to filter it:

```<code>        $data = file_get_contents($var);
        $pat  = '/intervals \[\d+\]:\s+\Kxmin = (?P<xmin>\d+(\.\d+)?) \
                \s+xmax = (?P<xmax>\d+(\.\d+)?)\s+text = "(?P<text>[^"]*)"/m';

        // print_r($data);
        preg_match_all($pat, $data, $m);
        $result = array_map(function($a){
            return array_combine(['xmin', 'xmax', 'text'], $a);
        }, array_map(null, $m['xmin'], $m['xmax'], $m['text']));

        print_r($result);
</code>```

it returns an empty array. At first, it was working but when I added a for loop to handle multiple file upload it stopped working.

This also happened before when I tried to process the file right after it was uploaded.

Like this:

```<code>if (move_uploaded_file($_FILES["uploadedfile"]["tmp_name"], $target_file)) {
        if (file_exists($target_file)) {
            $data = file_get_contents($target_file);
            $pat  = '/intervals \[\d+\]:\s+\Kxmin = (?P<xmin>\d+(\.\d+)?) \
            \s+xmax = (?P<xmax>\d+(\.\d+)?)\s+text = "(?P<text>[^"]*)"/m';

            preg_match_all($pat, $data, $m);
            $result = array_map(function($a){
               return array_combine(['xmin', 'xmax', 'text'], $a);
            }, array_map(null, $m['xmin'], $m['xmax'], $m['text']));

            print_r($result);
        }
    }
</code>```

With the above code, the RegEx also failed since the $result array was empty. I figured that was because the file was not yet ready to be read or something. Even though when I printed the contents of the file everything was there. So what I did then was to redirect my page to another file that did the RegEx processing and surprisingly it worked there.

答:
Try the following regex instead(DEMO, PHP Demo):

```<code> /(intervals \[\d+\]:)\s+\Kxmin = (?P<xmin>\d+(\.\d+)?)\s+xmax = (?P<xmax>\d+(\.\d+)?)\s+text = "(?P<text>[^"]*)"/m
</code>```

There is no need to put all the extra space as \s+ will cover it all.

Body:
I have this RegEx from my previous question. The problem is that sometimes it works, Sometimes it doesn't. I tried pasting it on an online simulator and got this: https://regex101.com/r/I3tnY4/3

The text is from a file I read using

file_get_contents

The contents of the file are complete but when I run it through the RegEx to filter it:

        $data = file_get_contents($var);
        $pat  = '/intervals \[\d+\]:\s+\Kxmin = (?P<xmin>\d+(\.\d+)?) \
                \s+xmax = (?P<xmax>\d+(\.\d+)?)\s+text = "(?P<text>[^"]*)"/m';

        // print_r($data);
        preg_match_all($pat, $data, $m);
        $result = array_map(function($a){
            return array_combine(['xmin', 'xmax', 'text'], $a);
        }, array_map(null, $m['xmin'], $m['xmax'], $m['text']));

        print_r($result);

it returns an empty array. At first, it was working but when I added a for loop to handle multiple file upload it stopped working.

This also happened before when I tried to process the file right after it was uploaded.

Like this:

if (move_uploaded_file($_FILES["uploadedfile"]["tmp_name"], $target_file)) {
        if (file_exists($target_file)) {
            $data = file_get_contents($target_file);
            $pat  = '/intervals \[\d+\]:\s+\Kxmin = (?P<xmin>\d+(\.\d+)?) \
            \s+xmax = (?P<xmax>\d+(\.\d+)?)\s+text = "(?P<text>[^"]*)"/m';

            preg_match_all($pat, $data, $m);
            $result = array_map(function($a){
               return array_combine(['xmin', 'xmax', 'text'], $a);
            }, array_map(null, $m['xmin'], $m['xmax'], $m['text']));

            print_r($result);
        }
    }

With the above code, the RegEx also failed since the $result array was empty. I figured that was because the file was not yet ready to be read or something. Even though when I printed the contents of the file everything was there. So what I did then was to redirect my page to another file that did the RegEx processing and surprisingly it worked there.

Body:
Try the following regex instead(DEMO, PHP Demo):

 /(intervals \[\d+\]:)\s+\Kxmin = (?P<xmin>\d+(\.\d+)?)\s+xmax = (?P<xmax>\d+(\.\d+)?)\s+text = "(?P<text>[^"]*)"/m

There is no need to put all the extra space as \s+ will cover it all.