问:
HTML and enable div's horizontal scrolling but hide the horizontal scrollbar
I need my div to be scrollable. Now it works fine, but I would like to hide the horizontal scrollbar. I do not want to disable it, just hide it.

All I want to see is one vertical scrollbar on the browser window. No horizontal scrollbars on the screen.

No JavaScript/jQuery allowed. I need a cross-browser solution.

#kaaviopohja {
  width: 100%;
  overflow: hidden;
  background-color: yellow;
}

#kaaviotaulukko {
  width: 100%;
  overflow-x: scroll;
  padding-bottom: 17px;
  background-color: pink;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh<br />
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh<br />
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh<br />
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh<br />
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh<br />

<DIV id="kaaviopohja">

  <div id="kaaviotaulukko" style="white-space: nowrap; position: relative; text-align: center;">
    <div style="display:inline-block">
      <!--
        -->
      <DIV STYLE="DISPLAY:INLINE-BLOCK">
        <div style="float:left;width:0">
          <div id="navi7">
            <div style="z-index:100;position:fixed;left:0;top:0;bottom:0;max-height:1em;margin:auto;">A</div>
            <div style="z-index:100;position:fixed;right:0;top:0;bottom:0;max-height:1em;margin:auto;">B</div>
          </div>
        </div>
        <div class="krs" style="display: inline-block; vertical-align: top; width: 300px;">
          <div>
            <h3>LQsssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss</h3>
          </div>
          1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />
        </div>
      </DIV>
      <!--
        -->
      <div style="float: right; width: 0;">
        <div id="navi100">
          <div style="z-index: 100; position: fixed; left: 0; top: 500px">C</div>
        </div>
      </div>
      <!--

      -->
      <div style="z-index:99;width:70px;position:fixed;left:0;top:0;bottom:0;margin:auto;background-color:red;"><br />
      </div>

      <div style="z-index:99;width:70px;position:fixed;right:0;top:0;bottom:0;margin:auto;background-color:red;"><br />
      </div>
    </div>
  </div>

</DIV></code>```

答: There's a similar question Hide scroll bar, but still being able to scroll, but I believe your question is focused on the horizontal scrollbar. In that other question, I found something that can help you, this answer. Jean posted that answer where he puts margin-bottom: -17px; in the container's child to hide the scrollbar.I did a simple jsFiddle to ilustrate his technique. It's a hack to hide the scrollbar, I didn't check if this work on all major browses but it works on chrome and firefox.

Body:
I need my div to be scrollable. Now it works fine, but I would like to hide the horizontal scrollbar. I do not want to disable it, just hide it.

All I want to see is one vertical scrollbar on the browser window. No horizontal scrollbars on the screen.

No JavaScript/jQuery allowed. I need a cross-browser solution.

#kaaviopohja {
  width: 100%;
  overflow: hidden;
  background-color: yellow;
}

#kaaviotaulukko {
  width: 100%;
  overflow-x: scroll;
  padding-bottom: 17px;
  background-color: pink;
}

hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh

hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh

hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh

hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh

hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh

A

B

LQsssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss

          1
2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10

C


来源: stackexchange

问:
Angular 2 router error
I created Angular 2 router module but it doen't work at the moment and I get an error when I want to open link /city 'ERROR Error: Uncaught (in promise): Error: Cannot activate an already activated outlet
Error: Cannot activate an already activated outlet'

But I can open this link manually

Here is the code of:
Router module

```<code>import { NgModule }from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import {WeatherListComponent} from "../weather-list/weather-list.component";
import {AddedCityComponent} from "../added-city/added-city.component";
import {AppComponent} from "../app.component";

const routes: Routes = [
    { path: '', redirectTo: '/weather-list', pathMatch: 'full'},
    { path: 'city', component: AddedCityComponent },
    { path: 'weather-list',  component: WeatherListComponent }

];

@NgModule({
    imports: [ RouterModule.forRoot(routes) ],
    exports: [ RouterModule ]
})
export class AppRoutingModule {}
</code>```

2) Appmodule

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MdButtonModule, MdCheckboxModule, MdCardModule, MdInputModule} from '@angular/material';

import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

import { AppComponent } from './app.component';
import { WeatherListComponent } from './weather-list/weather-list.component';

import { WeatherService } from './service/weather.service';
import { WeatherSearchComponent } from './weather-search/weather-search.component';
import { CloudsComponent } from './clouds/clouds.component';
import { SunComponent } from './sun/sun.component';
import { RainComponent } from './rain/rain.component';
import { AddedCityComponent } from './added-city/added-city.component';

import { AppRoutingModule } from './service/app.routing';

@NgModule({
  declarations: [
    AppComponent,
    WeatherListComponent,
    AddedCityComponent,
    WeatherSearchComponent,
    CloudsComponent,
    SunComponent,
    RainComponent

  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    BrowserAnimationsModule,
    MdButtonModule,
    MdCardModule,
    MdInputModule,
    NgbModule.forRoot(),
    AppRoutingModule

  ],
  providers: [
    WeatherService
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

3) AppComponentHTML

```<code><div class="page-wrapper" [ngClass]="{
                                    'sun-background': weatherDesc == 'Clear',
                                    'rain-background': weatherDesc == 'Rain',
                                    'clouds-background': weatherDesc == 'Clouds'
                                      }">
  <div class="container-fluid">
    <div class="row">
      <div class="col-sm-12">
        <header>
          <div class="header-wrapper">
            <h3 class=" text-left">Weather App</h3>
            <a routerLink="/city" routerLinkActive="active">cities</a>
            <a routerLink="/weather-list" routerLinkActive="active">weather</a>
            <app-weather-search></app-weather-search>
          </div>
        </header>
      </div>
    </div>
  </div>
  <!--<app-weather-list (notify)="background($event)"></app-weather-list>-->
  <!--<app-weather-list></app-weather-list>-->
  <router-outlet></router-outlet>

</div>
</code>```

答: Remove the leading slashes in the /weather-list to weather-list. This will make the first path work which might be causing the problem. Just try this out and let me know.

ContentLicense: CC BY-SA 3.0

Title: Angular 2 router error

Body:
I created Angular 2 router module but it doen't work at the moment and I get an error when I want to open link /city 'ERROR Error: Uncaught (in promise): Error: Cannot activate an already activated outlet
Error: Cannot activate an already activated outlet'

But I can open this link manually

Here is the code of:
Router module

import { NgModule }from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import {WeatherListComponent} from "../weather-list/weather-list.component";
import {AddedCityComponent} from "../added-city/added-city.component";
import {AppComponent} from "../app.component";

const routes: Routes = [
    { path: '', redirectTo: '/weather-list', pathMatch: 'full'},
    { path: 'city', component: AddedCityComponent },
    { path: 'weather-list',  component: WeatherListComponent }

];

@NgModule({
    imports: [ RouterModule.forRoot(routes) ],
    exports: [ RouterModule ]
})
export class AppRoutingModule {}

2) Appmodule

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MdButtonModule, MdCheckboxModule, MdCardModule, MdInputModule} from '@angular/material';

import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

import { AppComponent } from './app.component';
import { WeatherListComponent } from './weather-list/weather-list.component';

import { WeatherService } from './service/weather.service';
import { WeatherSearchComponent } from './weather-search/weather-search.component';
import { CloudsComponent } from './clouds/clouds.component';
import { SunComponent } from './sun/sun.component';
import { RainComponent } from './rain/rain.component';
import { AddedCityComponent } from './added-city/added-city.component';

import { AppRoutingModule } from './service/app.routing';

@NgModule({
  declarations: [
    AppComponent,
    WeatherListComponent,
    AddedCityComponent,
    WeatherSearchComponent,
    CloudsComponent,
    SunComponent,
    RainComponent

  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    BrowserAnimationsModule,
    MdButtonModule,
    MdCardModule,
    MdInputModule,
    NgbModule.forRoot(),
    AppRoutingModule

  ],
  providers: [
    WeatherService
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

3) AppComponentHTML

Weather App

            cities
            weather
            <app-weather-search></app-weather-search>

  <router-outlet></router-outlet>


问:
Self invoking function in react js ? (as in regular javascript)
I want to invoke the function good without calling it from a event. It should run as soon as page opened just like in the self invoking javascript function.
Here is an example

```<code>import React from 'react';

class App extends React.Component {

   good(){
      console.log('I was triggered during good')
   }

   render() {
       console.log('I was triggered during render')
       return(
          <div>
             good();
          </div>
      );
   }
}

export default App;
</code>```

答:
You can also use lifecycle methods as componentDidMount(){} or componentWillMount(){}.

componentWillMount will be triggered before mounting of component and componentDidMount() will be triggered after component has been mounted.

Body:
I want to invoke the function good without calling it from a event. It should run as soon as page opened just like in the self invoking javascript function.
Here is an example

import React from 'react';

class App extends React.Component {

   good(){
      console.log('I was triggered during good')
   }

   render() {
       console.log('I was triggered during render')
       return(

             good();

      );
   }
}

export default App;


问:
Changing the folder path context inside the view to root directory
I'm using MVC 4 with .NET Framework 4.5.1.

I'm using an external library to create a chart. The html references a dynamically created image,

But it's looking at /Home/chartimage.aspx?SessionID=FooBar&Delete=T (which returns file not found)

It currently exists under /chartimage.aspx?SessionID=FooBar&Delete=T

What would be the best way to fix this pathing error? I cannot change the src attribute in the img to include a '/' prior to run time it as this is generated by an external library.

Controller: /Controllers/HomeController

View: /Views/Home/Sitemaster and /Views/Home/Default.aspx.

If I make this view the default startup page it works.
RouteConfig:

```<code>        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
        //localhost:9000 Works great! But I don't want this as the default page.
        //localhost:9000/Home/Index Doesn't work :( It's trying to get the resource from /Home/chartimage.aspx...
</code>```

答:
use this link  on how to change the src value of an image.

If you want to use Rewrite URL:

```<code>   <rule name="Remove en" stopProcessing="true">
    <match url="^(.*)/Home$" />
    <action type="Rewrite" url="{R:1}" />
</rule>
</code>```

if your example is www.local.com/home/chartimage.aspx will be rewritten as

```<code>www.local.com/chartimage.aspx
</code>```

Body:
I'm using MVC 4 with .NET Framework 4.5.1.

I'm using an external library to create a chart. The html references a dynamically created image,

But it's looking at /Home/chartimage.aspx?SessionID=FooBar&Delete=T (which returns file not found)

It currently exists under /chartimage.aspx?SessionID=FooBar&Delete=T

What would be the best way to fix this pathing error? I cannot change the src attribute in the img to include a '/' prior to run time it as this is generated by an external library.

Controller: /Controllers/HomeController

View: /Views/Home/Sitemaster and /Views/Home/Default.aspx.

If I make this view the default startup page it works.
RouteConfig:

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
        //localhost:9000 Works great! But I don't want this as the default page.
        //localhost:9000/Home/Index Doesn't work :( It's trying to get the resource from /Home/chartimage.aspx...

Body:
use this link  on how to change the src value of an image.

If you want to use Rewrite URL:

   <rule name="Remove en" stopProcessing="true">
    <match url="^(.*)/Home$" />
    <action type="Rewrite" url="{R:1}" />
</rule>

if your example is www.local.com/home/chartimage.aspx will be rewritten as

www.local.com/chartimage.aspx


问:
Why is prolog unification depth-first-search instead of breadth-first-search?
I just started learning about prolog and I was wondering why it's dfs instead of bfs and why there isn't an easy way to change it.

Does ISO prolog mandate it?

答:
First of all, it is fairly easy to change. Most Prolog texts explain how both how to write a predicate that performs a BFS and how to create a meta-interpreter that does it with arbitrary terms. The truth is that students who get a taste of Prolog at the university get through (basically) the first week or two of using Prolog. To do this isn't exactly a basic Prolog task, but it isn't an advanced Prolog technique either. If you spent two months on Prolog it would not be an intimidating thing to do. That sounds like a lot of Prolog, but compared to (say) Java it really isn't much. For some reason we expect to get to the finish line with Prolog much faster than we do for systems that are actually much less interesting.

I believe the search strategy mandated by ISO is called SLD Resolution, and depth-first search arises from this resolution mechanism. I have not read the ISO standard, so perhaps someone better informed than me will comment. I think it would be difficult to manage Prolog standardization if the resolution method (and thus, depth-first or breadth-first) were not mandatory, since computations that succeed one way may enter an infinite loop the other way. A language standard that does not specify the behavior of normal-ish programs would be a rather poor standard. Although, there's no reason there couldn't be a built-in for specifying an alternate search strategy.

I don't know the reason for mandating DFS in particular. Having used Prolog for a while, the idea of not-DFS seems obviously inefficient to me. For instance, if I add some code to handle an edge case, I'm going to pay for it every time with BFS, but only in cases where it is necessary with DFS. I feel like DFS is going to be more memory efficient; I'm not going to have to keep track of a bunch of possibly-useless code paths, for instance. I feel like DFS is probably easier to control, because I can easily prune the search tree. But these are just feelings; maybe my sense of what is natural is completely a result of what I've used. The lack of existence of a Prolog competitor that is BFS-based is a kind of suggestion that it may not be a great idea though. On the other hand, what was inefficient in 1980 still informs Prolog implementations today, even though things are very different now.


问:
What is the linq query of below sql statements?
Can anybody explain me how to write equivalent LINQ query for this SQL query

```<code>select  t1.Description,t2.Description,t1.ReponseTypeID
from tblResponseType t1
   inner join tblPartnerServiceResponseType t2
      on t1.ReponseTypeID = t2.ReponseTypeID
where t1.ReponseTypeID = (select ReponseTypeID
                          from tblPartnerServiceResponseType
                          where PartnerServiceID = 1);
</code>```

I am new to this

答:
We can first try as two queries:

```<code>var psrt = tblPartnerServiceResponseType.FirstOrDefault(srt => srt.PartnerServiceID == 1);
if (psrt != null)
{
    var rt = tblResponseType.FirstOrDefault(rt => rt.ReponseTypeID == psrt.ReponseTypeID);
}
</code>```

This will work, but requires two round-trip to the dataserver.

Ok, next, let's assume that you've got you foreign keys set up right, so that tblPartnerServiceResponseType has a tblResponseType property in it:

```<code>var query = from t2 in tblPartnerServiceResponseType
            where t2.PartnerServiceID == 1
            select new {Desc1 = t2.tblResponseType.description,
                        Desc2 = t2.Description,
                        t2.ReponseTypeID
                        };
</code>```

Finally, if you DON'T have the foreign key set up (which you really SHOULD!), then we have to do the explicit join:

```<code>var query = from t2 in tblPartnerServiceResponseType
            join t1 in tblResponseType on t2.ReponseTypeID equals  t1.ReponseTypeID
        where t2.PartnerServiceID == 1
        select new {Desc1 = t1.Description,
                    Desc2 = t2.Description,
                    t2.ReponseTypeID
                    };
</code>```

Body:
Can anybody explain me how to write equivalent LINQ query for this SQL query

select  t1.Description,t2.Description,t1.ReponseTypeID
from tblResponseType t1
   inner join tblPartnerServiceResponseType t2
      on t1.ReponseTypeID = t2.ReponseTypeID
where t1.ReponseTypeID = (select ReponseTypeID
                          from tblPartnerServiceResponseType
                          where PartnerServiceID = 1);

I am new to this

Body:
We can first try as two queries:

var psrt = tblPartnerServiceResponseType.FirstOrDefault(srt => srt.PartnerServiceID == 1);
if (psrt != null)
{
    var rt = tblResponseType.FirstOrDefault(rt => rt.ReponseTypeID == psrt.ReponseTypeID);
}

This will work, but requires two round-trip to the dataserver.

Ok, next, let's assume that you've got you foreign keys set up right, so that tblPartnerServiceResponseType has a tblResponseType property in it:

var query = from t2 in tblPartnerServiceResponseType
            where t2.PartnerServiceID == 1
            select new {Desc1 = t2.tblResponseType.description,
                        Desc2 = t2.Description,
                        t2.ReponseTypeID
                        };

Finally, if you DON'T have the foreign key set up (which you really SHOULD!), then we have to do the explicit join:

var query = from t2 in tblPartnerServiceResponseType
            join t1 in tblResponseType on t2.ReponseTypeID equals  t1.ReponseTypeID
        where t2.PartnerServiceID == 1
        select new {Desc1 = t1.Description,
                    Desc2 = t2.Description,
                    t2.ReponseTypeID
                    };


问:
Angular 4: "Cannot find name 'require'
I am building an app with Angular 4 and webpack.

I have the following in one of my components:

```<code>ngOnInit() {
    require('/assets/js/regular-expresions.js');
}
</code>```

When I attempt to compile, I get:

ERROR in
  C:/SRC/Sandbox/eat-sleep-code.com/src/app/content.component.ts (21,9):
  Cannot find name 'require'.

I have ran npm install @types/node --save-dev and updated my tsconfig.json to look like:

```<code>{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "baseUrl": "src",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "types": [
      "node"
    ],
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2016",
      "dom"
    ]
  }
}
</code>```

But alas, the same error keeps getting thrown.  Any ideas?

Here is my package.json:

```<code>{
  "name": "eat-sleep-code.com",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^4.0.1",
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^4.0.0",
    "@angular/core": "^4.0.0",
    "@angular/forms": "^4.0.0",
    "@angular/http": "^4.0.0",
    "@angular/material": "^2.0.0-beta.3",
    "@angular/platform-browser": "^4.0.0",
    "@angular/platform-browser-dynamic": "^4.0.0",
    "@angular/router": "^4.0.0",
    "@types/node": "^6.0.69",
    "angularfire2": "^2.0.0-beta.8",
    "core-js": "^2.4.1",
    "firebase": "^3.7.8",
    "jquery": "^3.2.1",
    "jquery-validation": "^1.16.0",
    "ng2-gist": "^1.0.0",
    "promise-polyfill": "^6.0.2",
    "requirejs": "^2.3.3",
    "rxjs": "^5.1.0",
    "typescript": "^2.2.2",
    "web-animations-js": "^2.2.4",
    "webpack": "^2.4.1",
    "zone.js": "^0.8.4"
  },
  "devDependencies": {
    "@angular/cli": "1.0.0",
    "@angular/compiler-cli": "^4.0.0",
    "@types/jasmine": "2.5.38",
    "@types/node": "^6.0.69",
    "codelyzer": "~2.0.0",
    "jasmine-core": "~2.5.2",
    "jasmine-spec-reporter": "~3.2.0",
    "karma": "~1.4.1",
    "karma-chrome-launcher": "~2.0.0",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^0.2.0",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.0",
    "ts-node": "~2.0.0",
    "tslint": "~4.5.0",
    "typescript": "^2.2.2",
    "webpack": "^2.4.1"
  }
}
</code>```

答:
try

```<code>compilerOptions: {
   ...
   "typeRoots": [ "../node_modules/@types" ],
   ...
}
</code>```

in tsconfig.json

Title: Angular 4: "Cannot find name 'require'

Body:
I am building an app with Angular 4 and webpack.

I have the following in one of my components:

ngOnInit() {
    require('/assets/js/regular-expresions.js');
}

When I attempt to compile, I get:

ERROR in
  C:/SRC/Sandbox/eat-sleep-code.com/src/app/content.component.ts (21,9):
  Cannot find name 'require'.

I have ran npm install @types/node --save-dev and updated my tsconfig.json to look like:

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "baseUrl": "src",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "types": [
      "node"
    ],
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2016",
      "dom"
    ]
  }
}

But alas, the same error keeps getting thrown.  Any ideas?

Here is my package.json:

{
  "name": "eat-sleep-code.com",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^4.0.1",
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^4.0.0",
    "@angular/core": "^4.0.0",
    "@angular/forms": "^4.0.0",
    "@angular/http": "^4.0.0",
    "@angular/material": "^2.0.0-beta.3",
    "@angular/platform-browser": "^4.0.0",
    "@angular/platform-browser-dynamic": "^4.0.0",
    "@angular/router": "^4.0.0",
    "@types/node": "^6.0.69",
    "angularfire2": "^2.0.0-beta.8",
    "core-js": "^2.4.1",
    "firebase": "^3.7.8",
    "jquery": "^3.2.1",
    "jquery-validation": "^1.16.0",
    "ng2-gist": "^1.0.0",
    "promise-polyfill": "^6.0.2",
    "requirejs": "^2.3.3",
    "rxjs": "^5.1.0",
    "typescript": "^2.2.2",
    "web-animations-js": "^2.2.4",
    "webpack": "^2.4.1",
    "zone.js": "^0.8.4"
  },
  "devDependencies": {
    "@angular/cli": "1.0.0",
    "@angular/compiler-cli": "^4.0.0",
    "@types/jasmine": "2.5.38",
    "@types/node": "^6.0.69",
    "codelyzer": "~2.0.0",
    "jasmine-core": "~2.5.2",
    "jasmine-spec-reporter": "~3.2.0",
    "karma": "~1.4.1",
    "karma-chrome-launcher": "~2.0.0",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^0.2.0",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.0",
    "ts-node": "~2.0.0",
    "tslint": "~4.5.0",
    "typescript": "^2.2.2",
    "webpack": "^2.4.1"
  }
}

Body:
try

compilerOptions: {
   ...
   "typeRoots": [ "../node_modules/@types" ],
   ...
}

in tsconfig.json


问:
Shopping Cart Dictionary and Session Variable - Moving from Code-Behind to Class
I am building a shopping cart using ASP.NET (C#). I have the cart working in the code behind, but I have to implement it across several product pages, so I would like to move it to a class for maintainability, but I'm having trouble.

I am using a Dictionary to store the product ID and quantity desired, then I store that Dictionary into a Session variable to store the cart between postbacks and navigating the site. The Dictionary is a global variable in multiple pages' code-behind.

```<code>public partial class products : System.Web.UI.Page
{
    Dictionary<int, int> CartList;
</code>```

On Page_Load, I am checking if the Session variable has a value:

```<code>protected void Page_Load(object sender, EventArgs e)
{
    if (Session["CartList"] == null)
    {
        CartList = new Dictionary<int, int>();
        Session["CartList"] = CartList;
    }
}
</code>```

When an Add to Cart button is clicked I have the following event handler. The button passes the product ID to the event handler in an attribute that was assigned to it when it was dynamically created. Then we loop through the dictionary to see if that product is already in the cart, and if so, we update the quantity by 1, then store the updated dictonary into the session variable:

```<code>protected void btnAddProduct_Click(object sender, EventArgs e)
{
    Button btn = (Button)sender;

    int pId = Convert.ToInt32(btn.Attributes["data-id"]);

    CartList = (Dictionary<int, int>)Session["CartList"];

    int count = 1;

    if (pId  > 0)
    {
        if (CartList.Count > 0)
        {
            foreach (KeyValuePair<int, int> item in CartList)
            {
                if (item.Key == pId)
                {
                    count = item.Value + 1;
                }
            }
        }

        if (count > 1)
        {
            CartList[pId] = count;
        }
        else
        {
            CartList.Add(pId, count);
        }
    }

    Session["CartList"] = CartList;
}
</code>```

On the Cart Display page, I have a global CartList Dictonary again:

```<code>public partial class cart : System.Web.UI.Page
{

   Dictionary<int, int> CartList;
</code>```

On Page_PreInit, I am checking if my session variable has a value, and if so, we display the cart:

```<code>protected void Page_PreInit(object sender, EventArgs e)
{

    if (Session["CartList"] != null)
    {
        CartList = (Dictionary<int, int>)Session["CartList"];
        DisplayCartList();

    }
    else
    {
        lbl = new Label();
        lbl.Text = "<h1>There are no items in your cart.</h1>";
        Master.FindControl("ContentPlaceHolder1").Controls.Add(lbl);
    }
 }
</code>```

I've read that a session variable might not be the best approach for this, so any ideas in that regard are appreciated. I understand that using Cache may be better, but I'm not very familiar with it yet. Either way, I would like to have the Dictionary and Session or Cache variable inside a class that is accessible across the website.

I have read about using a Session Wrapper class such as this example: How to access session variables from any class in ASP.NET? to hold the session, but I can't seem to get my head wrapped around that idea.

答:
Session variables are very useful tools, but they have their drawbacks, so should be used judiciously.

The drawbacks mainly are:

Takes up memory on the server. If one has many sessions vars and they store large data structures this can be costly especially if you have memory restriction and your target audience is large.
(* This is less true in in ASP.net than in Classic ASP)

Session variables can be modified from anywhere in the application so one has to keep track of the value at all times.

*The latter could actually be more tricky then it sounds, especially when you have a large and complex App like a Shopping-Cart.

For example: if you are displaying the shopping cart content in a control on your page on which you are modifying the contents of the shopping cart. If you are adding an item and posting back the control may load with  (old) session values as the add to list function will occur after the control is built .

Hope this is helpful.

Body:
I am building a shopping cart using ASP.NET (C#). I have the cart working in the code behind, but I have to implement it across several product pages, so I would like to move it to a class for maintainability, but I'm having trouble.

I am using a Dictionary to store the product ID and quantity desired, then I store that Dictionary into a Session variable to store the cart between postbacks and navigating the site. The Dictionary is a global variable in multiple pages' code-behind.

public partial class products : System.Web.UI.Page
{
    Dictionary<int, int> CartList;

On Page_Load, I am checking if the Session variable has a value:

protected void Page_Load(object sender, EventArgs e)
{
    if (Session["CartList"] == null)
    {
        CartList = new Dictionary<int, int>();
        Session["CartList"] = CartList;
    }
}

When an Add to Cart button is clicked I have the following event handler. The button passes the product ID to the event handler in an attribute that was assigned to it when it was dynamically created. Then we loop through the dictionary to see if that product is already in the cart, and if so, we update the quantity by 1, then store the updated dictonary into the session variable:

protected void btnAddProduct_Click(object sender, EventArgs e)
{
    Button btn = (Button)sender;

    int pId = Convert.ToInt32(btn.Attributes["data-id"]);

    CartList = (Dictionary<int, int>)Session["CartList"];

    int count = 1;

    if (pId  > 0)
    {
        if (CartList.Count > 0)
        {
            foreach (KeyValuePair<int, int> item in CartList)
            {
                if (item.Key == pId)
                {
                    count = item.Value + 1;
                }
            }
        }

        if (count > 1)
        {
            CartList[pId] = count;
        }
        else
        {
            CartList.Add(pId, count);
        }
    }

    Session["CartList"] = CartList;
}

On the Cart Display page, I have a global CartList Dictonary again:

public partial class cart : System.Web.UI.Page
{

   Dictionary<int, int> CartList;

On Page_PreInit, I am checking if my session variable has a value, and if so, we display the cart:

protected void Page_PreInit(object sender, EventArgs e)
{

    if (Session["CartList"] != null)
    {
        CartList = (Dictionary<int, int>)Session["CartList"];
        DisplayCartList();

    }
    else
    {
        lbl = new Label();
        lbl.Text = "
There are no items in your cart.
";
        Master.FindControl("ContentPlaceHolder1").Controls.Add(lbl);
    }
 }

I've read that a session variable might not be the best approach for this, so any ideas in that regard are appreciated. I understand that using Cache may be better, but I'm not very familiar with it yet. Either way, I would like to have the Dictionary and Session or Cache variable inside a class that is accessible across the website.

I have read about using a Session Wrapper class such as this example: How to access session variables from any class in ASP.NET? to hold the session, but I can't seem to get my head wrapped around that idea.


问:
Django: asynchronously load data when page is requested?
I am new to Django and have completed the 7 part tutorial and am now trying to learn more by making my own app.

Suppose you are making an interactive data visualization application where the front end is powered by d3 (or your favorite JS library) and your data is coming from the server. Since your data is large, you first have to load it into server memory (maybe from a binary file, or however you store it). Yet you don't want your user to be looking at a blank page when they could be seeing the rest of the site (maybe filling in some parameters for the interactive data).

How can you, when a user requests a web-page, load and maintain data in memory on the server while Django still renders the page as well as maybe sends POST requests to update some server side information?

答:
Django doesn't have any asynchronous method to deal with what you're asking. The platform is request-based so there's no way to send the information later using the same request.

The solution in this case is using two views (or a view that can handle multiple formats, like @SumNeuron mentioned):

The first view loads the page where you'll be loading the data later. On that page, an XMLHttpRequest is done to request the data.

This view only sends the data, it can be just the data in JSON or it can be partial HTML made from a template.


问:
Using configmap for ports
Is it possible to use configMap values for port values like containerPort or targetPort?

Here's the possible example how it could work:

```<code>apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: auth
spec:
  template:
    metadata:
        labels:
          app: auth
    spec:
      containers:
        - name: auth
          image: {{someImage}}
          ports:
            - name: CONTAINER_PORT
              containerPort:
                valueFrom:
                  configMapKeyRef:
                    name: auth-config
                    key: PORT
          env:
            - name: PORT
              valueFrom:
                configMapKeyRef:
                  name: auth-config
                  key: PORT
</code>```

答:
No, it is not possible for the ports section.

You can use env keys in container's commands and args. Find more here: https://github.com/kubernetes/community/blob/master/contributors/design-proposals/expansion.md

Usually most docker images have static port numbers encoded in the image with EXPOSE keyword, so having a dynamically configurable port is not a best practice from configuration standpoint. Try sticking to fixed port numbers as you can always remap them while exposing the port on Service.

Title: Using configmap for ports

Body:
Is it possible to use configMap values for port values like containerPort or targetPort?

Here's the possible example how it could work:

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: auth
spec:
  template:
    metadata:
        labels:
          app: auth
    spec:
      containers:
        - name: auth
          image: {{someImage}}
          ports:
            - name: CONTAINER_PORT
              containerPort:
                valueFrom:
                  configMapKeyRef:
                    name: auth-config
                    key: PORT
          env:
            - name: PORT
              valueFrom:
                configMapKeyRef:
                  name: auth-config
                  key: PORT


问:
what creates the default ObjectID in mongodb?
Quite new to MongoDB. Going through the documentation.

From https://docs.mongodb.com/manual/reference/method/db.collection.insert/#id-field

If the document does not specify an _id field, then MongoDB will add the _id field and assign a unique ObjectId for the document before inserting. Most drivers create an ObjectId and insert the _id field, but the mongod will create and populate the _id if the driver or application does not.

Here it says MongoDB will create the _id.

From https://docs.mongodb.com/manual/reference/method/db.collection.save/?_ga=2.24854906.1181826191.1496665143-146886871.1493019056#save-a-new-document-without-specifying-an-id-field

During the insert, the shell will create the _id field with a unique ObjectId value, as verified by the inserted document.

And here, it says Mongo shell.

Is it the mongo shell that creates the default ObjectID or mongod? Hope someone can clarify!

答: If the client didn't create Id for the document, mongo server will create the _id when it creates a new document.</p>


问:
Django - Accessing sublist of list in for loop
I have a query that outputs data in the following format:

```<code>[["W/E 6/11/17", "Carter, J", 40.0],
 ["W/E 6/18/17", "Carter, J", 40.0],
 ["W/E 6/11/17", "Linn, K", 27.0],
 ["W/E 6/18/17", "Linn, K", 27.0],
 ["W/E 6/11/17", "Massey, S", 55.0],
 ["W/E 6/18/17", "Massey, S", 45.0]]
</code>```

My query:

```<code>emp3 = (
    Projectsummaryplannedhours.objects.values(
        'employeename', 'displayval')
    .order_by()
    .filter(businessunit='a')
    .filter(billinggroup__startswith='PLS - Pip')
    .filter(Q(displayval=sunday2)|Q(displayval=sunday))
    .annotate(plannedhours__sum=Sum('plannedhours'))
)
</code>```

In my template, I'm currently using a for loop, but it returns all items in the list, rather than just the first list of lists.

```<code>{% for x in emp3 %}
{{x.employeename}}
{{x.plannedhours__sum}}
</code>```

What I would like to do is iterate through the list and display Employee: Value for W/E 6/11, Value for W/E 6/18 in a horizontal form.

Model:

```<code>class Projectsummaryplannedhours(models.Model):
    number = models.CharField(db_column='Number', max_length=50, blank=True, null=True)  # Field name made lowercase.
    description = models.CharField(db_column='Description', max_length=100, blank=True, null=True)  # Field name made lowercase.
    clientname = models.CharField(db_column='ClientName', max_length=100, blank=True, null=True)  # Field name made lowercase.
    department = models.CharField(db_column='Department', max_length=50, blank=True, null=True)  # Field name made lowercase.
    billinggroup = models.CharField(db_column='BillingGroup', max_length=50, blank=True, null=True)  # Field name made lowercase.
    businessunit = models.CharField(db_column='BusinessUnit', max_length=50, blank=True, null=True)  # Field name made lowercase.
    employeename = models.CharField(db_column='EmployeeName', max_length=50, blank=True, null=True)  # Field name made lowercase.
    displayval = models.CharField(db_column='DisplayVal', max_length=50, blank=True, null=True)  # Field name made lowercase.
    startofweek = models.DateTimeField(db_column='StartOfWeek', blank=True, null=True)  # Field name made lowercase.
    endofweek = models.DateTimeField(db_column='EndOfWeek', blank=True, null=True)  # Field name made lowercase.
    plannedhours = models.DecimalField(db_column='PlannedHours', max_digits=10, decimal_places=5, blank=True, null=True)  # Field name made lowercase.
    rateschedule = models.CharField(db_column='RateSchedule', max_length=50, blank=True, null=True)  # Field name made lowercase.
    classification = models.CharField(db_column='Classification', max_length=50, blank=True, null=True)  # Field name made lowercase.
    dollarsforecast = models.DecimalField(db_column='DollarsForecast', max_digits=10, decimal_places=5, blank=True, null=True)  # Field name made lowercase.
    deleted = models.NullBooleanField(db_column='Deleted')  # Field name made lowercase.
    datelastmodified = models.DateTimeField(db_column='DateLastModified', blank=True, null=True)  # Field name made lowercase.
    datecreated = models.DateTimeField(db_column='DateCreated', blank=True, null=True)  # Field name made lowercase.
</code>```

Updated Query:

```<code>emp3_list = Projectsummaryplannedhours.objects.values('employeename', 'displayval').order_by().filter(businessunit='a').filter(billinggroup__startswith='PLS - Pip').filter(Q(displayval=sunday2)|Q(displayval=sunday)).annotate(plannedhours__sum=Sum('plannedhours'))
emp3 = map(lambda x: {'date': x[0], 'employee_name': x[1], 'planned_hours': x[2]}, emp3_list)
</code>```

Every query I have tried:

```<code>def DesignHubR(request):
#emp1 = Projectsummaryplannedhours.objects.filter(employeename__startswith='Linn').values_list('endofweek').annotate(plannedhours__sum=Sum('plannedhours'))

day = datetime.datetime.today()
start = day - timedelta(days=day.weekday())
s1 = start + timedelta(days=6)
day2 = day + + timedelta(days=7)
start2 = day2 - timedelta(days=day.weekday())
s2 = start2 + timedelta(days=6)
sunday = datetime.datetime.strftime(s1, "W/E %#m/%#d/%y")
sunday2 = datetime.datetime.strftime(s2, "W/E %#m/%#d/%y")
employee = Projectsummaryplannedhours.objects.order_by().values_list('employeename', flat=True).distinct().filter(businessunit='a').filter(billinggroup__startswith='PLS - Pip')
emp1 = Projectsummaryplannedhours.objects.values_list('displayval', 'employeename').filter(businessunit='a').filter(billinggroup__startswith='PLS - Pip').filter(displayval=sunday).annotate(plannedhours__sum=Sum('plannedhours'))
emp4 = Projectsummaryplannedhours.objects.filter(employeename__startswith='Linn').filter(Q(displayval=sunday2)|Q(displayval=sunday)).annotate(plannedhours__sum=Sum('plannedhours'))
emp2 = Projectsummaryplannedhours.objects.values_list('displayval', 'employeename').filter(businessunit='a').filter(billinggroup__startswith='PLS - Pip').filter(Q(displayval=sunday2)|Q(displayval=sunday)).annotate(plannedhours__sum=Sum('plannedhours'))
emp3_list = Projectsummaryplannedhours.objects.values_list('displayval', 'employeename').filter(businessunit='a').filter(billinggroup__startswith='PLS - Pip').filter(Q(displayval=sunday2)|Q(displayval=sunday)).annotate(plannedhours__sum=Sum('plannedhours'))
emp3 = map(lambda x: {'date': x[0], 'employee_name': x[1], 'planned_hours': x[2]}, emp3_list)
context = {'emp1': emp1, 'emp2': emp2, 'sunday2': sunday2, 'employee': employee, 'emp3': emp3, 'emp4': emp4}
return render(request,'department_hub_ple.html', context)
</code>```

答:
You can use list indexes in the following way:

```<code>{{ x.0 }}
</code>```

So your template might look like (without any markup or styling):

```<code>{% for x in emp3 %}
  {{ x.1 }}
  {{ x.2 }}
{% endfor %}
</code>```

See Docs on Variables and Lookups

EDIT

If you're looking for a way to use only the list in your list-of-lists, you can chain lookups. The following example would give the second element of the first list.

```<code>{{ x.0.1 }}
</code>```

This probably makes your template harder to read, since it's not very clear what x.0.1 refers to in your context. You might consider changing the data structure of the results, and limiting the data your view returns to just the data your template is going to use.

EDIT 2

To make your template more readable, use a map function convert your list-of-lists back to a list-of-dicts:

```<code>emp3_list = [
    ["W/E 6/11/17", "Carter, Jon", 40.0],
    ["W/E 6/18/17", "Carter, Jon", 40.0],
    ["W/E 6/11/17", "Linn, Kenneth", 27.0],
    ["W/E 6/18/17", "Linn, Kenneth", 27.0],
    ["W/E 6/11/17", "Massey, Smiley", 55.0],
    ["W/E 6/18/17", "Massey, Smiley", 45.0]
]
emp3 = map(lambda x: {'date': x[0], 'employee_name': x[1], 'planned_hours': x[2]}, emp3_list)
</code>```

Your template would then look like this:

```<code>{% for x in emp3 %}
    Employee: {{ x.employee_name }}
    Date: {{ x.date }}
    Planned Hours: {{ x.planned_hours }}
{% endfor %}
</code>```

Body:
I have a query that outputs data in the following format:

[["W/E 6/11/17", "Carter, J", 40.0],
 ["W/E 6/18/17", "Carter, J", 40.0],
 ["W/E 6/11/17", "Linn, K", 27.0],
 ["W/E 6/18/17", "Linn, K", 27.0],
 ["W/E 6/11/17", "Massey, S", 55.0],
 ["W/E 6/18/17", "Massey, S", 45.0]]

My query:

emp3 = (
    Projectsummaryplannedhours.objects.values(
        'employeename', 'displayval')
    .order_by()
    .filter(businessunit='a')
    .filter(billinggroup__startswith='PLS - Pip')
    .filter(Q(displayval=sunday2)|Q(displayval=sunday))
    .annotate(plannedhours__sum=Sum('plannedhours'))
)

In my template, I'm currently using a for loop, but it returns all items in the list, rather than just the first list of lists.

{% for x in emp3 %}
{{x.employeename}}
{{x.plannedhours__sum}}

What I would like to do is iterate through the list and display Employee: Value for W/E 6/11, Value for W/E 6/18 in a horizontal form.

Model:

class Projectsummaryplannedhours(models.Model):
    number = models.CharField(db_column='Number', max_length=50, blank=True, null=True)  # Field name made lowercase.
    description = models.CharField(db_column='Description', max_length=100, blank=True, null=True)  # Field name made lowercase.
    clientname = models.CharField(db_column='ClientName', max_length=100, blank=True, null=True)  # Field name made lowercase.
    department = models.CharField(db_column='Department', max_length=50, blank=True, null=True)  # Field name made lowercase.
    billinggroup = models.CharField(db_column='BillingGroup', max_length=50, blank=True, null=True)  # Field name made lowercase.
    businessunit = models.CharField(db_column='BusinessUnit', max_length=50, blank=True, null=True)  # Field name made lowercase.
    employeename = models.CharField(db_column='EmployeeName', max_length=50, blank=True, null=True)  # Field name made lowercase.
    displayval = models.CharField(db_column='DisplayVal', max_length=50, blank=True, null=True)  # Field name made lowercase.
    startofweek = models.DateTimeField(db_column='StartOfWeek', blank=True, null=True)  # Field name made lowercase.
    endofweek = models.DateTimeField(db_column='EndOfWeek', blank=True, null=True)  # Field name made lowercase.
    plannedhours = models.DecimalField(db_column='PlannedHours', max_digits=10, decimal_places=5, blank=True, null=True)  # Field name made lowercase.
    rateschedule = models.CharField(db_column='RateSchedule', max_length=50, blank=True, null=True)  # Field name made lowercase.
    classification = models.CharField(db_column='Classification', max_length=50, blank=True, null=True)  # Field name made lowercase.
    dollarsforecast = models.DecimalField(db_column='DollarsForecast', max_digits=10, decimal_places=5, blank=True, null=True)  # Field name made lowercase.
    deleted = models.NullBooleanField(db_column='Deleted')  # Field name made lowercase.
    datelastmodified = models.DateTimeField(db_column='DateLastModified', blank=True, null=True)  # Field name made lowercase.
    datecreated = models.DateTimeField(db_column='DateCreated', blank=True, null=True)  # Field name made lowercase.

Updated Query:

emp3_list = Projectsummaryplannedhours.objects.values('employeename', 'displayval').order_by().filter(businessunit='a').filter(billinggroup__startswith='PLS - Pip').filter(Q(displayval=sunday2)|Q(displayval=sunday)).annotate(plannedhours__sum=Sum('plannedhours'))
emp3 = map(lambda x: {'date': x[0], 'employee_name': x[1], 'planned_hours': x[2]}, emp3_list)

Every query I have tried:

def DesignHubR(request):
#emp1 = Projectsummaryplannedhours.objects.filter(employeename__startswith='Linn').values_list('endofweek').annotate(plannedhours__sum=Sum('plannedhours'))

day = datetime.datetime.today()
start = day - timedelta(days=day.weekday())
s1 = start + timedelta(days=6)
day2 = day + + timedelta(days=7)
start2 = day2 - timedelta(days=day.weekday())
s2 = start2 + timedelta(days=6)
sunday = datetime.datetime.strftime(s1, "W/E %#m/%#d/%y")
sunday2 = datetime.datetime.strftime(s2, "W/E %#m/%#d/%y")
employee = Projectsummaryplannedhours.objects.order_by().values_list('employeename', flat=True).distinct().filter(businessunit='a').filter(billinggroup__startswith='PLS - Pip')
emp1 = Projectsummaryplannedhours.objects.values_list('displayval', 'employeename').filter(businessunit='a').filter(billinggroup__startswith='PLS - Pip').filter(displayval=sunday).annotate(plannedhours__sum=Sum('plannedhours'))
emp4 = Projectsummaryplannedhours.objects.filter(employeename__startswith='Linn').filter(Q(displayval=sunday2)|Q(displayval=sunday)).annotate(plannedhours__sum=Sum('plannedhours'))
emp2 = Projectsummaryplannedhours.objects.values_list('displayval', 'employeename').filter(businessunit='a').filter(billinggroup__startswith='PLS - Pip').filter(Q(displayval=sunday2)|Q(displayval=sunday)).annotate(plannedhours__sum=Sum('plannedhours'))
emp3_list = Projectsummaryplannedhours.objects.values_list('displayval', 'employeename').filter(businessunit='a').filter(billinggroup__startswith='PLS - Pip').filter(Q(displayval=sunday2)|Q(displayval=sunday)).annotate(plannedhours__sum=Sum('plannedhours'))
emp3 = map(lambda x: {'date': x[0], 'employee_name': x[1], 'planned_hours': x[2]}, emp3_list)
context = {'emp1': emp1, 'emp2': emp2, 'sunday2': sunday2, 'employee': employee, 'emp3': emp3, 'emp4': emp4}
return render(request,'department_hub_ple.html', context)

Body:
You can use list indexes in the following way:

{{ x.0 }}

So your template might look like (without any markup or styling):

{% for x in emp3 %}
  {{ x.1 }}
  {{ x.2 }}
{% endfor %}

See Docs on Variables and Lookups

EDIT

If you're looking for a way to use only the list in your list-of-lists, you can chain lookups. The following example would give the second element of the first list.

{{ x.0.1 }}

This probably makes your template harder to read, since it's not very clear what x.0.1 refers to in your context. You might consider changing the data structure of the results, and limiting the data your view returns to just the data your template is going to use.

EDIT 2

To make your template more readable, use a map function convert your list-of-lists back to a list-of-dicts:

emp3_list = [
    ["W/E 6/11/17", "Carter, Jon", 40.0],
    ["W/E 6/18/17", "Carter, Jon", 40.0],
    ["W/E 6/11/17", "Linn, Kenneth", 27.0],
    ["W/E 6/18/17", "Linn, Kenneth", 27.0],
    ["W/E 6/11/17", "Massey, Smiley", 55.0],
    ["W/E 6/18/17", "Massey, Smiley", 45.0]
]
emp3 = map(lambda x: {'date': x[0], 'employee_name': x[1], 'planned_hours': x[2]}, emp3_list)

Your template would then look like this:

{% for x in emp3 %}
    Employee: {{ x.employee_name }}
    Date: {{ x.date }}
    Planned Hours: {{ x.planned_hours }}
{% endfor %}


问:
C++ 'wrapper class' for XML library
So I've been attempting to create some classes around the xerces XML library so I can 'hide' it from the rest of my project the underlying xml library stays independent from the rest of my project.

This was supposed to be a fairly easy task, however it seems entirely impossible to hide a library from the rest of a project by writing some classes around it.

Have I got the wrong approach or is my 'wrapper' idea completely silly?

I end up with something like this:

```<code>DOMElement* root();  //in my 'wrapper' class, however this DOMElement is part of the xerces library, at this point my 'wrapper' is broken.  Now I have to use the xerces library everywhere I want to use this function.
</code>```

Where is my thinking gone wrong?

答:
As I mentioned in my comments, I would take a slightly different approach. I would not want my codebase to be dependent on the particular messaging format (xml) that I am using (what if for example you decide to change the xml to something else later?) Instead I would work with a well defined object model and have a simple encoder/decoder to handle the conversion to XML string and vice versa. This encode/decoder would then be the bit that I would replace if the underlying wire format changed.

The decoder would take in the data read from the socket, and produce a suitable object (with nested objects to represent the request) and the decoder would take a similar object and generate the XML from it. If performance is not a primary concern, I would use a library such as TinyXML which is quite lightweight - heck, you can strip that down even further and make it more light weight...

ContentLicense: CC BY-SA 2.5

Title: C++ 'wrapper class' for XML library

Body:
So I've been attempting to create some classes around the xerces XML library so I can 'hide' it from the rest of my project the underlying xml library stays independent from the rest of my project.

This was supposed to be a fairly easy task, however it seems entirely impossible to hide a library from the rest of a project by writing some classes around it.

Have I got the wrong approach or is my 'wrapper' idea completely silly?

I end up with something like this:

DOMElement* root();  //in my 'wrapper' class, however this DOMElement is part of the xerces library, at this point my 'wrapper' is broken.  Now I have to use the xerces library everywhere I want to use this function.

Where is my thinking gone wrong?


问:
Can Hubot send an HTML or other type of formatted message to Hipchat?
Looking at the Hubot documentation there seems to be no way to send a formatted message to the Hipchat client from a Hubot script.

Does anyone know of a way to better present lines of text sent from Hubot?

Version 1 of the Hipchat API (albeit deprecated) suggests that a message_format parameter can be used to specify an HTML message.

Many thanks.

答: It is possible, according to this article</p>


问:
How to change Prestashop 1.7 table prefix?
I tried to change define('_DB_PREFIX_', 'ps_'); in /config/settings.inc.php, but my settings.inc.php file is empty.

I tried set that define, is working, but where is saved my first configuration?

How can I change table prefix in Prestashop 1.7?

答:
The new version of PrestaShop is migrating to the symfony framework. The configuration file that you should to change is located in:

rootofps/app/config/parameters.php

Hope it helps :)


问:
Caliburn Micro - Using IResult and rendering views
I am just getting started with Caliburn Micro and trying to wrap my head around IResult. To do so, I have written some dummy code. The code is meant to display "Loading..." in a text box until some lengthy operation (Task.Delay) completes, at which point the text should disappear. Here is my code:

ViewModel:

```<code>[Export(typeof(IShell))]
public class ShellViewModel : IShell
{
    public string MyMessage { get; set; }

    public IEnumerable<IResult> DoSomething()
    {
        yield return Loader.Show("Loading...");
        yield return Task.Delay(1000).AsResult();
        yield return Loader.Hide();
    }
}
</code>```

View:

```<code><Window x:Class="CaliburnMicroTest.ShellView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:CaliburnMicroTest"
        xmlns:cal="http://www.caliburnproject.org"
        mc:Ignorable="d"
        Title="ShellView" Height="300" Width="300">
    <StackPanel>
        <Button Content="Do Something"
                x:Name="DoSomething" />
        <TextBox Text="{Binding Path=MyMessage, Mode=TwoWay}"/>
    </StackPanel>
</Window>
</code>```

Loader class:

```<code>public class Loader : IResult
{
    readonly string message;
    readonly bool hide;

    public Loader(string message)
    {
        this.message = message;
    }

    public Loader(bool hide)
    {
        this.hide = hide;
    }

    public event EventHandler<ResultCompletionEventArgs> Completed;

    public void Execute(CoroutineExecutionContext context)
    {
        var target = context.Target as ShellViewModel;

        target.MyMessage = hide ? string.Empty : message;

        Completed(this, new ResultCompletionEventArgs());
    }

    public static IResult Show(string message = null)
    {
        return new Loader(message);
    }

    public static IResult Hide()
    {
        return new Loader(true);
    }
}
</code>```

When I click the button, I expect the textbox to be populated with "Loading..." for one second and then become empty again, but nothing ever shows up in the textbox. Additionally, when I debug, the MyMessage property on my ViewModel has a value of "Loading...". Why would the text not show up on my view?

答:
Your view model class should inherit from PropertyChangedBase and raise change notifications:

```<code>[Export(typeof(IShell))]
public class ShellViewModel : IShell, PropertyChangedBase
{
    string _myMessage;
    public string MyMessage
    {
        get { return _myMessage; }
        set
        {
            _myMessage = value;
            NotifyOfPropertyChange(() => MyMessage);
        }
    }

    public IEnumerable<IResult> DoSomething()
    {
        yield return Loader.Show("Loading...");
        yield return Task.Delay(1000).AsResult();
        yield return Loader.Hide();
    }
}
</code>```

Body:
I am just getting started with Caliburn Micro and trying to wrap my head around IResult. To do so, I have written some dummy code. The code is meant to display "Loading..." in a text box until some lengthy operation (Task.Delay) completes, at which point the text should disappear. Here is my code:

ViewModel:

[Export(typeof(IShell))]
public class ShellViewModel : IShell
{
    public string MyMessage { get; set; }

    public IEnumerable<IResult> DoSomething()
    {
        yield return Loader.Show("Loading...");
        yield return Task.Delay(1000).AsResult();
        yield return Loader.Hide();
    }
}

View:

<Window x:Class="CaliburnMicroTest.ShellView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:CaliburnMicroTest"
        xmlns:cal="http://www.caliburnproject.org"
        mc:Ignorable="d"
        Title="ShellView" Height="300" Width="300">
    <StackPanel>
        <Button Content="Do Something"
                x:Name="DoSomething" />
        <TextBox Text="{Binding Path=MyMessage, Mode=TwoWay}"/>
    </StackPanel>
</Window>

Loader class:

public class Loader : IResult
{
    readonly string message;
    readonly bool hide;

    public Loader(string message)
    {
        this.message = message;
    }

    public Loader(bool hide)
    {
        this.hide = hide;
    }

    public event EventHandler<ResultCompletionEventArgs> Completed;

    public void Execute(CoroutineExecutionContext context)
    {
        var target = context.Target as ShellViewModel;

        target.MyMessage = hide ? string.Empty : message;

        Completed(this, new ResultCompletionEventArgs());
    }

    public static IResult Show(string message = null)
    {
        return new Loader(message);
    }

    public static IResult Hide()
    {
        return new Loader(true);
    }
}

When I click the button, I expect the textbox to be populated with "Loading..." for one second and then become empty again, but nothing ever shows up in the textbox. Additionally, when I debug, the MyMessage property on my ViewModel has a value of "Loading...". Why would the text not show up on my view?

Body:
Your view model class should inherit from PropertyChangedBase and raise change notifications:

[Export(typeof(IShell))]
public class ShellViewModel : IShell, PropertyChangedBase
{
    string _myMessage;
    public string MyMessage
    {
        get { return _myMessage; }
        set
        {
            _myMessage = value;
            NotifyOfPropertyChange(() => MyMessage);
        }
    }

    public IEnumerable<IResult> DoSomething()
    {
        yield return Loader.Show("Loading...");
        yield return Task.Delay(1000).AsResult();
        yield return Loader.Hide();
    }
}


问:
Python/Psychopy: Instantiating multiple circle objects from a class
I've made a class that contains a circle (a Psychopy Circle object). I want to know how I can instantiate 2 circle objects using this class, each for example, with a different fill color.

```<code>class Circle(object):
    def __init__(self):
        self.circle = visual.Circle(win, units = 'deg', pos=(1,1),
        radius=1, lineColor="black", fillColor="red")

        self.components = [self.circle]

    def draw(self):
        [component.draw() for component in self.components]

circle=Circle() #red colour
circle2=Circle() #blue colour if possible
</code>```

Is there a way for me to instantiate circle2 whilst accessing some of the visual.circle parameters e.g. to change it's position or fill color? This is my first use of classes. Currently, If I draw 'circle' and 'cirle2' to the screen, one simply overlays the other, as one is merely a copy of the other.

Cheers,
Jon

答:
Based on your clarification in the comment, I assume you want something like this:

```<code>class Circle(psychopy.visual.circle.Circle):
    def __init__(self, win, lineColor='black', fillColor='red'):
        super(Circle, self).__init__(
            win=win, lineColor=lineColor, fillColor=fillColor, units='deg',
            pos=(1,1), radius=1)
</code>```

Circle would then default to units='deg', pos=(1,1), and radius=1. You could, however, specify different lineColors and fillColors for each instance. Since Circle inherits from the PsychoPy visual.Circle class, it has all its features. The call to super() actually initializes the parent class. See e.g. this post for more information on the super() function.

Let's put this to work.

```<code>#!/usr/bin/env python
# -*- coding: utf-8 -*-

from psychopy import core, visual, monitors
import psychopy.visual.circle

class Circle(psychopy.visual.circle.Circle):
    def __init__(self, win, lineColor='black', fillColor='red'):
        super(Circle, self).__init__(
            win=win, lineColor=lineColor, fillColor=fillColor, units='deg',
            pos=(1,1), radius=1)

def main():
    # Create a temporary monitor configuration.
    monitor = monitors.Monitor('test_display')
    monitor.setWidth(60)
    monitor.setDistance(80)
    monitor.setSizePix((1440, 900))

    win = visual.Window(monitor=monitor)

    colors = ('red', 'green', 'blue')
    circles = [Circle(win=win, fillColor=color) for color in colors]

    for circle in circles:
        circle.draw()
        win.flip()
        core.wait(1)

    core.quit()

if __name__ == '__main__':
    main()
</code>```

This code will create three Circles with different colors, and display them one after the other. I had to create a temporary monitor configuration or else PsychoPy would refuse to open a Window on my current computer.

Body:
I've made a class that contains a circle (a Psychopy Circle object). I want to know how I can instantiate 2 circle objects using this class, each for example, with a different fill color.

class Circle(object):
    def __init__(self):
        self.circle = visual.Circle(win, units = 'deg', pos=(1,1),
        radius=1, lineColor="black", fillColor="red")

        self.components = [self.circle]

    def draw(self):
        [component.draw() for component in self.components]

circle=Circle() #red colour
circle2=Circle() #blue colour if possible

Is there a way for me to instantiate circle2 whilst accessing some of the visual.circle parameters e.g. to change it's position or fill color? This is my first use of classes. Currently, If I draw 'circle' and 'cirle2' to the screen, one simply overlays the other, as one is merely a copy of the other.

Cheers,
Jon

Body:
Based on your clarification in the comment, I assume you want something like this:

class Circle(psychopy.visual.circle.Circle):
    def __init__(self, win, lineColor='black', fillColor='red'):
        super(Circle, self).__init__(
            win=win, lineColor=lineColor, fillColor=fillColor, units='deg',
            pos=(1,1), radius=1)

Circle would then default to units='deg', pos=(1,1), and radius=1. You could, however, specify different lineColors and fillColors for each instance. Since Circle inherits from the PsychoPy visual.Circle class, it has all its features. The call to super() actually initializes the parent class. See e.g. this post for more information on the super() function.

Let's put this to work.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from psychopy import core, visual, monitors
import psychopy.visual.circle

class Circle(psychopy.visual.circle.Circle):
    def __init__(self, win, lineColor='black', fillColor='red'):
        super(Circle, self).__init__(
            win=win, lineColor=lineColor, fillColor=fillColor, units='deg',
            pos=(1,1), radius=1)

def main():
    # Create a temporary monitor configuration.
    monitor = monitors.Monitor('test_display')
    monitor.setWidth(60)
    monitor.setDistance(80)
    monitor.setSizePix((1440, 900))

    win = visual.Window(monitor=monitor)

    colors = ('red', 'green', 'blue')
    circles = [Circle(win=win, fillColor=color) for color in colors]

    for circle in circles:
        circle.draw()
        win.flip()
        core.wait(1)

    core.quit()

if __name__ == '__main__':
    main()

This code will create three Circles with different colors, and display them one after the other. I had to create a temporary monitor configuration or else PsychoPy would refuse to open a Window on my current computer.


问:
Groovy enums - call chains
I am surprised to see that chaining calls to an enum works. I happened to have an enum instance called 'name' and that was referenced instead of the name() when I forgot the brackets. Should enum's allow chaining calls?
Using Groovy 2.4.10 - see the last 3 calls below:</p>

```<code>Groovy Shell (2.4.10, JVM: 1.8.0_121)
Type ':help' or ':h' for help.

groovy:000> public enum Compass { north, south }
===> true
groovy:000> Compass.north
===> north
groovy:000> Compass.north.name
ERROR groovy.lang.MissingPropertyException:
No such property: name for class: Compass
groovy:000> Compass.north.name()
===> north
groovy:000> public enum Compass { north, south, name }
===> true
groovy:000> Compass.north.name()
===> north
groovy:000> Compass.north.name
===> name
groovy:000> Compass.north.south
===> south
groovy:000> Compass.north.south.north
===> north
</code>```

答:
That is correct. Enums, in Java, are a syntactic sugar (plus useful stuff like values() and name()) over static fields in that same class, thus, when you call an enum field, you have also a static reference to that class, which also has access to the other class' fields:

```<code>class Compass {
    static NORTH = new Compass()
    static SOUTH = new Compass()
}

assert Compass.NORTH.SOUTH.NORTH == Compass.NORTH

def west = new Compass()
assert west.SOUTH == Compass.SOUTH
</code>```

Title: Groovy enums - call chains

Body:
I am surprised to see that chaining calls to an enum works. I happened to have an enum instance called 'name' and that was referenced instead of the name() when I forgot the brackets. Should enum's allow chaining calls?
Using Groovy 2.4.10 - see the last 3 calls below:

Groovy Shell (2.4.10, JVM: 1.8.0_121)
Type ':help' or ':h' for help.

groovy:000> public enum Compass { north, south }
===> true
groovy:000> Compass.north
===> north
groovy:000> Compass.north.name
ERROR groovy.lang.MissingPropertyException:
No such property: name for class: Compass
groovy:000> Compass.north.name()
===> north
groovy:000> public enum Compass { north, south, name }
===> true
groovy:000> Compass.north.name()
===> north
groovy:000> Compass.north.name
===> name
groovy:000> Compass.north.south
===> south
groovy:000> Compass.north.south.north
===> north

Body:
That is correct. Enums, in Java, are a syntactic sugar (plus useful stuff like values() and name()) over static fields in that same class, thus, when you call an enum field, you have also a static reference to that class, which also has access to the other class' fields:

class Compass {
    static NORTH = new Compass()
    static SOUTH = new Compass()
}

assert Compass.NORTH.SOUTH.NORTH == Compass.NORTH

def west = new Compass()
assert west.SOUTH == Compass.SOUTH


问:
Synchronization between Audio & Text for iPhone/iPad SDK
Is there any way to sync audio with text. I have to highlight text word by word for audio file. Text is shown in HTML pages & audioPlay function is implmented in Objective C.</p>

答: I know in flash you would use que points. Maybe iphone as a similar api? Failing that you could do it really easy on the timeline in flash and then package the swf for iphone.</p>


问:
How to take apart parsed JSON results
I want to take a JSON response from an external server but I cannot pull apart each field in the response.

```<code><script>
 function padronafip() {
    $.ajax({
        url:   'https://soa.afip.gob.ar/sr-padron/v2/persona/27293892046',
        datatype: 'json',
        success: function(data) {
            var JSONString = JSON.stringify(data);
            console.log(JSONString);
        }
    });
}
</script>
</code>```

Here follows the response:

```<code>{"success":true,"data":{"idPersona":27293892046,"tipoPersona":"FISICA","tipoClave":"CUIT","estadoClave":"ACTIVO","nombre":"SPITALE LAURA ANDREA","tipoDocumento":"DNI","numeroDocumento":"29389204","domicilioFiscal":{"direccion":"25 DE MAYO 198      - ESQUINA: RIVADAVIA","localidad":"PIGUE","codPostal":"8170","idProvincia":1},"idDependencia":111,"mesCierre":12,"fechaInscripcion":"1997-07-03","categoriasMonotributo":[{"idImpuesto":20,"idCategoria":44},{"idImpuesto":21,"idCategoria":11}],"impuestos":[20],"actividades":[474010,951100]}}
</code>```

I want to fill differet text boxes with some of the data.

Thanks!

答:
remove this:

```<code>var JSONString = JSON.stringify(data);
console.log(JSONString);
</code>```

you can then access your data in this manner:

```<code>$.ajax({
    url: 'https://soa.afip.gob.ar/sr-padron/v2/persona/27293892046',
    datatype: 'json',
    success: function(result) {
        console.log(result.data.nombre);
    }
});
</code>```

Title: How to take apart parsed JSON results

Body:
I want to take a JSON response from an external server but I cannot pull apart each field in the response.

Here follows the response:

{"success":true,"data":{"idPersona":27293892046,"tipoPersona":"FISICA","tipoClave":"CUIT","estadoClave":"ACTIVO","nombre":"SPITALE LAURA ANDREA","tipoDocumento":"DNI","numeroDocumento":"29389204","domicilioFiscal":{"direccion":"25 DE MAYO 198      - ESQUINA: RIVADAVIA","localidad":"PIGUE","codPostal":"8170","idProvincia":1},"idDependencia":111,"mesCierre":12,"fechaInscripcion":"1997-07-03","categoriasMonotributo":[{"idImpuesto":20,"idCategoria":44},{"idImpuesto":21,"idCategoria":11}],"impuestos":[20],"actividades":[474010,951100]}}

I want to fill differet text boxes with some of the data.

Thanks!

Body:
remove this:

var JSONString = JSON.stringify(data);
console.log(JSONString);

you can then access your data in this manner:

$.ajax({
    url: 'https://soa.afip.gob.ar/sr-padron/v2/persona/27293892046',
    datatype: 'json',
    success: function(result) {
        console.log(result.data.nombre);
    }
});


问:
Java: Long result = -1: cannot convert from int to long
I'm using eclipse java ee to perform java programming.

I had the following line of code in one of my functions:

```<code>Long result = -1;
</code>```

I got the following error:

Type mismatch: cannot convert from int to Long

I can't quite understand why when i add a number to the variable it provides this error.

How can this issue be resolved and why did it happen in the first place?

答:
-1 is a primitive int value, Long however is the wrapper class java.lang.Long. An primitive integer value cannot be assigned to an Long object. There are two ways to solve this.

Change the type to long

If you change the type from the wrapper class Long to the primitive type long java automatically casts the integer value to a long value.

long result = -1;

Change the int value to long

If you change the integer value from -1 to -1L to explicit change it to an long literal java can use this primitive value to automatically wrap this value to an java.lang.Long object.

Long result = -1L;

Body:
I'm using eclipse java ee to perform java programming.

I had the following line of code in one of my functions:

Long result = -1;

I got the following error:

Type mismatch: cannot convert from int to Long

I can't quite understand why when i add a number to the variable it provides this error.

How can this issue be resolved and why did it happen in the first place?


问:
JPA Criteria multiselect with fetch
I have following model:

```<code>@Entity
@Table(name = "SAMPLE_TABLE")
@Audited
public class SampleModel implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID")
    private Long id;

    @Column(name = "NAME", nullable = false)
    @NotEmpty
    private String name;

    @Column(name = "SHORT_NAME", nullable = true)
    private String shortName;

    @ManyToOne(fetch = FetchType.LAZY, optional = true)
    @JoinColumn(name = "MENTOR_ID")
    private User mentor;

//other fields here

//omitted getters/setters

}
</code>```

Now I would like to query only columns: id, name, shortName and mentor which referes to User entity (not complete entity, because it has many other properties and I would like to have best performance).

When I write query:

```<code>CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<SampleModel> query = builder.createQuery(SampleModel.class);
Root<SampleModel> root = query.from(SampleModel.class);
query.select(root).distinct(true);
root.fetch(SampleModel_.mentor, JoinType.LEFT);

query.multiselect(root.get(SampleModel_.id), root.get(SampleModel_.name), root.get(SampleModel_.shortName), root.get(SampleModel_.mentor));
query.orderBy(builder.asc(root.get(SampleModel_.name)));
TypedQuery<SampleModel> allQuery = em.createQuery(query);
return allQuery.getResultList();
</code>```

I have following exception:

```<code>Caused by: org.hibernate.QueryException: query specified join fetching, but the owner of the fetched association was not present in the select list [FromElement{explicit,not a collection join,fetch join,fetch non-lazy properties,classAlias=generatedAlias1,role=com.sample.SampleModel.model.SampleModel.mentor,tableName=USER_,tableAlias=user1_,origin=SampleModel SampleModel0_,columns={SampleModel0_.MENTOR_ID ,className=com.sample.credential.model.User}}]
    at org.hibernate.hql.internal.ast.tree.SelectClause.initializeExplicitSelectClause(SelectClause.java:214)
    at org.hibernate.hql.internal.ast.HqlSqlWalker.useSelectClause(HqlSqlWalker.java:991)
    at org.hibernate.hql.internal.ast.HqlSqlWalker.processQuery(HqlSqlWalker.java:759)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:675)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:311)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:259)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:262)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:190)
    ... 138 more
</code>```

Query before exception:

```<code>SELECT DISTINCT NEW com.sample.SampleModel.model.SampleModel(generatedAlias0.id, generatedAlias0.name, generatedAlias0.shortName, generatedAlias0.mentor)
FROM com.sample.SampleModel.model.SampleModel AS generatedAlias0
LEFT JOIN FETCH generatedAlias0.mentor AS generatedAlias1
ORDER BY generatedAlias0.name ASC
</code>```

I know that I can replace fetch with join but then I will have N+1 problem. Also I do not have back reference from User to SampleModel and I do not want to have..

答:
I got the same problem using EclipseLink as the JPA provider : I just wanted to return the id of a mapped entity («User» in Gazeciarz's example).

This can be achieved quite simply by replacing (in the query.multiselect clause)

```<code>root.get(SampleModel_.mentor)
</code>```

with something like

```<code>root.get(SampleModel_.mentor).get(User_.id)
</code>```

Then, instead of returning all the fields of User, the request will only return the its id.

I also used a tuple query but, in my case, it was because my query was returning fileds from more than one entity.

Title: JPA Criteria multiselect with fetch

Body:
I have following model:

@Entity
@Table(name = "SAMPLE_TABLE")
@Audited
public class SampleModel implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID")
    private Long id;

    @Column(name = "NAME", nullable = false)
    @NotEmpty
    private String name;

    @Column(name = "SHORT_NAME", nullable = true)
    private String shortName;

    @ManyToOne(fetch = FetchType.LAZY, optional = true)
    @JoinColumn(name = "MENTOR_ID")
    private User mentor;

//other fields here

//omitted getters/setters

}

Now I would like to query only columns: id, name, shortName and mentor which referes to User entity (not complete entity, because it has many other properties and I would like to have best performance).

When I write query:

CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<SampleModel> query = builder.createQuery(SampleModel.class);
Root<SampleModel> root = query.from(SampleModel.class);
query.select(root).distinct(true);
root.fetch(SampleModel_.mentor, JoinType.LEFT);

query.multiselect(root.get(SampleModel_.id), root.get(SampleModel_.name), root.get(SampleModel_.shortName), root.get(SampleModel_.mentor));
query.orderBy(builder.asc(root.get(SampleModel_.name)));
TypedQuery<SampleModel> allQuery = em.createQuery(query);
return allQuery.getResultList();

I have following exception:

Caused by: org.hibernate.QueryException: query specified join fetching, but the owner of the fetched association was not present in the select list [FromElement{explicit,not a collection join,fetch join,fetch non-lazy properties,classAlias=generatedAlias1,role=com.sample.SampleModel.model.SampleModel.mentor,tableName=USER_,tableAlias=user1_,origin=SampleModel SampleModel0_,columns={SampleModel0_.MENTOR_ID ,className=com.sample.credential.model.User}}]
    at org.hibernate.hql.internal.ast.tree.SelectClause.initializeExplicitSelectClause(SelectClause.java:214)
    at org.hibernate.hql.internal.ast.HqlSqlWalker.useSelectClause(HqlSqlWalker.java:991)
    at org.hibernate.hql.internal.ast.HqlSqlWalker.processQuery(HqlSqlWalker.java:759)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:675)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:311)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:259)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:262)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:190)
    ... 138 more

Query before exception:

SELECT DISTINCT NEW com.sample.SampleModel.model.SampleModel(generatedAlias0.id, generatedAlias0.name, generatedAlias0.shortName, generatedAlias0.mentor)
FROM com.sample.SampleModel.model.SampleModel AS generatedAlias0
LEFT JOIN FETCH generatedAlias0.mentor AS generatedAlias1
ORDER BY generatedAlias0.name ASC

I know that I can replace fetch with join but then I will have N+1 problem. Also I do not have back reference from User to SampleModel and I do not want to have..

Body:
I got the same problem using EclipseLink as the JPA provider : I just wanted to return the id of a mapped entity («User» in Gazeciarz's example).

This can be achieved quite simply by replacing (in the query.multiselect clause)

root.get(SampleModel_.mentor)

with something like

root.get(SampleModel_.mentor).get(User_.id)

Then, instead of returning all the fields of User, the request will only return the its id.

I also used a tuple query but, in my case, it was because my query was returning fileds from more than one entity.


问:
Cannot call value of non-function type 'NSHTTPURLResponse?' Alamofire ObjectMapper
Cannot call value of non-function type 'NSHTTPURLResponse?'

Can someone please help me here?

Here is the code

```<code>   public func responseObject<T: Mappable>(queue: dispatch_queue_t?, keyPath: String?, completionHandler: (NSURLRequest, NSHTTPURLResponse?, T?, AnyObject?, ErrorType?) -> Void) -> Self {

    return response(queue: queue, responseSerializer: Request.JSONResponseSerializer(options: NSJSONReadingOptions.AllowFragments)) { request, response, result in
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
            let parsedObject = Mapper<T>().map(keyPath != nil ? result.value?[keyPath!] : result.value)

            dispatch_async(queue ?? dispatch_get_main_queue()) {
                completionHandler(self.request!, self.response, parsedObject, result.value ?? result.data, result.error)
            }
        }
    }
}
</code>```

My bad, I did not notice the return type of Alamofire 2.0,

This is fixed, updated code is here

```<code>public func responseObject<T: Mappable>(queue: dispatch_queue_t?, keyPath: String?, completionHandler: (NSURLRequest, NSHTTPURLResponse?, T?, AnyObject?, ErrorType?) -> Void) -> Self {

let serializer = Request.JSONResponseSerializer(options: NSJSONReadingOptions.AllowFragments)

return response(queue: queue, responseSerializer: serializer) { (Response) -> Void in

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
            let parsedObject = Mapper<T>().map(keyPath != nil ? Response.result.value?[keyPath!] : Response.result.value)

            dispatch_async(queue ?? dispatch_get_main_queue()) {
                completionHandler(self.request!, self.response, parsedObject, Response.result.value ?? Response.result.value, Response.result.error)
            }
        }

    }
}
</code>```

答: You need to mark your completionHandler as @escaping.</p>

Body:
Cannot call value of non-function type 'NSHTTPURLResponse?'

Can someone please help me here?

Here is the code

   public func responseObject<T: Mappable>(queue: dispatch_queue_t?, keyPath: String?, completionHandler: (NSURLRequest, NSHTTPURLResponse?, T?, AnyObject?, ErrorType?) -> Void) -> Self {

    return response(queue: queue, responseSerializer: Request.JSONResponseSerializer(options: NSJSONReadingOptions.AllowFragments)) { request, response, result in
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
            let parsedObject = Mapper<T>().map(keyPath != nil ? result.value?[keyPath!] : result.value)

            dispatch_async(queue ?? dispatch_get_main_queue()) {
                completionHandler(self.request!, self.response, parsedObject, result.value ?? result.data, result.error)
            }
        }
    }
}

My bad, I did not notice the return type of Alamofire 2.0,

This is fixed, updated code is here

public func responseObject<T: Mappable>(queue: dispatch_queue_t?, keyPath: String?, completionHandler: (NSURLRequest, NSHTTPURLResponse?, T?, AnyObject?, ErrorType?) -> Void) -> Self {

let serializer = Request.JSONResponseSerializer(options: NSJSONReadingOptions.AllowFragments)

return response(queue: queue, responseSerializer: serializer) { (Response) -> Void in

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
            let parsedObject = Mapper<T>().map(keyPath != nil ? Response.result.value?[keyPath!] : Response.result.value)

            dispatch_async(queue ?? dispatch_get_main_queue()) {
                completionHandler(self.request!, self.response, parsedObject, Response.result.value ?? Response.result.value, Response.result.error)
            }
        }

    }
}


问:
How to replace escape character in Netezza column
I am trying to replace escape character in Netezza column, but it is not properly replacing.
Please help me some one on this.

```<code>select replace('replaces\tring','\','\\\\');
</code>```

I need output as replaces\\\\tring. Below is the error message i am getting...

ERROR [42S02] ERROR:  Function 'REPLACE(UNKNOWN, UNKNOWN, UNKNOWN)'
  does not exist    Unable to identify a function that satisfies the given
  argument types    You may need to add explicit typecasts

Thanks in advance.

答:
That particular function is part of the "SQL Extensions toolkit" and on our system it is placed in the ADMIN schema of the SQLEXT database. All users have been granted execute access to that schema. Furthermore the database.schema have been placed in the path (the DBA's did it globally, but you can issue a "set PATH=..." in your session if need be)

our path is:

```<code>select current_path;

CURRENT_PATH
---------------------------------------------------------------------------------------
SQLEXT.ADMIN,INZA.INZA,NZA.INZA,NZM.INZA,NZMSG.INZA,NZR.INZA,NZRC.INZA,SYNCHDB.ADMIN
</code>```

and as you can see the SQLEXT is at the beginning...

Body:
I am trying to replace escape character in Netezza column, but it is not properly replacing.
Please help me some one on this.

select replace('replaces\tring','\','\\\\');

I need output as replaces\\\\tring. Below is the error message i am getting...

ERROR [42S02] ERROR:  Function 'REPLACE(UNKNOWN, UNKNOWN, UNKNOWN)'
  does not exist    Unable to identify a function that satisfies the given
  argument types    You may need to add explicit typecasts

Thanks in advance.

Body:
That particular function is part of the "SQL Extensions toolkit" and on our system it is placed in the ADMIN schema of the SQLEXT database. All users have been granted execute access to that schema. Furthermore the database.schema have been placed in the path (the DBA's did it globally, but you can issue a "set PATH=..." in your session if need be)

our path is:

select current_path;

CURRENT_PATH
---------------------------------------------------------------------------------------
SQLEXT.ADMIN,INZA.INZA,NZA.INZA,NZM.INZA,NZMSG.INZA,NZR.INZA,NZRC.INZA,SYNCHDB.ADMIN

and as you can see the SQLEXT is at the beginning...


问:
string manipulation for column names in pyspark
This artcle gives a great overview on how to change columnnames.
How to change dataframe column names in pyspark?

Nontheless I need something more / slightly adjusted that I am not capable of doing. Can anybody help remove spaces from all colnames? Its needed for e.g. join commands and the systematic approach reduces the effort of dealing with 30 columns. I suppose a combination of regex and a UDF would work best.

Example:
root
 |-- CLIENT: string (nullable = true)
 |-- Branch Number: string (nullable = true)

答:
There is a real simple solution:</p>

```<code>for name in df.schema.names:
  df = df.withColumnRenamed(name, name.replace(' ', ''))
</code>```

Body:
There is a real simple solution:

for name in df.schema.names:
  df = df.withColumnRenamed(name, name.replace(' ', ''))