问:
Return resolve only on download complete [ http.get + Promise ]
Below is my code and I am trying to return only when the downloading of a file gets finished. But the request hangs even if download completes.

```<code>const download = async () => {
    await new Promise((resolve) => {
        let file = fs.createWriteStream('./20181221001417.zip');
        http.get('http://speedtest.ftp.otenet.gr/files/test100k.db', (response) => {
           response.pipe(file);
        });
        file.on('finish', () => resolve('hi'));
    });
}
</code>```

Any suggestion would be deeply appreciated.

答:
Your code works fine though :). In this case the writeStreamObject should be the name including the path of the file where you want to save the stream data.
From you code, it looks like you want to zip the file once the response has been successfully piped into the stream.

You can put the following code in a js file and execute it using node.js, it will download the image file into the zip directory. After that it zips that zip directory and names it file.zip.

Blockquote If you run this snippet make sure you have a zip directory available in your current directory where this snippet is going to reside. otherwise you may get error. You can give your choice of path simply adding the path to path.join for example path.join(__dirname, "your_path", "filename.extension").Sometimes the extension also matters, so be careful with that! In my case I had a jpeg file that I wanted to download but providing a .png extension in the filestream object, it created broken image.

```<code>const http = require('http');
const fs = require('fs');
const path = require('path');
const zipDir = require('zip-dir');

const download = async () => {
  return new Promise((resolve) => {
    let filePath = path.join(__dirname, 'zip', 'image.jpg');
    let writeStream = fs.createWriteStream(filePath);
    http.get('http://i3.ytimg.com/vi/J---aiyznGQ/mqdefault.jpg', (response) => {
      response.pipe(file);
    });
    // on finish event resolve the promise
    writeStream.on('finish', resolve);
  });
}

function zipTheFile() {
  let zipPath = path.join(__dirname, "file.zip");
  let sourcePath = path.join(__dirname, "zip");
  return new Promise((resolve, reject) => {
    zipDir(sourcePath, {
      saveTo: zipPath
    }, function (err, buffer) {
      if (err) {
        return reject(err);
      }
      return resolve('done');
    });
  })
}

(async () => {
  await download().catch(err => console.log(err));
  await zipTheFile();
})();
</code>```

For zipping the folder i have used zip-dir library

If you want to download the file from browser it's pretty straight forward. The idea is to put the above logic inside a Service in this case like FileDownloadService. Here downloadAndZipFile exactly does the same thing like first download the file and zip it. Afterwards it creates a ReadStream object and pipes it into the res which makes the browser to download the file.

```<code>var express = require("express");
var router = express.Router();
var path = require('path');
var mime = require('mime');
var fs = require('fs');

router.get('/download', async function (req, res) {

  await FileDownloadService.downloadAndZipFile();

  var file = path.join(__dirname, "file.zip")
  var mimetype = mime.lookup(file);

  // the name for file to be saved
  const fileName = "myzipFile"

  res.setHeader('Content-disposition', 'attachment; filename=' + fileName);
  res.setHeader('Content-type', mimetype);

  var filestream = fs.createReadStream(file);
  filestream.pipe(res);
});
module.exports = router;
</code>```

Body:
Below is my code and I am trying to return only when the downloading of a file gets finished. But the request hangs even if download completes.

const download = async () => {
    await new Promise((resolve) => {
        let file = fs.createWriteStream('./20181221001417.zip');
        http.get('http://speedtest.ftp.otenet.gr/files/test100k.db', (response) => {
           response.pipe(file);
        });
        file.on('finish', () => resolve('hi'));
    });
}

Any suggestion would be deeply appreciated.

Body:
Your code works fine though :). In this case the writeStreamObject should be the name including the path of the file where you want to save the stream data.
From you code, it looks like you want to zip the file once the response has been successfully piped into the stream.

You can put the following code in a js file and execute it using node.js, it will download the image file into the zip directory. After that it zips that zip directory and names it file.zip.

Blockquote If you run this snippet make sure you have a zip directory available in your current directory where this snippet is going to reside. otherwise you may get error. You can give your choice of path simply adding the path to path.join for example path.join(__dirname, "your_path", "filename.extension").Sometimes the extension also matters, so be careful with that! In my case I had a jpeg file that I wanted to download but providing a .png extension in the filestream object, it created broken image.

const http = require('http');
const fs = require('fs');
const path = require('path');
const zipDir = require('zip-dir');

const download = async () => {
  return new Promise((resolve) => {
    let filePath = path.join(__dirname, 'zip', 'image.jpg');
    let writeStream = fs.createWriteStream(filePath);
    http.get('http://i3.ytimg.com/vi/J---aiyznGQ/mqdefault.jpg', (response) => {
      response.pipe(file);
    });
    // on finish event resolve the promise
    writeStream.on('finish', resolve);
  });
}

function zipTheFile() {
  let zipPath = path.join(__dirname, "file.zip");
  let sourcePath = path.join(__dirname, "zip");
  return new Promise((resolve, reject) => {
    zipDir(sourcePath, {
      saveTo: zipPath
    }, function (err, buffer) {
      if (err) {
        return reject(err);
      }
      return resolve('done');
    });
  })
}

(async () => {
  await download().catch(err => console.log(err));
  await zipTheFile();
})();

For zipping the folder i have used zip-dir library

If you want to download the file from browser it's pretty straight forward. The idea is to put the above logic inside a Service in this case like FileDownloadService. Here downloadAndZipFile exactly does the same thing like first download the file and zip it. Afterwards it creates a ReadStream object and pipes it into the res which makes the browser to download the file.

var express = require("express");
var router = express.Router();
var path = require('path');
var mime = require('mime');
var fs = require('fs');

router.get('/download', async function (req, res) {

  await FileDownloadService.downloadAndZipFile();

  var file = path.join(__dirname, "file.zip")
  var mimetype = mime.lookup(file);

  // the name for file to be saved
  const fileName = "myzipFile"

  res.setHeader('Content-disposition', 'attachment; filename=' + fileName);
  res.setHeader('Content-type', mimetype);

  var filestream = fs.createReadStream(file);
  filestream.pipe(res);
});
module.exports = router;


来源: stackexchange

问:
ng-bootstrap modal is not displaying
Am using ng-bootstrap modal in my application to show dialogue box. but while clicking the button, nothing is happening, the modal is not displaying.
while debugging it could find that the action is getting called, but the modal is not showing.

this is my app.module.ts

import {NgModule }      from '@angular/core';
import {BrowserModule } from '@angular/platform-browser';
import {TaskService} from '../app/task/task.service';
import {TaskComponent} from '../app/task/task.component';
import {AppComponent }  from './app.component';
import {FormsModule ,ReactiveFormsModule} from '@angular/forms';
import {HttpModule } from '@angular/http';
import {RouterModule, Routes,Route } from '@angular/router';
import {AddNewTaskComponent} from './task/addtask.component';
import {EventComponent} from '../app/controller/event.component'
import {EventService} from '../app/service/event.service'
import {AddNewEventComponent} from '../app/controller/addevent.component'
import {AddEventService} from '../app/service/addevent.service'
import {WeatherComponent} from '../app/controller/weather.component'
import {LoginComponent} from '../app/controller/login.component'
import {RegisterComponent} from '../app/controller/register.component'
import {DashBoardcomponent} from '../app/controller/dashboard.component'
import {FeatureComponent,StoryComponents} from '../app/controller/feature.component'
import {AddTaskService} from '../app/task/addtask.service'
import {FeatureServices } from '../app/service/feature.services'
import {FileUploadComponents } from '../app/controller/fileUpload.component'
import {AngularFireModule } from 'angularfire2'
import {NgbModule } from '@ng-bootstrap/ng-bootstrap'

//index routing , redirect to login for the blank request
const indexRoutes:Route = {
  path:'',component:LoginComponent
}

// for all invalid routers , it will redirect to login component
const fallbackRoutes = {
  path:'**',component:LoginComponent
}

// order is important, routes get called on the order which they defined
const routes: Routes = [
  indexRoutes,

  { path: 'register', component: RegisterComponent },
  { path: 'dash', component: DashBoardcomponent,
    children: [
      {   // shows feature   as default
          path: '',
          redirectTo: 'feature',
          pathMatch: 'full'
      },
      {
          path: 'events',
          component: EventComponent,
            children:[
              {
                  path: 'addevent',
                  component: AddNewEventComponent
              }
            ]
      },

      {
          path: 'task',
          component: TaskComponent,
          children:[
              {
                  path: 'addtask',
                  component: AddNewTaskComponent
              }
            ]
      },
      {
         path: 'weather',
         component: WeatherComponent
      },
      {
         path: 'feature',
         component: FeatureComponent,
      },
      {
         path: 'uploads',
         component: FileUploadComponents,
      }

  ]
 }
];

export const routing = RouterModule.forRoot(routes);

      };
@NgModule({
  imports:   [
    BrowserModule ,
    FormsModule,
    ReactiveFormsModule,
    HttpModule,
    routing,
    AngularFireModule.initializeApp(firebaseConfig),
    NgbModule.forRoot()
    ],
    providers: [TaskService,EventService,AddEventService,AddTaskService,FeatureServices],
    declarations: [
      AppComponent,
      LoginComponent,
      TaskComponent,
      AddNewTaskComponent,
      EventComponent,
      AddNewEventComponent,
      WeatherComponent,
      RegisterComponent,
      DashBoardcomponent,
      FeatureComponent,
      FileUploadComponents,
      StoryComponents
     ],
  entryComponents: [StoryComponents],
    bootstrap: [
     AppComponent
    ],

})
export class AppModule { }```
</div>
</div>
</p>

<p>this is my FeatureComponent class</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { Component, ViewChild,Input } from '@angular/core';
import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal';
import {FeatureServices} from '../service/feature.services'
import {ComponentAction} from '../base/Component.action'
import {Features} from '../model/feature'
import { NgForm } from '@angular/forms';
import {NgbModal, NgbActiveModal} from '@ng-bootstrap/ng-bootstrap';

@Component({
        selector: 'addstories',
        template: `

        <div class="modal-header">
            <h4 class="modal-title">Hi there!</h4>
            <button type="button" class="close" aria-label="Close" (click)="activeModal.dismiss('Cross click')">
                <span aria-hidden="true">×</span>
            </button>
            </div>
            <div class="modal-body">
            <p>Hello, {{name}}!</p>
            </div>
            <div class="modal-footer">
            <button type="button" class="btn btn-secondary" (click)="activeModal.close('Close click')">Close</button>
        </div>

    `
})
export class StoryComponents {
  @Input() name;

  constructor(public activeModal: NgbActiveModal) {}
}

@Component({
    moduleId:module.id,
    selector:'feature',
    template:`

         <link rel="stylesheet" href="../../bower_components/bootstrap/dist/css/bootstrap.min.css">

        <div>
            <button class="btn btn-primary" (click)="listFeature()">All Features</button>
            <button class="btn btn-primary" (click)="showAddFeature()" >Add Features</button>
        </div>
        {{enableAddFeature}}
            <!-- loads child component list task and add new task -->
            <router-outlet></router-outlet>

            <form *ngIf="mode == 'insert' || mode == 'update' " #featureForm="ngForm" (ngSubmit)="processFeature(featureForm)">
                    <div class="form-group">
                        <label for="title">Feature Title</label>
                        <input type="text" class="form-control" id="title" name="title" placeholder="Enter Feature Title" [(ngModel)]=selectedFeature.title>
                    </div>
                    <div class="form-group">
                        <label for="descr">Feature Title</label>
                        <input type="text" class="form-control" id="descr" name="descr" placeholder="Enter Feature Description" [(ngModel)]=selectedFeature.descr>
                    </div>
                    <div class="form-group">
                        <label for="area">Feature Title</label>
                        <input type="text" class="form-control" id="area" name="area" placeholder="Enter Feature Area" [(ngModel)]=selectedFeature.area>
                    </div>
                    <button type="submit" class="btn btn-primary">Submit</button>

                </form>
                <br/>
          <div class="container">
            <div class="row">
                <div class="">
                    <table class="table table-hover table-responsive table-bordered">
                        <thead>
                            <tr>
                                <th class="col-md-2">Title</th>
                                <th class="col-md-2">Descr</th>
                                <th class="col-md-1">Area</th>
                                <th class="col-md-1">User Stories</th>
                                <th class="col-md-1"></th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr *ngFor="let feature of features">
                                <td>{{feature.title}}</td>
                                <td>{{feature.descr}}</td>
                                <td>{{feature.area}}</td>
                                <td *ngIf ="feature.userstories == null" >0</td>
                                <td *ngIf ="feature.userstories != null" > {{feature.userstories.length}}</td>
                                <td><span class="glyphicon glyphicon-edit"></span> Edit <span class="glyphicon glyphicon-remove"></span> Del</td>
                            </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <button type="button" class="btn btn-default" (click)="open()">Open me!</button>

    `

})

export class FeatureComponent extends ComponentAction{

    features:Features[]
    mode :string = "start";
    isEditMode = false;
    selectedFeature: Features;

    constructor(private featureService:FeatureServices,private modalService: NgbModal){
       super();
       this.getFeatures();
    }

    getFeatures(){
        this.featureService.getFeatures()
        .subscribe(result => {
            console.log('features from mongo :'+JSON.stringify(result))
            this.features = result;
            console.log('this features :'+JSON.stringify(this.features))
        })
    }

    open() {
        console.log('u clicked me');
        const modalRef = this.modalService.open(StoryComponents);
        modalRef.componentInstance.name = 'World';
        console.log('finshed');
  }

}</code>```

I have a list of features and each feature contains different user stories, so am planning to display the option to add user stories into the future on the modal.but while clicking the StoryComponent is not displaying.

答:
I also had same problem, and found out that I was not including css link for bootstrap in my styles.css. Although I was using ng-bootstrap with bootstrap v4.

```<code>@import url('../node_modules/bootstrap/dist/css/bootstrap.min.css');
</code>```

ContentLicense: CC BY-SA 3.0

Title: ng-bootstrap modal is not displaying

Body:
Am using ng-bootstrap modal in my application to show dialogue box. but while clicking the button, nothing is happening, the modal is not displaying.
while debugging it could find that the action is getting called, but the modal is not showing.

this is my app.module.ts

import {NgModule }      from '@angular/core';
import {BrowserModule } from '@angular/platform-browser';
import {TaskService} from '../app/task/task.service';
import {TaskComponent} from '../app/task/task.component';
import {AppComponent }  from './app.component';
import {FormsModule ,ReactiveFormsModule} from '@angular/forms';
import {HttpModule } from '@angular/http';
import {RouterModule, Routes,Route } from '@angular/router';
import {AddNewTaskComponent} from './task/addtask.component';
import {EventComponent} from '../app/controller/event.component'
import {EventService} from '../app/service/event.service'
import {AddNewEventComponent} from '../app/controller/addevent.component'
import {AddEventService} from '../app/service/addevent.service'
import {WeatherComponent} from '../app/controller/weather.component'
import {LoginComponent} from '../app/controller/login.component'
import {RegisterComponent} from '../app/controller/register.component'
import {DashBoardcomponent} from '../app/controller/dashboard.component'
import {FeatureComponent,StoryComponents} from '../app/controller/feature.component'
import {AddTaskService} from '../app/task/addtask.service'
import {FeatureServices } from '../app/service/feature.services'
import {FileUploadComponents } from '../app/controller/fileUpload.component'
import {AngularFireModule } from 'angularfire2'
import {NgbModule } from '@ng-bootstrap/ng-bootstrap'

//index routing , redirect to login for the blank request
const indexRoutes:Route = {
  path:'',component:LoginComponent
}

// for all invalid routers , it will redirect to login component
const fallbackRoutes = {
  path:'**',component:LoginComponent
}

// order is important, routes get called on the order which they defined
const routes: Routes = [
  indexRoutes,

  { path: 'register', component: RegisterComponent },
  { path: 'dash', component: DashBoardcomponent,
    children: [
      {   // shows feature   as default
          path: '',
          redirectTo: 'feature',
          pathMatch: 'full'
      },
      {
          path: 'events',
          component: EventComponent,
            children:[
              {
                  path: 'addevent',
                  component: AddNewEventComponent
              }
            ]
      },

      {
          path: 'task',
          component: TaskComponent,
          children:[
              {
                  path: 'addtask',
                  component: AddNewTaskComponent
              }
            ]
      },
      {
         path: 'weather',
         component: WeatherComponent
      },
      {
         path: 'feature',
         component: FeatureComponent,
      },
      {
         path: 'uploads',
         component: FileUploadComponents,
      }

  ]
 }
];

export const routing = RouterModule.forRoot(routes);

      };
@NgModule({
  imports:   [
    BrowserModule ,
    FormsModule,
    ReactiveFormsModule,
    HttpModule,
    routing,
    AngularFireModule.initializeApp(firebaseConfig),
    NgbModule.forRoot()
    ],
    providers: [TaskService,EventService,AddEventService,AddTaskService,FeatureServices],
    declarations: [
      AppComponent,
      LoginComponent,
      TaskComponent,
      AddNewTaskComponent,
      EventComponent,
      AddNewEventComponent,
      WeatherComponent,
      RegisterComponent,
      DashBoardcomponent,
      FeatureComponent,
      FileUploadComponents,
      StoryComponents
     ],
  entryComponents: [StoryComponents],
    bootstrap: [
     AppComponent
    ],

})
export class AppModule { }

this is my FeatureComponent class

import { Component, ViewChild,Input } from '@angular/core';
import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal';
import {FeatureServices} from '../service/feature.services'
import {ComponentAction} from '../base/Component.action'
import {Features} from '../model/feature'
import { NgForm } from '@angular/forms';
import {NgbModal, NgbActiveModal} from '@ng-bootstrap/ng-bootstrap';

@Component({
        selector: 'addstories',
        template: `

Hi there!

            <button type="button" class="close" aria-label="Close" (click)="activeModal.dismiss('Cross click')">
                ×
            </button>

Hello, {{name}}!

            <button type="button" class="btn btn-secondary" (click)="activeModal.close('Close click')">Close</button>

    `
})
export class StoryComponents {
  @Input() name;

  constructor(public activeModal: NgbActiveModal) {}
}

@Component({
    moduleId:module.id,
    selector:'feature',
    template:`

         <link rel="stylesheet" href="../../bower_components/bootstrap/dist/css/bootstrap.min.css">

            <button class="btn btn-primary" (click)="listFeature()">All Features</button>
            <button class="btn btn-primary" (click)="showAddFeature()" >Add Features</button>

        {{enableAddFeature}}

            <router-outlet></router-outlet>

            <form *ngIf="mode == 'insert' || mode == 'update' " #featureForm="ngForm" (ngSubmit)="processFeature(featureForm)">

                        Feature Title
                        <input type="text" class="form-control" id="title" name="title" placeholder="Enter Feature Title" [(ngModel)]=selectedFeature.title>

                        Feature Title
                        <input type="text" class="form-control" id="descr" name="descr" placeholder="Enter Feature Description" [(ngModel)]=selectedFeature.descr>

                        Feature Title
                        <input type="text" class="form-control" id="area" name="area" placeholder="Enter Feature Area" [(ngModel)]=selectedFeature.area>

                    <button type="submit" class="btn btn-primary">Submit</button>

                </form>

                                Title
                                Descr
                                Area
                                User Stories

                                {{feature.title}}
                                {{feature.descr}}
                                {{feature.area}}
                                0
                                 {{feature.userstories.length}}
                                 Edit  Del

    <button type="button" class="btn btn-default" (click)="open()">Open me!</button>

    `

})

export class FeatureComponent extends ComponentAction{

    features:Features[]
    mode :string = "start";
    isEditMode = false;
    selectedFeature: Features;

    constructor(private featureService:FeatureServices,private modalService: NgbModal){
       super();
       this.getFeatures();
    }

    getFeatures(){
        this.featureService.getFeatures()
        .subscribe(result => {
            console.log('features from mongo :'+JSON.stringify(result))
            this.features = result;
            console.log('this features :'+JSON.stringify(this.features))
        })
    }

    open() {
        console.log('u clicked me');
        const modalRef = this.modalService.open(StoryComponents);
        modalRef.componentInstance.name = 'World';
        console.log('finshed');
  }

}

I have a list of features and each feature contains different user stories, so am planning to display the option to add user stories into the future on the modal.but while clicking the StoryComponent is not displaying.

Body:
I also had same problem, and found out that I was not including css link for bootstrap in my styles.css. Although I was using ng-bootstrap with bootstrap v4.

@import url('../node_modules/bootstrap/dist/css/bootstrap.min.css');

ContentLicense: CC BY-SA 4.0


问:
How can add a Custom filter / Custom search field to Sale Order view based on a field in the partner form
I have a field card_customer in partner form. What i need is i have to add a custom filter for sale orders based on the field card_customer. When choosing this filter i need the sale orders, which have customers with card_customer field equaling True.

答:
That's possible by creating the filter "technically". A normal user can't do that in vanilla Odoo sofar. Hopefully that feature will come one day.

"Technically" means either in a custom module or by using the debug mode in the client. Odoo can use dot-Notation in domains on such filters. And an admin can use this to create a custom filter directly in the client.

Creating in debug mode

active the debug mode

either go to Settings/Technical/user-defined filters OR open "Manage filters" in the debug context menu in the sales order list view

create the filter

Create a filter in custom module

  <record id="my_customer_filter" model="ir.filters">
    <field name="action_id" eval="False"/>
    <field name="active" eval="True"/>
    <field name="context">{}</field>
    <field name="domain">[["partner_id.card_customer","=",True]]</field>
    <field name="is_default" eval="True"/>
    <field name="model_id">sale.order</field>
    <field name="name">cart_customer is true</field>
    <field name="sort">[]</field>
  </record>
```

<p><strong>Create a filter in search view in a custom module</strong></p>

<pre class="lang-xml prettyprint-override"><code>        <record id="view_sales_order_filter" model="ir.ui.view">
            <field name="name">sale.order.list.select</field>
            <field name="model">sale.order</field>
            <field name="inherit_id" ref="sale.view_sales_order_filter" />
            <field name="arch" type="xml">
                <filter name="need_message" position="after">
                    <filter name="filter_card_customer_true" string="card_customer is true"
                        domain="[('partner_id.card_customer','=',True)]" />
                </filter>
            </field>
        </record>
</code>```

Body:
That's possible by creating the filter "technically". A normal user can't do that in vanilla Odoo sofar. Hopefully that feature will come one day.

"Technically" means either in a custom module or by using the debug mode in the client. Odoo can use dot-Notation in domains on such filters. And an admin can use this to create a custom filter directly in the client.

Creating in debug mode

active the debug mode

either go to Settings/Technical/user-defined filters OR open "Manage filters" in the debug context menu in the sales order list view

create the filter

Create a filter in custom module

  <record id="my_customer_filter" model="ir.filters">
    <field name="action_id" eval="False"/>
    <field name="active" eval="True"/>
    <field name="context">{}</field>
    <field name="domain">[["partner_id.card_customer","=",True]]</field>
    <field name="is_default" eval="True"/>
    <field name="model_id">sale.order</field>
    <field name="name">cart_customer is true</field>
    <field name="sort">[]</field>
  </record>

Create a filter in search view in a custom module

        <record id="view_sales_order_filter" model="ir.ui.view">
            <field name="name">sale.order.list.select</field>
            <field name="model">sale.order</field>
            <field name="inherit_id" ref="sale.view_sales_order_filter" />
            <field name="arch" type="xml">
                <filter name="need_message" position="after">
                    <filter name="filter_card_customer_true" string="card_customer is true"
                        domain="[('partner_id.card_customer','=',True)]" />
                </filter>
            </field>
        </record>


问:
inner joining a table with a long key
I have 30 character long key between two tables in my database,

The following is an example

CustomerID ::

```<code> '004a1dcc-74d4-43ee-ad0f-c142334c86ef'
</code>```

The following is the example of the select statement i have used

```<code>SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
</code>```

The result of the inner join is zero records which is not correct since the number is unique in both tables

答:
could be you have some fixed  legnth data type (char ..)  so you could trt using a proepr trim

```<code> SELECT Orders.OrderID, Customers.CustomerName
 FROM Orders
 INNER JOIN Customers ON trim(Orders.CustomerID ) = trim(Customers.CustomerID);
</code>```

if this is true you could avoid this problem (and the possible   performance degrade based on the use on function) using varchar datatype

Title: inner joining a table with a long key

Body:
I have 30 character long key between two tables in my database,

The following is an example

CustomerID ::

 '004a1dcc-74d4-43ee-ad0f-c142334c86ef'

The following is the example of the select statement i have used

SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;

The result of the inner join is zero records which is not correct since the number is unique in both tables

Body:
could be you have some fixed  legnth data type (char ..)  so you could trt using a proepr trim

 SELECT Orders.OrderID, Customers.CustomerName
 FROM Orders
 INNER JOIN Customers ON trim(Orders.CustomerID ) = trim(Customers.CustomerID);

if this is true you could avoid this problem (and the possible   performance degrade based on the use on function) using varchar datatype


问:
How to fix Boot layer in initialization in selenium webdriver
I'm using selenium webdriver tool for automation testing. In this, I am facing an error whenever I import the safariwebdriver class and Webdriver method. The error sign not resolve.

Error occurred during initialization of boot layer
  java.lang.module.ResolutionException: Modules
  selenium.server.standalone and okio export package
  org.openqa.selenium.safari to module net.bytebuddy

答:
Kindly insert external jar of selenium from here, as its not detected by eclipse as shown in screenshot

OR

If those jars are already present,
This happens when you have added the external jars in the ModulePath.

Solution:

Remove the external jars from the node "Modulepath".

Select the node "Classpath" then add the external jars.

Review that all the jars are under the node "Classpath".


问:
Django query if field has chosen
I have 2 models : ServiceRequest and Quote like this:

```<code>class ServiceRequest(models.Model):
   post_time = models.DateTimeField(default=timezone.now)

class Quote(models.Model):
   service_request = models.ForeignKey(ServiceRequest, on_delete=models.CASCADE)
   status = models.BooleanField(default=False)
</code>```

My question is: how to get queryset from ServiceRequest can know one of Quote has status is True ?

Example : ServiceRequest id = 1 , have 2 Quote. One status is True and one is False.
ServiceRequest id = 2 have 2 Quote, both them status is False.

I want id=1 return True, and id=2 return False

Thank you

答:
You can filter on whether there exists a related Quote with status True.</p>

```<code>Quote.objects.filter(service_request_id=1, status=True).exists()
</code>```

Title: Django query if field has chosen

Body:
I have 2 models : ServiceRequest and Quote like this:

class ServiceRequest(models.Model):
   post_time = models.DateTimeField(default=timezone.now)

class Quote(models.Model):
   service_request = models.ForeignKey(ServiceRequest, on_delete=models.CASCADE)
   status = models.BooleanField(default=False)

My question is: how to get queryset from ServiceRequest can know one of Quote has status is True ?

Example : ServiceRequest id = 1 , have 2 Quote. One status is True and one is False.
ServiceRequest id = 2 have 2 Quote, both them status is False.

I want id=1 return True, and id=2 return False

Thank you

Body:
You can filter on whether there exists a related Quote with status True.

Quote.objects.filter(service_request_id=1, status=True).exists()


问:
Count all persons who has ticket filed in last 12 months Grouped per month
I have these sample tables:

```<code>CREATE TABLE #tmp_persons (
    PersonID int primary key identity
    , FirstName varchar(max)
    , LastName varchar(max)
)

CREATE TABLE #tmp_tickets (
    TicketNum int primary key identity
    , Title varchar(max)
    , Descr varchar(max)
    , DateFiled datetime
    , SubmittedBy int FOREIGN KEY REFERENCES #tmp_persons(PersonID)
)

CREATE TABLE #tmp_assigned_lead (
    AssignmentID int primary key identity
    , PersonID int FOREIGN KEY REFERENCES #tmp_persons(PersonID) -- ID of the Lead
    , AssignedPersonID int FOREIGN KEY REFERENCES #tmp_persons(PersonID) -- ID of the person assigned
)

-- DATA DUMP
INSERT INTO #tmp_persons
VALUES
(1, 'John', 'Doe'), (2, 'Jane', 'Doe'),
(3, 'Carl', 'Smith'), (4, 'Jenny', 'Smith'),
(5, 'John', 'Wick'), (6, 'Stephanie', 'Mathews')

INSERT INTO #tmp_assigned_lead (PersonID, AssignedPersonID)
VALUES
(1, 2), (1, 3), (1, 4), (1, 5), (1, 6)

INSERT INTO #tmp_tickets (Title, Descr, DateFiled, SubmittedBy)
VALUES
('Ticket 1', 'blah', '01-01-2019', 2),
('Ticket 2', 'blah', '01-02-2019', 2),
('Ticket 3', 'blah', '05-01-2019', 4),
('Ticket 4', 'blah', '05-01-2019', 2),
('Ticket 5', 'blah', '06-01-2019', 5),
('Ticket 6', 'blah', '07-01-2019', 6),--
('Ticket 7', 'blah', '4-17-2018', 6),
('Ticket 8', 'blah', '12-30-2018', 6),
('Ticket 9', 'blah', '1-28-2019', 3),
('Ticket 10', 'blah', '3-16-2019', 3),
('Ticket 11', 'blah', '3-30-2018', 5),
('Ticket 12', 'blah', '2-4-2018', 4),
('Ticket 13', 'blah', '1-11-2019', 6),
('Ticket 14', 'blah', '9-5-2018', 6)
</code>```

So here are the points:

Each person in #tmp_persons can have a "lead" and this is stored in
a relational table #tmp_assigned_lead.

A person can file a ticket
which is stored in #tmp_tickets

A person is called a Contributor when he filed a ticket but goes back as a normal member when he doesnt file another ticket within 12 months.

Now my requirement is, I want to count all persons under a lead which have transitioned into Contributor per month. This will be a monthly record.

Sample Scenarios:

Person1 was registered Jan 01, 2018 and has never filed a ticket ever since until just Jan 01, 2019 when he filed his first ticket. This will consider Person1 as Contributor only for the month of January 2019 but he is a normal member from Jan 2018 up to Dec 2018.

Person1 filed another ticket in Feb 2019. Although he filed a new ticket, he is still not counted in Feb 2019 records of members who became Contributor since he is already a Contributor in Jan 2019

Person2 is registered in Feb 23, 2019 and immediately filed a ticket. This makes him/her a Contributor and is included in the count for "members who became contributors" in the month of Feb 2019.

This query I have come up so far groups the tickets per person and month:

```<code>SELECT
    SubmittedBy
    , MaxDate = MAX(DateFiled)
    , PeriodMonth = MONTH(DateFiled)
    , PeriodYear = YEAR(DateFiled)
FROM #tmp_tickets
GROUP BY
    SubmittedBy
    , MONTH(DateFiled)
    , YEAR(DateFiled)
</code>```

This is where I am at a roadblock. I can't come up with a query will return number of members under a lead, who became Contributors.

This is what I have so far. I used the above query as a CTE:

```<code>;with cte as (
    SELECT
        SubmittedBy
        , MaxDate = MAX(DateFiled)
        , PeriodMonth = MONTH(DateFiled)
        , PeriodYear = YEAR(DateFiled)
    FROM #tmp_tickets
    GROUP BY
        SubmittedBy
        , MONTH(DateFiled)
        , YEAR(DateFiled)
)
SELECT
    lead.PersonID
    , ContributorsCnt = COUNT(1)
    , PeriodMonth
    , PeriodYear
FROM #tmp_assigned_lead lead
INNER JOIN cte
    ON lead.AssignedPersonID = cte.SubmittedBy
-- WHERE??
-- check if member has no tickets in the past 12 months
GROUP BY
    lead.PersonID
    , PeriodMonth
    , PeriodYear
</code>```

Per data sample here, this is what the records look like in the cte above:

EDIT:

Added data dump and analysis points.

Points:

On 2018-02, PersonID 4 became a contributor. No one else filed a ticket except him. This will give us a row with:

LeadID: 1, PeriodYear: 2018, PeriodMonth: 2, Contributor: 1

On 2018-03, none other than PersonID 5 became a contributor. Again, this will give us another row:

LeadID: 1, PeriodYear: 2018, PeriodMonth: 3, Contributor: 1

On 2018-04, PersonID 6, became a contributor:

LeadID: 1, PeriodYear: 2018, PeriodMonth: 4, Contributor: 1

From 2018-05 to 2019-01, no one else became Contributor. PersonID 6 here is not counted because he is still a contributor.

On 2019-01, PersonID 2 and 3 became contributors. This is their first time filing ticket. Again, PersonID 6 is still a contributor. This will give us row:

LeadID: 1, PeriodYear: 2019, PeriodMonth: 1, Contributor: 2

On 2019-02, PersonID 4 is back to being a normal member, not a contributor, since it has been 12 months and he did not file any ticket since then. No row needed for this.

On 2019-03, PersonID 5 becomes a normal member (same logic in point #6). Person 3 filed a ticket but he is still a contributor. Overall, no row needed.

On 2019-05, Person 2 filed a ticket but he is still a contributor. Person 4 filed a ticket and he is already a regular member so he is now a Contributor:

LeadID: 1, PeriodYear: 2019, PeriodMonth: 5, Contributor: 1

On 2019-06, Person 5 becomes a contributor:

LeadID: 1, PeriodYear: 2018, PeriodMonth: 5 Contributor: 1

On 2019-07, Person 6 filed a ticket but he is still a contributor since his last ticket was filed on 2019-01. (What a busy man!)

Expected Data Set:

```<code>LeadID: 1, PeriodYear: 2018, PeriodMonth: 2, Contributor: 1
LeadID: 1, PeriodYear: 2018, PeriodMonth: 3, Contributor: 1
LeadID: 1, PeriodYear: 2018, PeriodMonth: 4, Contributor: 1
LeadID: 1, PeriodYear: 2019, PeriodMonth: 1, Contributor: 2
LeadID: 1, PeriodYear: 2019, PeriodMonth: 5, Contributor: 1
LeadID: 1, PeriodYear: 2018, PeriodMonth: 5 Contributor: 1
</code>```

I hope this helps clarify my question.

答:
Create a function that gets the list of submitted tickets for the past 12 months

```<code>ALTER FUNCTION func_isContributor(@dateFiled as DATE, @PersonID as INTEGER)
RETURNS  INTEGER
AS
BEGIN
    return
        (SELECT
            count(*)
        FROM
            tmp_tickets
        WHERE
            DateFiled BETWEEN  DATEADD(month, -12, @dateFiled) and  @dateFiled AND SubmittedBy = @PersonID)
END
</code>```

then check if the person has a record for the past 12 months

```<code>; with cte as (
    SELECT
        SubmittedBy,
        DateFiled,
        isCounted = case when dbo.func_isContributor(DateFiled,SubmittedBy) -1 = 0 then 1 else 0 END
    FROM
        tmp_tickets
)
SELECT
    lead.PersonID,
        ContributorCount = Count(1),
        PeriodMonth = MONTH(DateFiled),
        PeriodYear = YEAR(DateFiled)
FROM tmp_assigned_lead lead
INNER JOIN cte
    ON lead.AssignedPersonID = cte.SubmittedBy and cte.isCounted = 1
GROUP BY
    lead.PersonID,
    MONTH(DateFiled),
    YEAR(DateFiled)
</code>```

Body:
I have these sample tables:

CREATE TABLE #tmp_persons (
    PersonID int primary key identity
    , FirstName varchar(max)
    , LastName varchar(max)
)

CREATE TABLE #tmp_tickets (
    TicketNum int primary key identity
    , Title varchar(max)
    , Descr varchar(max)
    , DateFiled datetime
    , SubmittedBy int FOREIGN KEY REFERENCES #tmp_persons(PersonID)
)

CREATE TABLE #tmp_assigned_lead (
    AssignmentID int primary key identity
    , PersonID int FOREIGN KEY REFERENCES #tmp_persons(PersonID) -- ID of the Lead
    , AssignedPersonID int FOREIGN KEY REFERENCES #tmp_persons(PersonID) -- ID of the person assigned
)

-- DATA DUMP
INSERT INTO #tmp_persons
VALUES
(1, 'John', 'Doe'), (2, 'Jane', 'Doe'),
(3, 'Carl', 'Smith'), (4, 'Jenny', 'Smith'),
(5, 'John', 'Wick'), (6, 'Stephanie', 'Mathews')

INSERT INTO #tmp_assigned_lead (PersonID, AssignedPersonID)
VALUES
(1, 2), (1, 3), (1, 4), (1, 5), (1, 6)

INSERT INTO #tmp_tickets (Title, Descr, DateFiled, SubmittedBy)
VALUES
('Ticket 1', 'blah', '01-01-2019', 2),
('Ticket 2', 'blah', '01-02-2019', 2),
('Ticket 3', 'blah', '05-01-2019', 4),
('Ticket 4', 'blah', '05-01-2019', 2),
('Ticket 5', 'blah', '06-01-2019', 5),
('Ticket 6', 'blah', '07-01-2019', 6),--
('Ticket 7', 'blah', '4-17-2018', 6),
('Ticket 8', 'blah', '12-30-2018', 6),
('Ticket 9', 'blah', '1-28-2019', 3),
('Ticket 10', 'blah', '3-16-2019', 3),
('Ticket 11', 'blah', '3-30-2018', 5),
('Ticket 12', 'blah', '2-4-2018', 4),
('Ticket 13', 'blah', '1-11-2019', 6),
('Ticket 14', 'blah', '9-5-2018', 6)

So here are the points:

Each person in #tmp_persons can have a "lead" and this is stored in
a relational table #tmp_assigned_lead.

A person can file a ticket
which is stored in #tmp_tickets

A person is called a Contributor when he filed a ticket but goes back as a normal member when he doesnt file another ticket within 12 months.

Now my requirement is, I want to count all persons under a lead which have transitioned into Contributor per month. This will be a monthly record.

Sample Scenarios:

Person1 was registered Jan 01, 2018 and has never filed a ticket ever since until just Jan 01, 2019 when he filed his first ticket. This will consider Person1 as Contributor only for the month of January 2019 but he is a normal member from Jan 2018 up to Dec 2018.

Person1 filed another ticket in Feb 2019. Although he filed a new ticket, he is still not counted in Feb 2019 records of members who became Contributor since he is already a Contributor in Jan 2019

Person2 is registered in Feb 23, 2019 and immediately filed a ticket. This makes him/her a Contributor and is included in the count for "members who became contributors" in the month of Feb 2019.

This query I have come up so far groups the tickets per person and month:

SELECT
    SubmittedBy
    , MaxDate = MAX(DateFiled)
    , PeriodMonth = MONTH(DateFiled)
    , PeriodYear = YEAR(DateFiled)
FROM #tmp_tickets
GROUP BY
    SubmittedBy
    , MONTH(DateFiled)
    , YEAR(DateFiled)

This is where I am at a roadblock. I can't come up with a query will return number of members under a lead, who became Contributors.

This is what I have so far. I used the above query as a CTE:

;with cte as (
    SELECT
        SubmittedBy
        , MaxDate = MAX(DateFiled)
        , PeriodMonth = MONTH(DateFiled)
        , PeriodYear = YEAR(DateFiled)
    FROM #tmp_tickets
    GROUP BY
        SubmittedBy
        , MONTH(DateFiled)
        , YEAR(DateFiled)
)
SELECT
    lead.PersonID
    , ContributorsCnt = COUNT(1)
    , PeriodMonth
    , PeriodYear
FROM #tmp_assigned_lead lead
INNER JOIN cte
    ON lead.AssignedPersonID = cte.SubmittedBy
-- WHERE??
-- check if member has no tickets in the past 12 months
GROUP BY
    lead.PersonID
    , PeriodMonth
    , PeriodYear

Per data sample here, this is what the records look like in the cte above:

EDIT:

Added data dump and analysis points.

Points:

On 2018-02, PersonID 4 became a contributor. No one else filed a ticket except him. This will give us a row with:

LeadID: 1, PeriodYear: 2018, PeriodMonth: 2, Contributor: 1

On 2018-03, none other than PersonID 5 became a contributor. Again, this will give us another row:

LeadID: 1, PeriodYear: 2018, PeriodMonth: 3, Contributor: 1

On 2018-04, PersonID 6, became a contributor:

LeadID: 1, PeriodYear: 2018, PeriodMonth: 4, Contributor: 1

From 2018-05 to 2019-01, no one else became Contributor. PersonID 6 here is not counted because he is still a contributor.

On 2019-01, PersonID 2 and 3 became contributors. This is their first time filing ticket. Again, PersonID 6 is still a contributor. This will give us row:

LeadID: 1, PeriodYear: 2019, PeriodMonth: 1, Contributor: 2

On 2019-02, PersonID 4 is back to being a normal member, not a contributor, since it has been 12 months and he did not file any ticket since then. No row needed for this.

On 2019-03, PersonID 5 becomes a normal member (same logic in point #6). Person 3 filed a ticket but he is still a contributor. Overall, no row needed.

On 2019-05, Person 2 filed a ticket but he is still a contributor. Person 4 filed a ticket and he is already a regular member so he is now a Contributor:

LeadID: 1, PeriodYear: 2019, PeriodMonth: 5, Contributor: 1

On 2019-06, Person 5 becomes a contributor:

LeadID: 1, PeriodYear: 2018, PeriodMonth: 5 Contributor: 1

On 2019-07, Person 6 filed a ticket but he is still a contributor since his last ticket was filed on 2019-01. (What a busy man!)

Expected Data Set:

LeadID: 1, PeriodYear: 2018, PeriodMonth: 2, Contributor: 1
LeadID: 1, PeriodYear: 2018, PeriodMonth: 3, Contributor: 1
LeadID: 1, PeriodYear: 2018, PeriodMonth: 4, Contributor: 1
LeadID: 1, PeriodYear: 2019, PeriodMonth: 1, Contributor: 2
LeadID: 1, PeriodYear: 2019, PeriodMonth: 5, Contributor: 1
LeadID: 1, PeriodYear: 2018, PeriodMonth: 5 Contributor: 1

I hope this helps clarify my question.

Body:
Create a function that gets the list of submitted tickets for the past 12 months

ALTER FUNCTION func_isContributor(@dateFiled as DATE, @PersonID as INTEGER)
RETURNS  INTEGER
AS
BEGIN
    return
        (SELECT
            count(*)
        FROM
            tmp_tickets
        WHERE
            DateFiled BETWEEN  DATEADD(month, -12, @dateFiled) and  @dateFiled AND SubmittedBy = @PersonID)
END

then check if the person has a record for the past 12 months

; with cte as (
    SELECT
        SubmittedBy,
        DateFiled,
        isCounted = case when dbo.func_isContributor(DateFiled,SubmittedBy) -1 = 0 then 1 else 0 END
    FROM
        tmp_tickets
)
SELECT
    lead.PersonID,
        ContributorCount = Count(1),
        PeriodMonth = MONTH(DateFiled),
        PeriodYear = YEAR(DateFiled)
FROM tmp_assigned_lead lead
INNER JOIN cte
    ON lead.AssignedPersonID = cte.SubmittedBy and cte.isCounted = 1
GROUP BY
    lead.PersonID,
    MONTH(DateFiled),
    YEAR(DateFiled)


问:
C#: How to add an attributes to an object at run-time?
As an entity class, I want to add an attributes at run-time, how should I do?</p>

答:
Use a hashtable to store your attributes.

If you want more runtime flexibility, you might try Ruby or some other interpreted language.

LastEditorDisplayName: Samuel

OwnerDisplayName: Bill K

ContentLicense: CC BY-SA 2.5


问:
Query returns empty set when parameters are passed from GET variables
I have a simple query with a where clause that has no results when it is run from code.

This query works fine if it is ran from the SQL Server Management studio, but when i pass some variables that are taken from GET parameters this query will show no results.Request.QueryString["q"] is not NULL.Command.ExecuteReader(); executes fine.

```<code>Connection = new SqlConnection(ConnectionString);
        Connection.Open();
        Command = new SqlCommand("", Connection);
        if (Request.QueryString["q"] != null)
        {
            Query = Request.QueryString["q"].ToString();
            Command.CommandText = "SELECT * FROM [device] WHERE [display_name] LIKE N'%@query%' OR [address] LIKE N'%@query%' ";
            Command.Parameters.AddWithValue("@query", Query);
            Reader = Command.ExecuteReader();

            while (Reader.Read())//Here Reader.HasRows=False
            {
                //Do Stuff
            }
</code>```

There is a single row in the table that has its [display_name] is equal to KHR and its [address] is equal to تست.
passing ?q=kh to the page, i get no result form this query where it actually should return a single row.

答:
[display_name] LIKE N'%@query%' will search for a row where display_name contains the text '@query' not the value of the variable @query. C# doesn't inject the value of a parameter.
You need to do something like this:

```<code>Command.CommandText = "SELECT * FROM [device] WHERE [display_name] LIKE N'%' + @query + N'%' OR [address] LIKE N'%' + @query + N'%';";
Command.Parameters.Add("@query", SqlDbType.NVarChar, 50);
Command.Parameters["@query"].Value = Query;
</code>```

Note I have also removed AddWithValue (Can we stop using AddWithValue Already?)

Body:
I have a simple query with a where clause that has no results when it is run from code.

This query works fine if it is ran from the SQL Server Management studio, but when i pass some variables that are taken from GET parameters this query will show no results.Request.QueryString["q"] is not NULL.Command.ExecuteReader(); executes fine.

Connection = new SqlConnection(ConnectionString);
        Connection.Open();
        Command = new SqlCommand("", Connection);
        if (Request.QueryString["q"] != null)
        {
            Query = Request.QueryString["q"].ToString();
            Command.CommandText = "SELECT * FROM [device] WHERE [display_name] LIKE N'%@query%' OR [address] LIKE N'%@query%' ";
            Command.Parameters.AddWithValue("@query", Query);
            Reader = Command.ExecuteReader();

            while (Reader.Read())//Here Reader.HasRows=False
            {
                //Do Stuff
            }

There is a single row in the table that has its [display_name] is equal to KHR and its [address] is equal to تست.
passing ?q=kh to the page, i get no result form this query where it actually should return a single row.

Body:
[display_name] LIKE N'%@query%' will search for a row where display_name contains the text '@query' not the value of the variable @query. C# doesn't inject the value of a parameter.
You need to do something like this:

Command.CommandText = "SELECT * FROM [device] WHERE [display_name] LIKE N'%' + @query + N'%' OR [address] LIKE N'%' + @query + N'%';";
Command.Parameters.Add("@query", SqlDbType.NVarChar, 50);
Command.Parameters["@query"].Value = Query;

Note I have also removed AddWithValue (Can we stop using AddWithValue Already?)


问:
Android Studio: Rendering Problems with CoordinatorLayout
When I set a CoordinatorLayout as my root element I get the following error when Android Studio is rendering a preview.

```<code>java.lang.NoClassDefFoundError: Could not initialize class android.support.design.widget.CoordinatorLayout
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at org.jetbrains.android.uipreview.ViewLoader.createNewInstance(ViewLoader.java:413)
    at org.jetbrains.android.uipreview.ViewLoader.loadView(ViewLoader.java:105)
    at com.android.tools.idea.rendering.LayoutlibCallback.loadView(LayoutlibCallback.java:177)
    at android.view.BridgeInflater.loadCustomView(BridgeInflater.java:214)
    at android.view.BridgeInflater.createViewFromTag(BridgeInflater.java:142)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:482)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:385)
    at com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.java:413)
    at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:321)
    at com.android.ide.common.rendering.LayoutLibrary.createSession(LayoutLibrary.java:350)
    at com.android.tools.idea.rendering.RenderTask$2.compute(RenderTask.java:497)
    at com.android.tools.idea.rendering.RenderTask$2.compute(RenderTask.java:485)
    at com.intellij.openapi.application.impl.ApplicationImpl.runReadAction(ApplicationImpl.java:894)
    at com.android.tools.idea.rendering.RenderTask.createRenderSession(RenderTask.java:485)
    at com.android.tools.idea.rendering.RenderTask.render(RenderTask.java:590)
    at org.jetbrains.android.uipreview.AndroidLayoutPreviewToolWindowManager.doRender(AndroidLayoutPreviewToolWindowManager.java:644)
    at org.jetbrains.android.uipreview.AndroidLayoutPreviewToolWindowManager.access$1700(AndroidLayoutPreviewToolWindowManager.java:79)
    at org.jetbrains.android.uipreview.AndroidLayoutPreviewToolWindowManager$7$1.run(AndroidLayoutPreviewToolWindowManager.java:586)
    at com.intellij.openapi.progress.impl.CoreProgressManager$2.run(CoreProgressManager.java:152)
    at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:452)
    at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:402)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:54)
    at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:137)
    at org.jetbrains.android.uipreview.AndroidLayoutPreviewToolWindowManager$7.run(AndroidLayoutPreviewToolWindowManager.java:581)
    at com.intellij.util.ui.update.MergingUpdateQueue.execute(MergingUpdateQueue.java:320)
    at com.intellij.util.ui.update.MergingUpdateQueue.execute(MergingUpdateQueue.java:310)
    at com.intellij.util.ui.update.MergingUpdateQueue$2.run(MergingUpdateQueue.java:254)
    at com.intellij.util.ui.update.MergingUpdateQueue.flush(MergingUpdateQueue.java:269)
    at com.intellij.util.ui.update.MergingUpdateQueue.flush(MergingUpdateQueue.java:227)
    at com.intellij.util.ui.update.MergingUpdateQueue.run(MergingUpdateQueue.java:217)
    at com.intellij.util.concurrency.QueueProcessor.runSafely(QueueProcessor.java:238)
    at com.intellij.util.Alarm$Request$1.run(Alarm.java:351)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:439)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
    at java.lang.Thread.run(Thread.java:695)
</code>```

My layout file looks like this

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar_layout"
        android:layout_width="match_parent"
        android:layout_height="@dimen/detail_backdrop_height"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleMarginEnd="64dp"
            app:expandedTitleMarginStart="48dp"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <ImageView
                android:id="@+id/img"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                android:adjustViewBounds="true"
                android:scaleType="centerCrop"
                app:layout_collapseMode="parallax" />

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/detail_recyclerview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/appbar_layout"
        android:layout_marginTop="-25dp"
        android:background="@color/background_light"
        android:paddingTop="36dp"
        android:scrollbars="vertical"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_below="@id/appbar_layout"
        android:layout_gravity="bottom|end"
        android:layout_marginEnd="16dp"
        android:layout_marginTop="-32dp"
        android:src="@android:drawable/ic_menu_call"
        app:layout_scrollFlags="scroll|exitUntilCollapsed" />
</android.support.design.widget.CoordinatorLayout>
</code>```

Here is my build.gradle

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "com.godine"
        minSdkVersion 21
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    lintOptions {
        abortOnError false
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:cardview-v7:22.2.0'
    compile 'com.android.support:recyclerview-v7:22.2.0'
    compile 'com.android.support:design:22.2.0'
    compile 'com.android.support:appcompat-v7:22.2.0'

    ...
}
</code>```

Does anyone have an idea what might be wrong here?

Edit
As @deniz already mentioned in an answer the preview works with the newest update of the Android Studio

答:
I had similar problem with AppBarLayout, it seems IDE cached some wrong version of widget.

File -> Invalidate Caches/Restart helped me.

Body:
When I set a CoordinatorLayout as my root element I get the following error when Android Studio is rendering a preview.

java.lang.NoClassDefFoundError: Could not initialize class android.support.design.widget.CoordinatorLayout
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at org.jetbrains.android.uipreview.ViewLoader.createNewInstance(ViewLoader.java:413)
    at org.jetbrains.android.uipreview.ViewLoader.loadView(ViewLoader.java:105)
    at com.android.tools.idea.rendering.LayoutlibCallback.loadView(LayoutlibCallback.java:177)
    at android.view.BridgeInflater.loadCustomView(BridgeInflater.java:214)
    at android.view.BridgeInflater.createViewFromTag(BridgeInflater.java:142)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:482)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:385)
    at com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.java:413)
    at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:321)
    at com.android.ide.common.rendering.LayoutLibrary.createSession(LayoutLibrary.java:350)
    at com.android.tools.idea.rendering.RenderTask$2.compute(RenderTask.java:497)
    at com.android.tools.idea.rendering.RenderTask$2.compute(RenderTask.java:485)
    at com.intellij.openapi.application.impl.ApplicationImpl.runReadAction(ApplicationImpl.java:894)
    at com.android.tools.idea.rendering.RenderTask.createRenderSession(RenderTask.java:485)
    at com.android.tools.idea.rendering.RenderTask.render(RenderTask.java:590)
    at org.jetbrains.android.uipreview.AndroidLayoutPreviewToolWindowManager.doRender(AndroidLayoutPreviewToolWindowManager.java:644)
    at org.jetbrains.android.uipreview.AndroidLayoutPreviewToolWindowManager.access$1700(AndroidLayoutPreviewToolWindowManager.java:79)
    at org.jetbrains.android.uipreview.AndroidLayoutPreviewToolWindowManager$7$1.run(AndroidLayoutPreviewToolWindowManager.java:586)
    at com.intellij.openapi.progress.impl.CoreProgressManager$2.run(CoreProgressManager.java:152)
    at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:452)
    at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:402)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:54)
    at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:137)
    at org.jetbrains.android.uipreview.AndroidLayoutPreviewToolWindowManager$7.run(AndroidLayoutPreviewToolWindowManager.java:581)
    at com.intellij.util.ui.update.MergingUpdateQueue.execute(MergingUpdateQueue.java:320)
    at com.intellij.util.ui.update.MergingUpdateQueue.execute(MergingUpdateQueue.java:310)
    at com.intellij.util.ui.update.MergingUpdateQueue$2.run(MergingUpdateQueue.java:254)
    at com.intellij.util.ui.update.MergingUpdateQueue.flush(MergingUpdateQueue.java:269)
    at com.intellij.util.ui.update.MergingUpdateQueue.flush(MergingUpdateQueue.java:227)
    at com.intellij.util.ui.update.MergingUpdateQueue.run(MergingUpdateQueue.java:217)
    at com.intellij.util.concurrency.QueueProcessor.runSafely(QueueProcessor.java:238)
    at com.intellij.util.Alarm$Request$1.run(Alarm.java:351)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:439)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
    at java.lang.Thread.run(Thread.java:695)

My layout file looks like this

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar_layout"
        android:layout_width="match_parent"
        android:layout_height="@dimen/detail_backdrop_height"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleMarginEnd="64dp"
            app:expandedTitleMarginStart="48dp"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <ImageView
                android:id="@+id/img"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                android:adjustViewBounds="true"
                android:scaleType="centerCrop"
                app:layout_collapseMode="parallax" />

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/detail_recyclerview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/appbar_layout"
        android:layout_marginTop="-25dp"
        android:background="@color/background_light"
        android:paddingTop="36dp"
        android:scrollbars="vertical"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_below="@id/appbar_layout"
        android:layout_gravity="bottom|end"
        android:layout_marginEnd="16dp"
        android:layout_marginTop="-32dp"
        android:src="@android:drawable/ic_menu_call"
        app:layout_scrollFlags="scroll|exitUntilCollapsed" />
</android.support.design.widget.CoordinatorLayout>

Here is my build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "com.godine"
        minSdkVersion 21
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    lintOptions {
        abortOnError false
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:cardview-v7:22.2.0'
    compile 'com.android.support:recyclerview-v7:22.2.0'
    compile 'com.android.support:design:22.2.0'
    compile 'com.android.support:appcompat-v7:22.2.0'

    ...
}

Does anyone have an idea what might be wrong here?

Edit
As @deniz already mentioned in an answer the preview works with the newest update of the Android Studio


问:
Homework about using a file for input in bash
So basically i have been assigned this homework in which i have to make a bash script that gets its input from a file of numbers, and exports the bigger number, the smaller number their sum and their average.

I have tried to find a way to do this in a simple way, he told us to do it in a fashion of ./bashscript < numbers.txt, however i cant seem to know how to search for that neither can i find a clear simple solution to the problem, i guess that finding the bigger and smaller number as well as the average should be simple once i get some stuff going but now i am at a loss...

if i were to input a .txt file that had:
3
4
5
3
2
1

It should give me the greater : 5
the smaller: 1
the amount:6
and an average:3

答:
This is not too tricky and shows how nicely you can use AWK inside of a shell script.

The BEGIN section is being executed before awk processes the file line by line.
The END section is being executed after awk processed the whole input file.

Important is to assign min and max with the 1st number found in the file. Otherwise:
a) min will i.e. always be zero if you have only numbers >0 in the file
b) to have a valid number for max even if the file has only one number/line.

$_ represents the actual line which AWK is processing.

```<code>#! /bin/sh

# script.sh - awk script embedded into shell script

awk 'BEGIN {
        count=0
} {
        if (NR == 1) {
                min=$_
                max=$_
        }
        if ($_ < min) {
                min=$_
        }
        if ($_ > max) {
                max=$_
        }
        sum+=$_
        count++
} END {
        printf ("min=%d\n", min)
        printf ("max=%d\n", max)
        printf ("avg=%d\n", sum/count)
}'
</code>```

Usage:

```<code>$ cat datafile
2
1
4
5
3

$ chmod +x script.sh
$ ./script.sh < datafile
min=1
max=5
avg=3

</code>```

Body:
This is not too tricky and shows how nicely you can use AWK inside of a shell script.

The BEGIN section is being executed before awk processes the file line by line.
The END section is being executed after awk processed the whole input file.

Important is to assign min and max with the 1st number found in the file. Otherwise:
a) min will i.e. always be zero if you have only numbers >0 in the file
b) to have a valid number for max even if the file has only one number/line.

$_ represents the actual line which AWK is processing.

#! /bin/sh

# script.sh - awk script embedded into shell script

awk 'BEGIN {
        count=0
} {
        if (NR == 1) {
                min=$_
                max=$_
        }
        if ($_ < min) {
                min=$_
        }
        if ($_ > max) {
                max=$_
        }
        sum+=$_
        count++
} END {
        printf ("min=%d\n", min)
        printf ("max=%d\n", max)
        printf ("avg=%d\n", sum/count)
}'

Usage:

$ cat datafile
2
1
4
5
3

$ chmod +x script.sh
$ ./script.sh < datafile
min=1
max=5
avg=3


问:
Change background color of buttons onclick
I have two buttons called YES and NO whose color(i,e background-color) is light like this:

When the user click YES

YES button background color should change to green (i,e success) and NO should be in light color like this:

When the user click No

NO button background color should change to red (i,e danger) and Yes should be in light color like this:

DEMO

while surfing i saw this question. Here they are changing only one button color on click. But for my requirement both the button color should change on click.

CODE

HTML

```<code><ion-content padding>
  <ion-item lines="none">
  <ion-button class="btn-1" expand="full" color="light" >Yes</ion-button>
   <ion-button class="btn-2" expand="full"  color="light" >No</ion-button>
  </ion-item>
</ion-content>
</code>```

CSS

```<code>.btn-1{
width:45%;
float:left;
padding:0px 5px 0px 5px;
margin-bottom:20px;
}
.btn-2{
width:45%;
float:right;
padding:0px 5px 0px 5px;
margin-bottom:20px;
}
</code>```

TS

```<code> import { Component } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.css'],
})
export class HomePage {

}
</code>```

答:
Here you can try this code or follow this link stackblitz:

edit your template home.page.html

```<code><ion-button (click)="activeNow('green')" class="btn-1" expand="full" [color]="(selectItem==='green')? 'success':'light'" >Yes</ion-button>
<ion-button (click)="activeNow('red')" class="btn-2" expand="full"  [color]="(selectItem==='red')? 'danger':'light'"  >No</ion-button>
</code>```

And update the home.page.ts

```<code>selectItem:string='';
activeNow(item:string) {
  this.selectItem=item;
}
</code>```

Body:
I have two buttons called YES and NO whose color(i,e background-color) is light like this:

When the user click YES

YES button background color should change to green (i,e success) and NO should be in light color like this:

When the user click No

NO button background color should change to red (i,e danger) and Yes should be in light color like this:

DEMO

while surfing i saw this question. Here they are changing only one button color on click. But for my requirement both the button color should change on click.

CODE

HTML

<ion-content padding>
  <ion-item lines="none">
  <ion-button class="btn-1" expand="full" color="light" >Yes</ion-button>
   <ion-button class="btn-2" expand="full"  color="light" >No</ion-button>
  </ion-item>
</ion-content>

CSS

.btn-1{
width:45%;
float:left;
padding:0px 5px 0px 5px;
margin-bottom:20px;
}
.btn-2{
width:45%;
float:right;
padding:0px 5px 0px 5px;
margin-bottom:20px;
}

TS

 import { Component } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.css'],
})
export class HomePage {

}

Body:
Here you can try this code or follow this link stackblitz:

edit your template home.page.html

<ion-button (click)="activeNow('green')" class="btn-1" expand="full" [color]="(selectItem==='green')? 'success':'light'" >Yes</ion-button>
<ion-button (click)="activeNow('red')" class="btn-2" expand="full"  [color]="(selectItem==='red')? 'danger':'light'"  >No</ion-button>

And update the home.page.ts

selectItem:string='';
activeNow(item:string) {
  this.selectItem=item;
}


问:
Ansible - using json imported from Consul
I have a json content on Consul that I import to my playbook. The json contains account names and passwords:

```<code>{
    "account_1": "password_1",
    "account_2": "password_2",
    "account_3": "password_3"
}
</code>```

After registering it to variable I wish to be able to use every user name and password. Since these jsons may contain different numbers of entries, I was hoping I could use with_items for this. Can someone help me out?

Debugging the whole json works with no issues:

```<code>TASK [debug] **************************************************************************
ok: [localhost] => {
    "accountsDataFromConsul.data.Value": {
        "account_1": "password_1",
        "account_2": "password_2",
        "account_3": "password_3"
    }
}
</code>```

I try to get to individual entries (user names and passwords). I tried the below code, but it returned only user names:

```<code>- debug:
    var: item
  with_items: "{{accountsDataFromConsul.data.Value}}"
</code>```

```<code>TASK [debug] ******************************************************************************
ok: [localhost] => (item=account_1) => {
    "item": "account_1"
}
ok: [localhost] => (item=account_2) => {
    "item": "account_2"
}
ok: [localhost] => (item=account_3) => {
    "item": "account_3"
}
</code>```

答:
Thank you Vladimir and Nick. That works perfectly. The only thing I had to do was using from_json on my Consul output.</p>

```<code>- set_fact:
    jsonvar: "{{accountsDataFromConsul.data.Value | from_json}}"

- debug:
    msg: "{{ item.key }} {{ item.value }}"
  loop: "{{jsonvar | dict2items}}"
</code>```

Body:
I have a json content on Consul that I import to my playbook. The json contains account names and passwords:

{
    "account_1": "password_1",
    "account_2": "password_2",
    "account_3": "password_3"
}

After registering it to variable I wish to be able to use every user name and password. Since these jsons may contain different numbers of entries, I was hoping I could use with_items for this. Can someone help me out?

Debugging the whole json works with no issues:

TASK [debug] **************************************************************************
ok: [localhost] => {
    "accountsDataFromConsul.data.Value": {
        "account_1": "password_1",
        "account_2": "password_2",
        "account_3": "password_3"
    }
}

I try to get to individual entries (user names and passwords). I tried the below code, but it returned only user names:

- debug:
    var: item
  with_items: "{{accountsDataFromConsul.data.Value}}"

TASK [debug] ******************************************************************************
ok: [localhost] => (item=account_1) => {
    "item": "account_1"
}
ok: [localhost] => (item=account_2) => {
    "item": "account_2"
}
ok: [localhost] => (item=account_3) => {
    "item": "account_3"
}

Body:
Thank you Vladimir and Nick. That works perfectly. The only thing I had to do was using from_json on my Consul output.

- set_fact:
    jsonvar: "{{accountsDataFromConsul.data.Value | from_json}}"

- debug:
    msg: "{{ item.key }} {{ item.value }}"
  loop: "{{jsonvar | dict2items}}"


问:
JavaScript: Traversing and Reversing Singly-Linked Lists and Converting Between SLLs and Numbers
INTRO
Today, while doing a mock interview with a Facebook JavaScript problem, I blanked out on how to handle singly-linked lists.  The code I had so far is simply a function that takes 2 linked lists and returns another linked list.  My plan is below.

QUESTION
You are given two non-empty linked lists of arbitrary length representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation:
  342 + 465 = 807.

PLAN

Copy each number from the first linked list into an array in order.

Reverse the array.

Convert the array to a string then to an integer and store this in a variable.

Repeat this for the second linked list.

Sum the two numbers and store this value in a variable.

Convert this sum into a string.

Use Array.from on this string to convert it into an array then reverse the array.

?

Return the new linked list.

```<code>/*
 * Definition for singly-linked list.
 * function ListNode(val)
 * {
 *  this.val = val;
 *  this.next = null;
 * }
 */

/* Expected input and output.
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */

var addTwoNumbers = function(l1, l2)
{

};

</code>```

答:
Your plan seems complicated.  Just write enough of an ADT to provide a conversion from the list to an int and add the ints.  The reverse is implemented as it's the easiest way to create the data.

function ListNode(val, next)
{
  this.val = val;
  this.next = next;
}

function listNodeFromInt(val) {
    if (val > 10) {
      return new ListNode(val % 10, listNodeFromInt(Math.trunc(val / 10)));
    }
    return new ListNode(val, null);
}

function intFromNode(node) {
  var foo = 0;
  var exp = 0;

  while(node) { foo += node.val * Math.pow(10, exp++); node = node.next }
  return foo
}

var a = listNodeFromInt(342);
console.log(a);
var b = listNodeFromInt(465);
console.log(b);

console.log(listNodeFromInt(intFromNode(a) + intFromNode(b)));```

Body:
INTRO
Today, while doing a mock interview with a Facebook JavaScript problem, I blanked out on how to handle singly-linked lists.  The code I had so far is simply a function that takes 2 linked lists and returns another linked list.  My plan is below.

QUESTION
You are given two non-empty linked lists of arbitrary length representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation:
  342 + 465 = 807.

PLAN

Copy each number from the first linked list into an array in order.

Reverse the array.

Convert the array to a string then to an integer and store this in a variable.

Repeat this for the second linked list.

Sum the two numbers and store this value in a variable.

Convert this sum into a string.

Use Array.from on this string to convert it into an array then reverse the array.

?

Return the new linked list.

/*
 * Definition for singly-linked list.
 * function ListNode(val)
 * {
 *  this.val = val;
 *  this.next = null;
 * }
 */

/* Expected input and output.
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */

var addTwoNumbers = function(l1, l2)
{

};


问:
Making TextView scrollable on Android
I am displaying text in a TextView that appears to be too long to fit
into one screen. I need to make my TextView scrollable. How can I do
that?

Here is the code:

```<code>final TextView tv = new TextView(this);
tv.setBackgroundResource(R.drawable.splash);
tv.setTypeface(face);
tv.setTextSize(18);
tv.setTextColor(R.color.BROWN);
tv.setGravity(Gravity.CENTER_VERTICAL| Gravity.CENTER_HORIZONTAL);
tv.setOnTouchListener(new OnTouchListener() {
    public boolean onTouch(View v, MotionEvent e) {
        Random r = new Random();
        int i = r.nextInt(101);
        if (e.getAction() == e.ACTION_DOWN) {
            tv.setText(tips[i]);
            tv.setBackgroundResource(R.drawable.inner);
        }
        return true;
    }
});
setContentView(tv);
</code>```

答:
In kotlin for making the textview scrollable </p>

```<code>myTextView.movementMethod= ScrollingMovementMethod()
</code>```

<p>and also add in xml this property </p>

```<code>    android:scrollbars = "vertical"
</code>```

Title: Making TextView scrollable on Android

Body:
I am displaying text in a TextView that appears to be too long to fit
into one screen. I need to make my TextView scrollable. How can I do
that?

Here is the code:

final TextView tv = new TextView(this);
tv.setBackgroundResource(R.drawable.splash);
tv.setTypeface(face);
tv.setTextSize(18);
tv.setTextColor(R.color.BROWN);
tv.setGravity(Gravity.CENTER_VERTICAL| Gravity.CENTER_HORIZONTAL);
tv.setOnTouchListener(new OnTouchListener() {
    public boolean onTouch(View v, MotionEvent e) {
        Random r = new Random();
        int i = r.nextInt(101);
        if (e.getAction() == e.ACTION_DOWN) {
            tv.setText(tips[i]);
            tv.setBackgroundResource(R.drawable.inner);
        }
        return true;
    }
});
setContentView(tv);

Body:
In kotlin for making the textview scrollable

myTextView.movementMethod= ScrollingMovementMethod()

and also add in xml this property

    android:scrollbars = "vertical"


问:
How to clear the entire workbook's conditional formatting by openpyxl
I wrote some code to do the conditional formatting. However, whenever I run the code, the cell are written with same conditional formatting once. Is there any way to clear the existing ones and write the new.

I have checked the offical documentation https://openpyxl.readthedocs.io/en/stable/formatting.html
but no clear function inside

答:
If you just want to clear the formatting for a particular worksheet you just need to create a new list:</p>

```<code>from openpyxl.formatting.formatting import ConditionalFormattingList
ws.conditional_formatting = ConditionalFormattingList()
</code>```

Body:
If you just want to clear the formatting for a particular worksheet you just need to create a new list:

from openpyxl.formatting.formatting import ConditionalFormattingList
ws.conditional_formatting = ConditionalFormattingList()


问:
Pandas: number of days elapsed since a certain date
I have a dataframe with a 'date' column with ~200 elements in the format yyyy-mm-dd.

I want to compute the number of days elapsed since 2001-11-25 for each of those elements and add a column of those numbers of elapsed days to the dataframe.

I know of the to_datetime() function but can't figure out how to make this happen.

答:
In accordance with Jeff's comment, here's a correction to the second (and most relevant) part of the accepted answer:

```<code>df['time since'] = (df['datetime_column'] - basedate).dt.days
</code>```

The subtraction yields a series of type Timedelta, which can then be represented as days.

In some case you might need to pass the original column through pd.to_datetime(...) first.

Body:
In accordance with Jeff's comment, here's a correction to the second (and most relevant) part of the accepted answer:

df['time since'] = (df['datetime_column'] - basedate).dt.days

The subtraction yields a series of type Timedelta, which can then be represented as days.

In some case you might need to pass the original column through pd.to_datetime(...) first.


问:
Inserting text file words into AVL
I am stuck on a small part of my assignment where I need to basically insert the data from the .txt file (which are just random words) and add them to my AVL tree as data.

I will show you the code I have now which doesn't work obviously, but need a few tips on how to read the file and insert it into the AVL tree as data.

Where it says [ newItem.key = (file); ] the name I type in for the .txt shows up in the AVL tree perfectly (I know this because yes its just reading my string I made), but I need the entire .txt document full of words to be placed in there as I read it not the title. I hope this makes sense and will appreciate any help.

答:
Just read the file one word at a time:</p>

```<code>while (myfile) {
  std::string word;
  myfile >> word;
  newItem.key = word;
  tree.AVL_Insert(newItem);
}
</code>```

Title: Inserting text file words into AVL

Body:
Just read the file one word at a time:

while (myfile) {
  std::string word;
  myfile >> word;
  newItem.key = word;
  tree.AVL_Insert(newItem);
}


问:
C++ macros with define or inline?

Possible Duplicate:

  Inline functions vs Preprocessor macros

Inline functions were introduced in C++ to replace C style macros (#define macroname...), still, I see lots of C++ code using old C style macros rather than inlined functions, are inlined function inferior to old C style macros?

答:
I wouldn't say they are inferior.   In C++ there's is not much you can do with a macro that you can't get the same effect with inline functions or templates.   The only thing I can think of is the '#' stringize macro operator, and I would t be surprised if Boost has a way to do that, too.  </p>

<p>However, when it comes to constants,
macros  can have one advantage - they usually won't take up any data space, but get written right into the instruction stream.  On systems with small memory footprints, this can be a major consideration.   </p>

Title: C++ macros with define or inline?

Body:
I wouldn't say they are inferior.   In C++ there's is not much you can do with a macro that you can't get the same effect with inline functions or templates.   The only thing I can think of is the '#' stringize macro operator, and I would t be surprised if Boost has a way to do that, too.

However, when it comes to constants,
macros  can have one advantage - they usually won't take up any data space, but get written right into the instruction stream.  On systems with small memory footprints, this can be a major consideration.


问:
Pop Up Comment Box In wordpress
I Want to show pop up box on my Wordpress blog when someone want to make a comment in archive file , like i have "Leave a Comment" link in my index file and when user click on that it should be pop up with comment box rather than redirect to single post page

i have tried many Plugins but nothing works

this is my code in Wordpress

```<code><?php comments_popup_link( __( 'Leave a comment', 'beautytemple' ), __( '1 Comment', 'beautytemple' ), __( '% Comments', 'beautytemple' ) ); ?>
</code>```

答: If we are using comments_popup_link() function. We have to use the_loop, have_posts() ,the_post(). The  comments_popup_link() will only work when we are using this function within the loop.

Title: Pop Up Comment Box In wordpress

Body:
I Want to show pop up box on my Wordpress blog when someone want to make a comment in archive file , like i have "Leave a Comment" link in my index file and when user click on that it should be pop up with comment box rather than redirect to single post page

i have tried many Plugins but nothing works

this is my code in Wordpress

<?php comments_popup_link( __( 'Leave a comment', 'beautytemple' ), __( '1 Comment', 'beautytemple' ), __( '% Comments', 'beautytemple' ) ); ?>


问:
In Keras, how to get 3D input and 3D output for LSTM layers
In my original setting, I got

```<code>X1 = (1200,40,1)
y1 = (1200,10)
</code>```

Then, I work perfectly with my codes:

```<code>model = Sequential()
model.add(LSTM(12, input_shape=(40, 1), return_sequences=True))
model.add(LSTM(12, return_sequences=True))
model.add(LSTM(6, return_sequences=False))
model.add((Dense(10)))
</code>```

Now, I further got another time series data same sizes as X1 and y1. i.e.,

```<code>X2 = (1200,40,1)
y2 = (1200,10)
</code>```

Now, I stack X1, X2 and y1, y2 as 3D arrays:

```<code>X_stack = (1200,40,2)
y_stack = (1200,10,2)
</code>```

Then, I try to modify my keras code like:

```<code>model = Sequential()
model.add(LSTM(12, input_shape=(40, 2), return_sequences=True))
model.add(LSTM(12, return_sequences=True))
model.add(LSTM(6, return_sequences=False))
model.add((Dense((10,2))))
</code>```

I want my code work directly with the 3D arrays X_stack and y_stack without reshaping them as 2D arrays. Would you give me a hand on how to modify the settings? Thank you.

答:
I am assuming that there is an error somewhere in the shapes that you reported for your arrays. I'm guessing y_stack.shape == (1200, 10, 2), is that correct?

However, here is one possibility to do what you describe:

```<code>model = Sequential()
model.add(LSTM(12, input_shape=(40, 2), return_sequences=True))
model.add(LSTM(12, return_sequences=True))
model.add(LSTM(6, return_sequences=False))
model.add(Dense(10 * 2))
model.add(Reshape((10, 2)))
</code>```

The output of the network is created as a 2D tensor by the Dense layer, and then reshaped to a 3D tensor by the Reshape.
From an input-output perspective, this should behave like you specified.

Body:
In my original setting, I got

X1 = (1200,40,1)
y1 = (1200,10)

Then, I work perfectly with my codes:

model = Sequential()
model.add(LSTM(12, input_shape=(40, 1), return_sequences=True))
model.add(LSTM(12, return_sequences=True))
model.add(LSTM(6, return_sequences=False))
model.add((Dense(10)))

Now, I further got another time series data same sizes as X1 and y1. i.e.,

X2 = (1200,40,1)
y2 = (1200,10)

Now, I stack X1, X2 and y1, y2 as 3D arrays:

X_stack = (1200,40,2)
y_stack = (1200,10,2)

Then, I try to modify my keras code like:

model = Sequential()
model.add(LSTM(12, input_shape=(40, 2), return_sequences=True))
model.add(LSTM(12, return_sequences=True))
model.add(LSTM(6, return_sequences=False))
model.add((Dense((10,2))))

I want my code work directly with the 3D arrays X_stack and y_stack without reshaping them as 2D arrays. Would you give me a hand on how to modify the settings? Thank you.

Body:
I am assuming that there is an error somewhere in the shapes that you reported for your arrays. I'm guessing y_stack.shape == (1200, 10, 2), is that correct?

However, here is one possibility to do what you describe:

model = Sequential()
model.add(LSTM(12, input_shape=(40, 2), return_sequences=True))
model.add(LSTM(12, return_sequences=True))
model.add(LSTM(6, return_sequences=False))
model.add(Dense(10 * 2))
model.add(Reshape((10, 2)))

The output of the network is created as a 2D tensor by the Dense layer, and then reshaped to a 3D tensor by the Reshape.
From an input-output perspective, this should behave like you specified.