问:
Log4j DailyRollingFileAppender date before the filename
Is there a way to configure DailyRollingFileAppender to put the date before the file name? i.e. 2017.07.05.log.err instead of log.err.2017.07.05.

This is my current configuration

```<code><appender name="file" class="org.apache.log4j.DailyRollingFileAppender">
    <param name="append" value="true" />
    <param name="DatePattern" value="'.'yyyy.MM.dd" />
    <param name="file" value="./data/logs/log.err" />
    <layout class="org.apache.log4j.PatternLayout">
        <!-- The default pattern: Date Priority [Category] Message\n -->
        <param name="ConversionPattern" value="[%d{ABSOLUTE}][%-5p [%c{1}]] %m%n" />
    </layout>
</appender>
</code>```

答:
Before you configure log4j  ( e.g. using BasicConfigurator.configure() ) , set a property called log4j.log.file using :

System.setProperty( "log4j.log.file", "your_file_name" );

Or you can use -Dlog4j.log.file=your_file_name if you are using command line. But I guess you construct date runtime, so use setProperty().

Your file name could be constructed runtime using

```<code>String dateString = new SimpleDateFormat("yyyy.MM.dd").format(new Date()).toString();
String filename = "./data/logs/" + File.separator + dateString + ".log.err";
</code>```

and specify the property in your log4j xml like :

<param name="file" value="${log4j.log.file}" />

Body:
Is there a way to configure DailyRollingFileAppender to put the date before the file name? i.e. 2017.07.05.log.err instead of log.err.2017.07.05.

This is my current configuration

<appender name="file" class="org.apache.log4j.DailyRollingFileAppender">
    <param name="append" value="true" />
    <param name="DatePattern" value="'.'yyyy.MM.dd" />
    <param name="file" value="./data/logs/log.err" />
    <layout class="org.apache.log4j.PatternLayout">

        <param name="ConversionPattern" value="[%d{ABSOLUTE}][%-5p [%c{1}]] %m%n" />
    </layout>
</appender>

Body:
Before you configure log4j  ( e.g. using BasicConfigurator.configure() ) , set a property called log4j.log.file using :

System.setProperty( "log4j.log.file", "your_file_name" );

Or you can use -Dlog4j.log.file=your_file_name if you are using command line. But I guess you construct date runtime, so use setProperty().

Your file name could be constructed runtime using

String dateString = new SimpleDateFormat("yyyy.MM.dd").format(new Date()).toString();
String filename = "./data/logs/" + File.separator + dateString + ".log.err";

and specify the property in your log4j xml like :

<param name="file" value="${log4j.log.file}" />


来源: stackexchange

答:
Another example:  "$550,000".replace("$","");

That results in "550,000"

ContentLicense: CC BY-SA 3.0

Title: String slicing in javascript

Body:
export class Prices{
value : string;
}

const PRICES : Prices[] =[
{value :'$10,000'},{value :'$20,000'},{value :'$30,000'},{value
:'$40,000'},{value :'$50,000'},
{value :'$60,000'},{value :'$70,000'},{value :'$80,000'},{value
:'$90,000'},{value :'$100,000'},
{value :'$125,000'},{value :'$150,000'},{value :'$175,000'},{value
:'$200,000'},{value :'$225,000'},
{value :'$250,000'},{value :'$275,000'},{value :'$300,000'},{value
:'$325,000'},{value :'$350,000'},
{value :'$375,000'},{value :'$400,000'},{value :'$425,000'},{value
:'$450,000'},{value :'$475,000'},
{value :'$500,000'},{value :'$525,000'},{value :'$550,000'},{value
:'$575,000'},{value :'$600,000'}]

export class ConstantProperty implements OnInit{
prices=PRICES;
selectedPriceMin : Prices;
}

I am selecting the price from a drop down menu in html,
Now I want to slice that selected price in order to remove dollar sign.


问:
Cake3 Paginator Sort Error
I have a very simply model which I want to paginate. The pagination works but the sort links do not have any effect:

My Controller:

```<code>public $paginate = [
        'limit' => 10,
        'order' => [
            'Properties.id' => 'asc'
        ],
        'sortWhitelist' => [
            'Properties.id',
            'Properties.name',
            'Properties.active'
        ],
];
</code>```

My query:

```<code>$properties = $this->Properties->find('all')->where($options)->contain($contains)->order(['Properties.id']);

$this->set('properties', $this->paginate($properties));
</code>```

My view displays 10 items per page and the links to pages/next/previous work fine. When I click the sort link:

```<code>$this->Paginator->sort('id', 'ID')
</code>```

The url called is:

properties/index/3?sort=id&direction=desc

The page re-loads but the order of the data does not change.

答:
The whitelist expects the exact field name that you are using in sort. It will not automatically prepend the primary table's name, so your whitelist should look like this:

```<code>public $paginate = [
    'limit' => 10,
    'order' => [
        'Properties.id' => 'asc'
    ],
    'sortWhitelist' => [
        'id',
        'name',
        'active'
    ],
];
</code>```

It will see "id" in the query and check that the exact field name "id" exists in the whitelist.

Also, it appears you are including an order() on your query. To allow the paginator to set the order, you should remove this clause.

Title: Cake3 Paginator Sort Error

Body:
I have a very simply model which I want to paginate. The pagination works but the sort links do not have any effect:

My Controller:

public $paginate = [
        'limit' => 10,
        'order' => [
            'Properties.id' => 'asc'
        ],
        'sortWhitelist' => [
            'Properties.id',
            'Properties.name',
            'Properties.active'
        ],
];

My query:

$properties = $this->Properties->find('all')->where($options)->contain($contains)->order(['Properties.id']);

$this->set('properties', $this->paginate($properties));

My view displays 10 items per page and the links to pages/next/previous work fine. When I click the sort link:

$this->Paginator->sort('id', 'ID')

The url called is:

properties/index/3?sort=id&direction=desc

The page re-loads but the order of the data does not change.

Body:
The whitelist expects the exact field name that you are using in sort. It will not automatically prepend the primary table's name, so your whitelist should look like this:

public $paginate = [
    'limit' => 10,
    'order' => [
        'Properties.id' => 'asc'
    ],
    'sortWhitelist' => [
        'id',
        'name',
        'active'
    ],
];

It will see "id" in the query and check that the exact field name "id" exists in the whitelist.

Also, it appears you are including an order() on your query. To allow the paginator to set the order, you should remove this clause.


问:
VueJS: Fetch data before and after loading a component
I am new to VueJS and working on a component and want to fetch some data from an API before the corresponding route is loaded; only then the component should load. Once the component is created, I have to call another API that takes as input the data obtained from first API. Here is my component script:

```<code>export default {
  name: 'login',
  data () {
    return {
      categories: []
    }
  },
  created () {
     // it gives length = 0 but it should have been categories.length
      console.log(this.categories.length);

    // Call getImage method
    loginService.getImage(this.categories.length)
        .then(res => {
            console.log('Images fetched');
        })
  },
  beforeRouteEnter (to, from, next) {
    loginService.getCategories().then((res) => {
      next(vm => {
        vm.categories = res.data.categories;
      });
    }, (error) => {
      console.log('Error: ', error);
      next(error);
    })
  },
  methods: {}
}
</code>```

I tried using mounted hook but it does not work. However if I watch the categories property and call fetch image method, it works. I don't think using watchers is the best approach here. Any thoughts?

答:
Move your call to get additional information into a method and call that method from next.

```<code>export default {
  name: 'login',
  data () {
    return {
      categories: []
    }
  },
  beforeRouteEnter (to, from, next) {
    loginService.getCategories().then((res) => {
      next(vm => {
        vm.categories = res.data.categories;
        vm.getMoreStuff()
      });
    }, (error) => {
      console.log('Error: ', error);
      next(error);
    })
  },
  methods: {
    getMoreStuff(){
      console.log(this.categories.length);

      // Call getImage method
      loginService.getImage(this.categories.length)
        .then(res => {
            console.log('Images fetched');
        })
    }
  }
}
</code>```

Alternatively, do it in the callback for getCategories.

```<code>loginService.getCategories()
  .then(res => {
    vm.categories = res.data.categories;
    loginService.getImage(vm.categories.length)
      .then(res => //handle images then call next())
  })
  .catch(err => //handle err)
</code>```

Or if you are using a pre-compiler that handles async/await

```<code>async beforeRouteEnter(to, from, next){
  try{
    const categoryResponse = await loginService.getCategories()
    const categories = categoryResponse.data.categories
    const imageResponse= await loginService.getImage(categories.length)
    next(vm => {
      vm.categories = categories
      vm.images = imageResponse.data.images
    })

  } catch(err){
    //handle err
  }
}
</code>```

Body:
I am new to VueJS and working on a component and want to fetch some data from an API before the corresponding route is loaded; only then the component should load. Once the component is created, I have to call another API that takes as input the data obtained from first API. Here is my component script:

export default {
  name: 'login',
  data () {
    return {
      categories: []
    }
  },
  created () {
     // it gives length = 0 but it should have been categories.length
      console.log(this.categories.length);

    // Call getImage method
    loginService.getImage(this.categories.length)
        .then(res => {
            console.log('Images fetched');
        })
  },
  beforeRouteEnter (to, from, next) {
    loginService.getCategories().then((res) => {
      next(vm => {
        vm.categories = res.data.categories;
      });
    }, (error) => {
      console.log('Error: ', error);
      next(error);
    })
  },
  methods: {}
}

I tried using mounted hook but it does not work. However if I watch the categories property and call fetch image method, it works. I don't think using watchers is the best approach here. Any thoughts?

Body:
Move your call to get additional information into a method and call that method from next.

export default {
  name: 'login',
  data () {
    return {
      categories: []
    }
  },
  beforeRouteEnter (to, from, next) {
    loginService.getCategories().then((res) => {
      next(vm => {
        vm.categories = res.data.categories;
        vm.getMoreStuff()
      });
    }, (error) => {
      console.log('Error: ', error);
      next(error);
    })
  },
  methods: {
    getMoreStuff(){
      console.log(this.categories.length);

      // Call getImage method
      loginService.getImage(this.categories.length)
        .then(res => {
            console.log('Images fetched');
        })
    }
  }
}

Alternatively, do it in the callback for getCategories.

loginService.getCategories()
  .then(res => {
    vm.categories = res.data.categories;
    loginService.getImage(vm.categories.length)
      .then(res => //handle images then call next())
  })
  .catch(err => //handle err)

Or if you are using a pre-compiler that handles async/await

async beforeRouteEnter(to, from, next){
  try{
    const categoryResponse = await loginService.getCategories()
    const categories = categoryResponse.data.categories
    const imageResponse= await loginService.getImage(categories.length)
    next(vm => {
      vm.categories = categories
      vm.images = imageResponse.data.images
    })

  } catch(err){
    //handle err
  }
}


问:
Is it possible to display an OpenCV video inside the IPython /JuPyter Notebook?
When running the examples from the OpenCV video processing python tutorials, they all pop up in a dedicated window. I know that the IPython notebook can display videos from disk and YouTube, so I wonder if there is a way to direct the OpenCV video playback to the Notebook browser and have it play in the output cell instead of a separate window (preferably without saving it to disk and then playing it from there).

Below is the code from the OpenCV tutorial.

```<code>import cv2

cap = cv2.VideoCapture('/path/to/video')

while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()

    # Our operations on the frame come here
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Display the resulting frame
    cv2.imshow('frame',gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
</code>```

答:
The video encoded data (if in a format the browser can decode, eg. h264-encoded in ISO mp4 container) can be displayed using an HTML <video> tag and IPython.core.display.HTML(), this will provide standard playback performance.

The <video> can be a link, or have embedded base64'ed data (the latter is what matplotlib.animation does, for example), and its data can of course be generated in your notebook, using OpenCV (eg. VideoWriter).

Body:
When running the examples from the OpenCV video processing python tutorials, they all pop up in a dedicated window. I know that the IPython notebook can display videos from disk and YouTube, so I wonder if there is a way to direct the OpenCV video playback to the Notebook browser and have it play in the output cell instead of a separate window (preferably without saving it to disk and then playing it from there).

Below is the code from the OpenCV tutorial.

import cv2

cap = cv2.VideoCapture('/path/to/video')

while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()

    # Our operations on the frame come here
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Display the resulting frame
    cv2.imshow('frame',gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()


问:
module specifier in es6 import and export
I'm confused about what the module specifier in these statements refer to:

```<code>export {bar} from "foo";

import {bar} from "foo";
</code>```

What does "foo" refer to? It can't be a file since it would be something like "./foo". If it's not a file, I assume it's an ID. How is the ID defined?

I'm exporting from a js file, but the import would be part of an inline html script (type="module") in the firefox browser.

The browser version (and browser settings) have been verified to work with es6 modules.

Thanks in advance.

Body:
I'm confused about what the module specifier in these statements refer to:

export {bar} from "foo";

import {bar} from "foo";

What does "foo" refer to? It can't be a file since it would be something like "./foo". If it's not a file, I assume it's an ID. How is the ID defined?

I'm exporting from a js file, but the import would be part of an inline html script (type="module") in the firefox browser.

The browser version (and browser settings) have been verified to work with es6 modules.

Thanks in advance.

Body:
ES6 does not specify what the module specifier refers to.

It is indeed just that: an identifier. Nothing more.

It is left to the environment to resolve these identifiers to an actual module. A loader might interpret them as relative file paths, as global ids, as npm module names, as anything else.

In browsers, <script type="module"> took some time to specify, but it's here finally. A module specifier of "foo" is currently invalid, a browser will ignore that module as it doesn't know what to do with it. It will need something that resolves to an URL to load. Jake Archibald wrapped it up succinctly:

"Bare" import specifiers aren't currently supported. Valid module
  specifiers must match one of the following:

A full non-relative URL. As in, it doesn't throw an error when put
  through new URL(moduleSpecifier).

Starts with /.

Starts with ./.

Starts with ../.

Other specifiers are reserved for future-use, such as importing built-in
  modules.


问:
Creating winforms base controls
We have several winforms applications we want to restyle and make consistent (styling wise).  We want to create some base classes for some of the windows controls such as buttons and toolstrip.  All my base classes intend to do is specify the specific styling we wish to apply.  This works the first time I bring into my form but later on if I wish to update a property it doesn't apply it back to the forms that previously already have pulled it in.  Anyway to get this to work?  Here's an example, lets say I want to create a base class for a toolstrip.  All I want to do is set the backcolor to green (I really want to set more properties but this is to demo my issue).  So I create a class library called BaseControls and create a class called BaseToolStrip and set the backcolor to green in its constructor.

```<code>public class BaseToolStrip : ToolStrip
{
  public BaseToolStrip()
  {
    BackColor = Color.Green;
  }
}
</code>```

Now if I create a demo project and add an instance of BaseToolStrip to the form it works.  It creates a green toolstrip.  Later if I decided I want my base toolstrip to have a backcolor of red if I update the constructor in my BaseToolStrip class and set the BackColor = Color.Red and run my solution the color is still green.  It appears that once I've brought that control in it set backcolor = green.  So even though in my base class I set backcolor = red in my form that instantiates it still has backcolor = green.  Any way to override all instances and set backcolor equal to the color specified in my BaseToolStrip class?

答:
Try setting the default value for the property (as well as setting the actual value in the ctor):

```<code>[DefaultValue(typeof(Color), "Green")]
public override Color BackColor {
   get { return base.BackColor; }
   set { base.BackColor = value; }
}
</code>```

I do not have VS available to test right now, but I think that will cause the designer to notice that the current value is the default, and therefore doesn't need to be saved in the Designer.cs.

So if you change the color in both places later, it should update everywhere.

Of course, this will only work for controls that you drag onto a form after you add this code, since the others already have the value saved.

Title: Creating winforms base controls

Body:
We have several winforms applications we want to restyle and make consistent (styling wise).  We want to create some base classes for some of the windows controls such as buttons and toolstrip.  All my base classes intend to do is specify the specific styling we wish to apply.  This works the first time I bring into my form but later on if I wish to update a property it doesn't apply it back to the forms that previously already have pulled it in.  Anyway to get this to work?  Here's an example, lets say I want to create a base class for a toolstrip.  All I want to do is set the backcolor to green (I really want to set more properties but this is to demo my issue).  So I create a class library called BaseControls and create a class called BaseToolStrip and set the backcolor to green in its constructor.

public class BaseToolStrip : ToolStrip
{
  public BaseToolStrip()
  {
    BackColor = Color.Green;
  }
}

Now if I create a demo project and add an instance of BaseToolStrip to the form it works.  It creates a green toolstrip.  Later if I decided I want my base toolstrip to have a backcolor of red if I update the constructor in my BaseToolStrip class and set the BackColor = Color.Red and run my solution the color is still green.  It appears that once I've brought that control in it set backcolor = green.  So even though in my base class I set backcolor = red in my form that instantiates it still has backcolor = green.  Any way to override all instances and set backcolor equal to the color specified in my BaseToolStrip class?

Body:
Try setting the default value for the property (as well as setting the actual value in the ctor):

[DefaultValue(typeof(Color), "Green")]
public override Color BackColor {
   get { return base.BackColor; }
   set { base.BackColor = value; }
}

I do not have VS available to test right now, but I think that will cause the designer to notice that the current value is the default, and therefore doesn't need to be saved in the Designer.cs.

So if you change the color in both places later, it should update everywhere.

Of course, this will only work for controls that you drag onto a form after you add this code, since the others already have the value saved.


问:
Android substring values in arraylist
I'm pulling data from database into an arraylist.  I want to manipulate the arraylist and get a substring of the results.  How can I substring the values generated in carList below?</p>

```<code>private ArrayList<Cars> carList;
carList = CarDAO.getCarsByEngine(engineType);
</code>```

答:
Assuming you have a attribute String name in car.</p>

```<code>String searchStr = "your_str";
for(i=0; i<carList.size();i++){
    carList[i].name;
    if(searchStr.toLowerCase().contains(carList[i].name.toLowerCase())){
        // do somethig with your object carList[i]
    }
}
</code>```

Title: Android substring values in arraylist

Body:
I'm pulling data from database into an arraylist.  I want to manipulate the arraylist and get a substring of the results.  How can I substring the values generated in carList below?

private ArrayList<Cars> carList;
carList = CarDAO.getCarsByEngine(engineType);

Body:
Assuming you have a attribute String name in car.

String searchStr = "your_str";
for(i=0; i<carList.size();i++){
    carList[i].name;
    if(searchStr.toLowerCase().contains(carList[i].name.toLowerCase())){
        // do somethig with your object carList[i]
    }
}


问:
Share component in Angular 2
I have a page display all records in table, it have pagination in the bottom. I think the pagination should be a independent component because it will be reuse in many management panel.Ex: UserManagement, PostManagement, ..

I don't know how to do that because the pagination only work because it has to know exactly how many record in the specific table. Ex: In UserManagement, I use UserService to get count all records and get limit records to display in the table user. In PostManagement I have to do the same thing.

This is my code for now:
users.component.ts (to display list user)

```<code>export class UsersComponent implements OnInit {
  private users: User[];
  private pagination: Pagination;
  private limit: number;
  private currentPage: number;
  private limits:number[] = _.range(10,110,10);

  constructor(
    private userService: UsersService,
  ) { }

  ngOnInit() {
    this.limit = 10;
    this.currentPage = 1;
    this.pagination = new Pagination(1, this.currentPage, this.limit);
    this.changePage(this.currentPage);
  }

  changePage(page: number) {
    if (page < 1 || page > this.pagination.totalPages) {
      return;
    }
    this.currentPage = page;
    this.userService.getUsers(this.limit * (this.currentPage - 1), this.limit).subscribe(res => {
        this.users = res.rows as User[];
        this.pagination = new Pagination(res.count, this.currentPage, this.limit);
      });
  }
}
</code>```

users.component.html

```<code><div class="row">
          <div class="col-sm-12">
            <table class="table table-striped table-bordered table-hover dataTable no-footer dtr-inline" id="dataTables-example" role="grid">
              <thead>
                <tr role="row">
                  <th class="sorting_desc" tabindex="0" rowspan="1" colspan="1">Id</th>
                  <th class="sorting" tabindex="0" rowspan="1" colspan="1">Account</th>
                  <th class="sorting" tabindex="0" rowspan="1" colspan="1">Password</th>
                  <th tabindex="0" rowspan="1" colspan="1">Status</th>
                  <th tabindex="0" rowspan="1" colspan="3">Action</th>
                </tr>
              </thead>
              <tbody>
                <tr *ngFor="let user of users;let index=index;let isOdd=odd;let isEven=even" class="gradeA" [class.odd]="isOdd" [class.even]="isEven"
                  role="row">
                  <td>{{user.id}}</td>
                  <td>{{user.username}}</td>
                  <td>{{user.password}}</td>
                  <td>{{user.status}}</td>
                  <td>action</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
        <div class="row">
          <div class="col-sm-6">
            <div class="dataTables-info" id="dataTables-example_info">Information</div>
          </div>
          <div class="col-sm-6">
            <div class="dataTables_paginate paging_simple_numbers" id="dataTables-example_paginate" *ngIf="pagination.displayPages && pagination.displayPages.length">
              <ul class="pagination">
                <li class="paginate_button first" [ngClass]="{disabled:pagination.currentPage === 1}">
                  <a (click)="changePage(1)">First</a>
                </li>
                <li class="paginate_button previous" [ngClass]="{disabled:pagination.currentPage === 1}">
                  <a (click)="changePage(pagination.currentPage - 1 )">Previous</a>
                </li>
                <li class="paginate_button previous" *ngFor="let page of pagination.displayPages" [ngClass]="{active:pagination.currentPage === page}">
                  <a (click)="changePage(page)">{{page}}</a>
                </li>
                <li class="paginate_button next" [ngClass]="{disabled:pagination.currentPage === pagination.totalPages}">
                  <a (click)="changePage(pagination.currentPage + 1 )">Next</a>
                </li>
                <li class="paginate_button last" [ngClass]="{disabled:pagination.currentPage === pagination.totalPages}">
                  <a (click)="changePage(pagination.totalPages )">Last</a>
                </li>
              </ul>
            </div>
          </div>
        </div>
</code>```

pagination.ts

```<code>export class Pagination {
    totalElements: number;
    totalPages: number;
    currentPage: number;
    limit: number;
    startPage: number;
    endPage: number;
    startIndex: number;
    endIndex: number;
    displayPages: number[];

    constructor(totalElements: number, currentPage: number = 1, limit: number = 10) {
        this.totalElements = totalElements;
        this.limit = limit;
        this.currentPage = currentPage;
        this.totalPages = Math.ceil(totalElements / limit);
        this.startPage = 1;
        this.endPage = this.totalPages;
        if (this.totalPages > 10) {
            if (currentPage <= 6) {
                this.endPage = 10;
            } else if (currentPage + 4 >= this.totalPages) {
                this.startPage = this.totalPages - 9;
            } else {
                this.startPage = currentPage - 5;
                this.endPage = currentPage + 4;
            }

        }
        this.startIndex = (currentPage - 1) * limit;
        this.endIndex = Math.min(this.startIndex + limit - 1, totalElements - 1);
        this.displayPages = _.range(this.startPage, this.endPage + 1);
    }
}
</code>```

答:
Move pagination into separate component and include it into user.component

```<code><app-pagination></app-pagination>
</code>```

Then pass arguments into  from parent component using decorator @Input.

```<code><app-pagination [totalElements]="totalElements
                [totalPages]="totalPages"></app-pagination>
</code>```

In pagination.component.ts

```<code>@Input() totalElements;
</code>```

Then, if you want change parent's value from pagination component - use decorator @Output()

```<code><app-pagination [totalElements]="totalElements
                [totalPages]="totalPages"
                (event)="methodFromUserComponent()"></app-pagination>
</code>```

Read more on official site https://angular.io/guide/component-interaction

And really good article here: https://www.themarketingtechnologist.co/building-nested-components-in-angular-2/

Title: Share component in Angular 2

Body:
I have a page display all records in table, it have pagination in the bottom. I think the pagination should be a independent component because it will be reuse in many management panel.Ex: UserManagement, PostManagement, ..

I don't know how to do that because the pagination only work because it has to know exactly how many record in the specific table. Ex: In UserManagement, I use UserService to get count all records and get limit records to display in the table user. In PostManagement I have to do the same thing.

This is my code for now:
users.component.ts (to display list user)

export class UsersComponent implements OnInit {
  private users: User[];
  private pagination: Pagination;
  private limit: number;
  private currentPage: number;
  private limits:number[] = _.range(10,110,10);

  constructor(
    private userService: UsersService,
  ) { }

  ngOnInit() {
    this.limit = 10;
    this.currentPage = 1;
    this.pagination = new Pagination(1, this.currentPage, this.limit);
    this.changePage(this.currentPage);
  }

  changePage(page: number) {
    if (page < 1 || page > this.pagination.totalPages) {
      return;
    }
    this.currentPage = page;
    this.userService.getUsers(this.limit * (this.currentPage - 1), this.limit).subscribe(res => {
        this.users = res.rows as User[];
        this.pagination = new Pagination(res.count, this.currentPage, this.limit);
      });
  }
}

users.component.html

                  Id
                  Account
                  Password
                  Status
                  Action

                  {{user.id}}
                  {{user.username}}
                  {{user.password}}
                  {{user.status}}
                  action

Information

                  First

                  Previous

                  {{page}}

                  Next

                  Last

pagination.ts

export class Pagination {
    totalElements: number;
    totalPages: number;
    currentPage: number;
    limit: number;
    startPage: number;
    endPage: number;
    startIndex: number;
    endIndex: number;
    displayPages: number[];

    constructor(totalElements: number, currentPage: number = 1, limit: number = 10) {
        this.totalElements = totalElements;
        this.limit = limit;
        this.currentPage = currentPage;
        this.totalPages = Math.ceil(totalElements / limit);
        this.startPage = 1;
        this.endPage = this.totalPages;
        if (this.totalPages > 10) {
            if (currentPage <= 6) {
                this.endPage = 10;
            } else if (currentPage + 4 >= this.totalPages) {
                this.startPage = this.totalPages - 9;
            } else {
                this.startPage = currentPage - 5;
                this.endPage = currentPage + 4;
            }

        }
        this.startIndex = (currentPage - 1) * limit;
        this.endIndex = Math.min(this.startIndex + limit - 1, totalElements - 1);
        this.displayPages = _.range(this.startPage, this.endPage + 1);
    }
}

Body:
Move pagination into separate component and include it into user.component

<app-pagination></app-pagination>

Then pass arguments into  from parent component using decorator @Input.

<app-pagination [totalElements]="totalElements
                [totalPages]="totalPages"></app-pagination>

In pagination.component.ts

@Input() totalElements;

Then, if you want change parent's value from pagination component - use decorator @Output()

<app-pagination [totalElements]="totalElements
                [totalPages]="totalPages"
                (event)="methodFromUserComponent()"></app-pagination>

Read more on official site https://angular.io/guide/component-interaction

And really good article here: https://www.themarketingtechnologist.co/building-nested-components-in-angular-2/


问:
Call a Google App Maker App with a parameter
Hello i am new here so if i ask a stupid question please forgive me.

We at AppAtSchool are working with Google ApMaker and we want to call a published App with 2 parameters. How can we read those in App Maker? Thanks in advance!

答: you can call your application with url something like this: script.google.com/blablabla/#viewname/paramValue, and take param on client side and send it to server side.</p>


问:
Hibernate ManyToOne association in a Spring Form
I have two entities with a @ManyToOne association, and a form which adds a product. Everything is working fine except for the category and the manufacturer attribute. Any Idea ?

Here is the Product class :

```<code>@Entity
public class Product implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@NotEmpty(message = "Le champ nom ne peut être vide")
private String name;

@NotEmpty(message = "Le champ description ne peut être vide")
private String description;

@Min(value = 0, message = "Le prix du produit ne peux pas être négatif")
@NotNull(message = "Le champ prix ne peut pas être vide")
private Double price;

@ManyToOne
private Category category;

@Min(value = 0, message = "Le stock du produit ne peut pas être négatif")
@NotNull(message = "Le champ stock ne peut pas être vide")
private Long stock;

@ManyToOne
private Manufacturer manufacturer;

@Transient
private MultipartFile image;
</code>```

Here is the Category class :

```<code>@Entity
public class Category {
@Id
private Long id;

@NotEmpty(message = "Le champ nom est vide.")
private String name;

private String description;
private String picture;
</code>```

Here is the controller :

```<code>@RequestMapping(value = "admin/inventaire/ajout", method = RequestMethod.POST)
public String ajoutProduitPost(@Valid @ModelAttribute("product") Product product,
        BindingResult result, HttpServletRequest request) {

    if (result.hasErrors()) {
        return "addProduct";
    }

    productDao.addProduct(product);

    MultipartFile productImage = product.getImage();
    String contextPath = context.getRealPath("/");

    Path path = Paths.get(contextPath + "/WEB-INF/resources/images/product   /"+product.getId()+".png");

    if (productImage != null && !productImage.isEmpty()) {
        try {
            productImage.transferTo(new File(path.toString()));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Product image saving failed", e);
        }
    }

    return "redirect:/admin/inventaire";
}
</code>```

And finally the JSP :

```<code>    <%@include file="/WEB-INF/views/template/header.jsp" %>
<%@page contentType="text/html" pageEncoding="UTF-8" language="java"%>

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

<div class="container-wrapper">
    <div class ="container">

        <div class="page-header">
            <h1>Ajout d'un nouveau produit</h1>
        </div>
        <form:form action="${pageContext.request.contextPath}/admin/inventaire/ajout" method="post"
                   modelAttribute="product" enctype="multipart/form-data">
            <!-- NOM -->
            <div class="form-group" >
                <label for = "productName">Name</label>
                <form:input path="name" id="productName" class="form-control "/> <form:errors path="name" cssStyle="color:#ff0000;"/>
            </div>
            <!-- DESCRIPTION -->
            <div class = "form-group">
                <label for = "description">Description</label>
                <form:textarea path = "description" id="description" class ="form-control"/> <form:errors path="description" cssStyle="color:#ff0000;"/>
            </div>
            <!-- STOCK -->
            <div class="form-group">
                <label for="stock">Quantité en stock</label>
                <form:input path="stock" id="stock" class="form-control"/> <form:errors path="stock" cssStyle="color:#ff0000;"/>
            </div>
            <!-- PRIX -->
            <div class="form-group">
                <label for="price">Prix</label>
                <form:input path="price" id="price" class="form-control"/> <form:errors path="price" cssStyle="color:#ff0000;"/>
            </div>
            <!-- CATEGORY -->
            <div class="form-group">
                <label for="category">Catégorie</label>
                <form:select path="category">
                    <form:option value="-" label="--Please Select"/>
                    <form:options items="${categoryList}" itemValue="id" itemLabel="name"/>
                </form:select>
            </div>
            <!-- FABRICANT -->

            <!-- IMAGE -->
            <div class="form-group">
                <label class = "control-label" for= "image">Image</label>
                <form:input id="image" path = "image" type="file" class="form:input-large"/>
            </div>

            <input type="submit" value="Envoyer" class="btn btn-default">
            <a href="<c:url value="/admin/inventaire" />" class="btn btn-default">Annuler</a>

        </form:form>
    </div>
</div>
    <%@include file="/WEB-INF/views/template/footer.jsp" %>
</code>```

I think the problem is that the form sends the id of the category to the controller, but it expects the object Category instead. I can't find a solution around it.

答:
first of all you need to use @JoinColumn for mapping of @ManyToOne, for example you can use refer code :

```<code>@ManyToOne
@JoinColumn(name = "id")
private Category category;
</code>```

then after get the category id into controller and find the category by id. now you have object of Category Entity, set the category Object into Product. and use cascade = CascadeType.ALL, fetch = FetchType.LAZY onto  ManyToOne relation.

Body:
I have two entities with a @ManyToOne association, and a form which adds a product. Everything is working fine except for the category and the manufacturer attribute. Any Idea ?

Here is the Product class :

@Entity
public class Product implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@NotEmpty(message = "Le champ nom ne peut être vide")
private String name;

@NotEmpty(message = "Le champ description ne peut être vide")
private String description;

@Min(value = 0, message = "Le prix du produit ne peux pas être négatif")
@NotNull(message = "Le champ prix ne peut pas être vide")
private Double price;

@ManyToOne
private Category category;

@Min(value = 0, message = "Le stock du produit ne peut pas être négatif")
@NotNull(message = "Le champ stock ne peut pas être vide")
private Long stock;

@ManyToOne
private Manufacturer manufacturer;

@Transient
private MultipartFile image;

Here is the Category class :

@Entity
public class Category {
@Id
private Long id;

@NotEmpty(message = "Le champ nom est vide.")
private String name;

private String description;
private String picture;

Here is the controller :

@RequestMapping(value = "admin/inventaire/ajout", method = RequestMethod.POST)
public String ajoutProduitPost(@Valid @ModelAttribute("product") Product product,
        BindingResult result, HttpServletRequest request) {

    if (result.hasErrors()) {
        return "addProduct";
    }

    productDao.addProduct(product);

    MultipartFile productImage = product.getImage();
    String contextPath = context.getRealPath("/");

    Path path = Paths.get(contextPath + "/WEB-INF/resources/images/product   /"+product.getId()+".png");

    if (productImage != null && !productImage.isEmpty()) {
        try {
            productImage.transferTo(new File(path.toString()));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Product image saving failed", e);
        }
    }

    return "redirect:/admin/inventaire";
}

And finally the JSP :

    <%@include file="/WEB-INF/views/template/header.jsp" %>
<%@page contentType="text/html" pageEncoding="UTF-8" language="java"%>

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

Ajout d'un nouveau produit

        <form:form action="${pageContext.request.contextPath}/admin/inventaire/ajout" method="post"
                   modelAttribute="product" enctype="multipart/form-data">

                Name
                <form:input path="name" id="productName" class="form-control "/> <form:errors path="name" cssStyle="color:#ff0000;"/>

                Description
                <form:textarea path = "description" id="description" class ="form-control"/> <form:errors path="description" cssStyle="color:#ff0000;"/>

                Quantité en stock
                <form:input path="stock" id="stock" class="form-control"/> <form:errors path="stock" cssStyle="color:#ff0000;"/>

                Prix
                <form:input path="price" id="price" class="form-control"/> <form:errors path="price" cssStyle="color:#ff0000;"/>

                Catégorie
                <form:select path="category">
                    <form:option value="-" label="--Please Select"/>
                    <form:options items="${categoryList}" itemValue="id" itemLabel="name"/>
                </form:select>

                Image
                <form:input id="image" path = "image" type="file" class="form:input-large"/>

            <input type="submit" value="Envoyer" class="btn btn-default">
            <a href="<c:url value="/admin/inventaire" />" class="btn btn-default">Annuler

        </form:form>

    <%@include file="/WEB-INF/views/template/footer.jsp" %>

I think the problem is that the form sends the id of the category to the controller, but it expects the object Category instead. I can't find a solution around it.

Body:
first of all you need to use @JoinColumn for mapping of @ManyToOne, for example you can use refer code :

@ManyToOne
@JoinColumn(name = "id")
private Category category;

then after get the category id into controller and find the category by id. now you have object of Category Entity, set the category Object into Product. and use cascade = CascadeType.ALL, fetch = FetchType.LAZY onto  ManyToOne relation.


问:
How do you get "You might also like" results from Foursquare's API based on a venue ID?
I'd like to get results like the following from Foursquare's API:

How do you get the "You might also like" venue list from Foursquare based on a particular venue ID?

答:
It is probably the venues/similar API.

Returns a list of venues similar to the specified venue.


问:
Map this/self of source to specific field in target in Orika
Let's have source classes

```<code>@Data
public class Source {
    private String name;
}

@Data
public class SourceParent {
    private String parentName;
}
</code>```

and target classes

```<code>@Data
public class Target {
    private String name;
    private TargetParent parent;
}

@Data
public class TargetParent {
    private String parentName;
}
</code>```

As you can see in Source I don't have the parent reference.

What I do is

```<code>Source s = findSource();
SourceParent sp = findParentForSource(s);
Target t = mapperFactory.map(s, Target.class);
mapperFactory.map(sp, t); //<--- Here is the problem
</code>```

The problem is that I cannot map a SourceParent object to a specific field in Target.
I know how to do this using custom mappers or another "manual" ways. Is there a way to do it "Orika way"?

Something like:

```<code> mapperFactory.classMap(SourceParent.class, Target.class)
    .fieldAtoB("?myslef?","parent")
    .register();
</code>```

答:
Try with </p>

```<code>mapperFactory.classMap(SourceParent.class, Target.class)
    .fieldAtoB("","parent")
    .register();
</code>```

Body:
Let's have source classes

@Data
public class Source {
    private String name;
}

@Data
public class SourceParent {
    private String parentName;
}

and target classes

@Data
public class Target {
    private String name;
    private TargetParent parent;
}

@Data
public class TargetParent {
    private String parentName;
}

As you can see in Source I don't have the parent reference.

What I do is

Source s = findSource();
SourceParent sp = findParentForSource(s);
Target t = mapperFactory.map(s, Target.class);
mapperFactory.map(sp, t); //<--- Here is the problem

The problem is that I cannot map a SourceParent object to a specific field in Target.
I know how to do this using custom mappers or another "manual" ways. Is there a way to do it "Orika way"?

Something like:

 mapperFactory.classMap(SourceParent.class, Target.class)
    .fieldAtoB("?myslef?","parent")
    .register();

Body:
Try with

mapperFactory.classMap(SourceParent.class, Target.class)
    .fieldAtoB("","parent")
    .register();


问:
Single Manifest file for different audio and video segments created using MP4Box (MPEG DASH)
I have three questions

1) Does dash.js support audio and video content multiplexed in a single segment?

2) If not how to merge audio.mpd and video.mpd created using MP4Box into a single out.mpd, that is supported by dash.js player?

3) It works if AdaptationSet is copied manually from audio.mpd and placed in video.mpd and video.mpd is played using dash.js. How to automate it?

```<code>MP4Box -dash 4000 -frag 4000 -rap -bs-switching no -profile dashavc264:live -segment-name ./video/segment_ -out video.mpd video.mp4#video

MP4Box -dash 4000 -frag 4000 -rap -bs-switching no -profile dashavc264:live -segment-name ./audio/segment_ -out audio.mpd video.mp4#audio
</code>```

答:
In order to produce one MPD file containing details about separate audio and video segments using MP4Box, just remove the -segment-name option and it's value. So your command should look like this

```<code>MP4Box -dash 4000 -frag 4000 -rap -bs-switching no -profile dashavc264:live
-url-template video.mp4 audio.mp4 -out manifest.mpd
</code>```

Body:
I have three questions

1) Does dash.js support audio and video content multiplexed in a single segment?

2) If not how to merge audio.mpd and video.mpd created using MP4Box into a single out.mpd, that is supported by dash.js player?

3) It works if AdaptationSet is copied manually from audio.mpd and placed in video.mpd and video.mpd is played using dash.js. How to automate it?

MP4Box -dash 4000 -frag 4000 -rap -bs-switching no -profile dashavc264:live -segment-name ./video/segment_ -out video.mpd video.mp4#video

MP4Box -dash 4000 -frag 4000 -rap -bs-switching no -profile dashavc264:live -segment-name ./audio/segment_ -out audio.mpd video.mp4#audio

Body:
In order to produce one MPD file containing details about separate audio and video segments using MP4Box, just remove the -segment-name option and it's value. So your command should look like this

MP4Box -dash 4000 -frag 4000 -rap -bs-switching no -profile dashavc264:live
-url-template video.mp4 audio.mp4 -out manifest.mpd


问:
.NET MVC issue with multiple routes
I have registered a route in my .NET MVC 5 application like this :

```<code> routes.MapRoute(
   "Books", // Route name
   "Books/{id}", // URL with parameters*
   new { controller = "Books", action = "Index", id =
   UrlParameter.Optional }
   );
</code>```

Now the web controller and action index is accessible through:

```<code>mylocalhost:8080/Books/50ShadesOfGrey
</code>```

What the problem now is I have another method where I post the data with this parameter like this:

```<code>  @if (Url.RequestContext.RouteData.Values["id"] != null)
   {
       @:DoScan('@Url.RequestContext.RouteData.Values["id"]');
   }
</code>```

DoScan is a javascript method which accepts the book name as parameter, which should then post the book name to this method I have in same controller (Books), which is defined like this:

```<code>  [HttpPost]
  public ActionResult LoadData(string bookName)
  {
   // method sould now be called but nothing happens??
  }
</code>```

I tested it without the route that I recently added and the post works just fine... But when I add this route it's like this LoadData HttpPost method gets ignored completely?? I feel like I should add another route in route config just for it, but I'm not really sure what to do here? Can someone help me out ?

P.S.

The route defined in the post method is like this:

```<code>/Books/LoadData/
</code>```

But the action never gets triggered?

P.S. The method gets called through datatables ajax call like this:

```<code> "ajax": {
           "url": "/Books/LoadData/",
           "type": "POST",
            "data": {
            "bookName": _bookName /*Parameter I passed through calling the function*/
           },
</code>```

答:
I bet you also have a default route in your config. So in actuality you have:

```<code>Books/{id}
{controller}/{action}/{id}
</code>```

MVC will pick the first that matches your request. Request in the post method is "Books/LoadData" with some data. What data exactly is there is not important, what is important is that it is not the part of the URL.

So "Books/LoadData" matches the first route, with "LoadData" being {id}. Thus your request goes to Index action, and LoadData action is not triggered.

Your intention was obviously to have this request captured with the default route, but again, MVC picks first that matches.

To fix this you need to either remove your route, or add a third one above it:

```<code>Books/LoadData
Books/{id}
{controller}/{action}/{id}
</code>```

Note that this new route does not have URL parameters, nor does it need any - data is being passed in the request body instead.

Title: .NET MVC issue with multiple routes

Body:
I have registered a route in my .NET MVC 5 application like this :

 routes.MapRoute(
   "Books", // Route name
   "Books/{id}", // URL with parameters*
   new { controller = "Books", action = "Index", id =
   UrlParameter.Optional }
   );

Now the web controller and action index is accessible through:

mylocalhost:8080/Books/50ShadesOfGrey

What the problem now is I have another method where I post the data with this parameter like this:

  @if (Url.RequestContext.RouteData.Values["id"] != null)
   {
       @:DoScan('@Url.RequestContext.RouteData.Values["id"]');
   }

DoScan is a javascript method which accepts the book name as parameter, which should then post the book name to this method I have in same controller (Books), which is defined like this:

  [HttpPost]
  public ActionResult LoadData(string bookName)
  {
   // method sould now be called but nothing happens??
  }

I tested it without the route that I recently added and the post works just fine... But when I add this route it's like this LoadData HttpPost method gets ignored completely?? I feel like I should add another route in route config just for it, but I'm not really sure what to do here? Can someone help me out ?

P.S.

The route defined in the post method is like this:

/Books/LoadData/

But the action never gets triggered?

P.S. The method gets called through datatables ajax call like this:

 "ajax": {
           "url": "/Books/LoadData/",
           "type": "POST",
            "data": {
            "bookName": _bookName /*Parameter I passed through calling the function*/
           },

Body:
I bet you also have a default route in your config. So in actuality you have:

Books/{id}
{controller}/{action}/{id}

MVC will pick the first that matches your request. Request in the post method is "Books/LoadData" with some data. What data exactly is there is not important, what is important is that it is not the part of the URL.

So "Books/LoadData" matches the first route, with "LoadData" being {id}. Thus your request goes to Index action, and LoadData action is not triggered.

Your intention was obviously to have this request captured with the default route, but again, MVC picks first that matches.

To fix this you need to either remove your route, or add a third one above it:

Books/LoadData
Books/{id}
{controller}/{action}/{id}

Note that this new route does not have URL parameters, nor does it need any - data is being passed in the request body instead.


问:
Seed Job environment variable ${WORKSPACE} is assigned to child jobs
Create a Seed Job using DSL that would create 5 Child Jobs. As part of build step I've to use ${WORKSPACE} environment variable, which should read the value from the slave machine where the child Job is running. But however when the child jobs are created, the workspace value is replaced with SeedJobs  workspace location from master server.

How would I restrict  seed job not to inject its ${WORKSPACE} value.

Could some one help me on this please.

Thanks
Mano

答:
To refer to the BUILD_NUMBER of the generated job in your job-dsl code, you should code it as follows :

```<code>"\${BUILD_NUMBER}"
</code>```

The important part is the \ before the $ sign which prevents the evaluation of the BUILD_NUMBER variable as it pertains to the Goovy runtime that is (likely) your Jenkins job-dsl seed job.

The config.xml of the generated job will contain ${BUILD_NUMBER} instead of a digit that represents you build number of your seed-job. And then your generated job will evaluate that when it runs.

Body:
To refer to the BUILD_NUMBER of the generated job in your job-dsl code, you should code it as follows :

"\${BUILD_NUMBER}"

The important part is the \ before the $ sign which prevents the evaluation of the BUILD_NUMBER variable as it pertains to the Goovy runtime that is (likely) your Jenkins job-dsl seed job.

The config.xml of the generated job will contain ${BUILD_NUMBER} instead of a digit that represents you build number of your seed-job. And then your generated job will evaluate that when it runs.


问:
DUMP(A) opcode in RPG
There is an error handling procedure that I need to write up in a module that will be called from other programs bound to the module when there is a program error. This needs to include the statement to take a DUMP. My question is suppose the call to this procedure goes from program A to Module B (to which A is bound through a service program also the Module has the error handler procedure with a Sumo statement), will the Dump work as expected?Should the dump be included in the caller program to get the dump of the correct process? Or would it work if included in the Called procedure?</p>

答:
The DUMP opcode dumps the values for the variables in automatic storage for all the procedures in the module, but the values listed in the dump are only valid if the procedure is active.

So if you want the dump to show the correct values for the automatic variables in the called procedure, you should do the DUMP from the called procedure.

Title: DUMP(A) opcode in RPG


问:
Operating on arrays using Unsigned Values
I have been generating a C function from Matlab Coder environnement in order to implement it in an other software called MAX/MSP.
I'm trying to make sense of it, thanks to my poor level in C programming, and there is some syntax elements I can't understand: the use of unsigned values like 0U or 1U to pass arrays.

The next example doesn't do anything. Pasting the entire code wouldn't help much, unless you think so.

```<code>void function1(const double A[49], double B[50])
{
  function2( (double *)&A[0U] );
}

static void function2(const double A[])
{

}
</code>```

While doing some math, Matlab wrote something like:

```<code>b = 2;
f[1U] += b;
</code>```

I don't understand the use of unsigned value either...

Thanks a lot!

答:
For a[n], array indexes are always non-negative values, from 0 to n-1.  Appending a u to a decimal constant poses no problem for indexing an array, yet does offer a benefit: it insures that the value is of minimal type width and of some unsigned type.

Automated generation of a fixed index like with Matlab benefits by using a u suffix.

Consider small and large values on a 32-bit unsigned/int/long/size_t system

```<code>aweeu[0u];           // `0u` is 32-bit `unsigned`.
aweenou[0];          // `0` is 32-bit `int`.
abigu[3000000000u];  // `3000000000u` is a 32-bit `unsigned`.
abignou[3000000000]; // `3000000000` is a 64-bit `long long`.
</code>```

Is this of value?  Perhaps.  Some compiles make look at the value first and see that all above are in range of size_t and not complain.  Others may complain about an index of type long long or possible even int.  By appending the u, such rare complaints do not occur.

Body:
I have been generating a C function from Matlab Coder environnement in order to implement it in an other software called MAX/MSP.
I'm trying to make sense of it, thanks to my poor level in C programming, and there is some syntax elements I can't understand: the use of unsigned values like 0U or 1U to pass arrays.

The next example doesn't do anything. Pasting the entire code wouldn't help much, unless you think so.

void function1(const double A[49], double B[50])
{
  function2( (double *)&A[0U] );
}

static void function2(const double A[])
{

}

While doing some math, Matlab wrote something like:

b = 2;
f[1U] += b;

I don't understand the use of unsigned value either...

Thanks a lot!

Body:
For a[n], array indexes are always non-negative values, from 0 to n-1.  Appending a u to a decimal constant poses no problem for indexing an array, yet does offer a benefit: it insures that the value is of minimal type width and of some unsigned type.

Automated generation of a fixed index like with Matlab benefits by using a u suffix.

Consider small and large values on a 32-bit unsigned/int/long/size_t system

aweeu[0u];           // `0u` is 32-bit `unsigned`.
aweenou[0];          // `0` is 32-bit `int`.
abigu[3000000000u];  // `3000000000u` is a 32-bit `unsigned`.
abignou[3000000000]; // `3000000000` is a 64-bit `long long`.

Is this of value?  Perhaps.  Some compiles make look at the value first and see that all above are in range of size_t and not complain.  Others may complain about an index of type long long or possible even int.  By appending the u, such rare complaints do not occur.


问:
How To Properly Create a Histogram: Displaying the Frequency of the Tweets for Each Day Spanning 2 Years
Unfortunately, I'm not experienced at all with matplotlib (and similar libraries), and I find some of the avaiable tutorials confusing.

This is my problem:

I have list of timestamps in string format, like this:

```<code>timestamp_list = ['2017-01-30 23:45', '2017-01-30 20:30', '2017-01-30 18:22', '2017-01-29 17:39', '2017-01-29 15:39', '2017-01-29 14:45', '2017-01-29 11:51', '2017-01-29 11:15', '2017-01-29 09:41', '2017-01-30 05:54', '2017-01-29 03:10']
</code>```

Each timestamp represents a tweet. I would like to build a histogram similar to this, but grouping my tweets per day. So, ultimately, I would like this histogram to show how many tweets are being tweeted on a daily basis from my list.

I have no idea how to group these tweets day by day (or any other grouping, i.e. monthly). I don't know which is the most easy and painless way to do it, and most importantly, when I'm reading posts on how to use matplotlib to create histograms (and similar things, like CDFs), I don't understand what each line specifically does, and thus, I cannot edit these posts according to my needs and expand my knowledge.

Can someone please provide a sample solution of to create such a histogram using matplotlib (or similar), but also comment each line so that I can fully understand how to produce similar plots in the future?

Thank you.

EDIT: I think that my original question wasn't clear enough, since none of the solutions suggested solve my problem. I'm sorry for not being more explicit. I will try to elaborate:

Let's say that I have a set of tweets of a specific topic spanning a duration of two years. This sums up to 730 days. timestamp_list is a list containing the unique timestamps of each tweet, in string format.

Every day in the duration of these two years is a unique day. That means that I have 730 unique days. What I want is to find out how many tweets of that specific topic were tweeted on every day of the 730 days. For instance, on 2017-01-20 there might have been 10 tweets, on 2017-01-21 45 tweets, and so on. I would like to create a histogram based on this. Some people suggested creating a dictionary.

How can I create a dictionary containing 730 keys and their respective number of tweets?

How can I plot a histogram based on the previous dictionary?

Or, if there is another, more efficient way to do (instead of using dictionaries), it's also welcome.

What I want is to somehow take this string list and create a histogram, like this, showing the number of tweets tweeted on a daily basis, spanning the duration of the dates (in my case, 2 years).

Bounty:

Thank you all for your submissions. Both @cphlewis' and @TobiasRibizel' answers are correct. However, I'm inclined to pick @TobiasRibizel' answer as the winning answer, since it doesn't use third party libraries, it is very well explained, and it produces a very nice histogram, just like the one I asked. Thank you.

答:
Histograms are quite easy to do in matplotlib:

```<code>import matplotlib.pyplot as plt
# generate data in list form here
plt.hist(list)
plt.show()
</code>```

You can set number of bins by doing plt.hist(list, bins=desired number)

I'm not sure how matplotlib will handle the date strings, but what you could do is set a start date to be 0 and every other date is x (days after day 0). Then you can adjust number of bins so that 1 bin corresponds to one day.

Body:
Unfortunately, I'm not experienced at all with matplotlib (and similar libraries), and I find some of the avaiable tutorials confusing.

This is my problem:

I have list of timestamps in string format, like this:

timestamp_list = ['2017-01-30 23:45', '2017-01-30 20:30', '2017-01-30 18:22', '2017-01-29 17:39', '2017-01-29 15:39', '2017-01-29 14:45', '2017-01-29 11:51', '2017-01-29 11:15', '2017-01-29 09:41', '2017-01-30 05:54', '2017-01-29 03:10']

Each timestamp represents a tweet. I would like to build a histogram similar to this, but grouping my tweets per day. So, ultimately, I would like this histogram to show how many tweets are being tweeted on a daily basis from my list.

I have no idea how to group these tweets day by day (or any other grouping, i.e. monthly). I don't know which is the most easy and painless way to do it, and most importantly, when I'm reading posts on how to use matplotlib to create histograms (and similar things, like CDFs), I don't understand what each line specifically does, and thus, I cannot edit these posts according to my needs and expand my knowledge.

Can someone please provide a sample solution of to create such a histogram using matplotlib (or similar), but also comment each line so that I can fully understand how to produce similar plots in the future?

Thank you.

EDIT: I think that my original question wasn't clear enough, since none of the solutions suggested solve my problem. I'm sorry for not being more explicit. I will try to elaborate:

Let's say that I have a set of tweets of a specific topic spanning a duration of two years. This sums up to 730 days. timestamp_list is a list containing the unique timestamps of each tweet, in string format.

Every day in the duration of these two years is a unique day. That means that I have 730 unique days. What I want is to find out how many tweets of that specific topic were tweeted on every day of the 730 days. For instance, on 2017-01-20 there might have been 10 tweets, on 2017-01-21 45 tweets, and so on. I would like to create a histogram based on this. Some people suggested creating a dictionary.

How can I create a dictionary containing 730 keys and their respective number of tweets?

How can I plot a histogram based on the previous dictionary?

Or, if there is another, more efficient way to do (instead of using dictionaries), it's also welcome.

What I want is to somehow take this string list and create a histogram, like this, showing the number of tweets tweeted on a daily basis, spanning the duration of the dates (in my case, 2 years).

Bounty:

Thank you all for your submissions. Both @cphlewis' and @TobiasRibizel' answers are correct. However, I'm inclined to pick @TobiasRibizel' answer as the winning answer, since it doesn't use third party libraries, it is very well explained, and it produces a very nice histogram, just like the one I asked. Thank you.

Body:
Histograms are quite easy to do in matplotlib:

import matplotlib.pyplot as plt
# generate data in list form here
plt.hist(list)
plt.show()

You can set number of bins by doing plt.hist(list, bins=desired number)

I'm not sure how matplotlib will handle the date strings, but what you could do is set a start date to be 0 and every other date is x (days after day 0). Then you can adjust number of bins so that 1 bin corresponds to one day.


问:
Get id of previous select tag
I have next structure:

```<code><div class="input_fields_wrap">
  <div class="row">
    <select id="house-1-room-1"><?php echo $options; ?></select>
    <input type='text' class='name' name='house-1-room-size-1' placeholder='Room Size'>
  </div>
</div>
<button class="add_field_button">Add Another Room</button>
</code>```

When  add_field_button clicked, I am trying to get the id of previous select tag, in my case it is house-1-room-1 with jquery (or vanila js).

I've tried:

```<code>$(this).parent().prev("select").attr('id');
</code>```

and

```<code>$(this).prev("div").closest("select").attr('id');
</code>```

And many other combination of above to no avail.

Please help!

答:
Use:

```<code>$(this).prev("div").find("select").attr('id');
</code>```

.closest() goes up in the DOM hierarchy, find() searches down the hierarchy.

Title: Get id of previous select tag

Body:
I have next structure:

    <select id="house-1-room-1"><?php echo $options; ?></select>
    <input type='text' class='name' name='house-1-room-size-1' placeholder='Room Size'>

<button class="add_field_button">Add Another Room</button>

When  add_field_button clicked, I am trying to get the id of previous select tag, in my case it is house-1-room-1 with jquery (or vanila js).

I've tried:

$(this).parent().prev("select").attr('id');

and

$(this).prev("div").closest("select").attr('id');

And many other combination of above to no avail.

Please help!

Body:
Use:

$(this).prev("div").find("select").attr('id');

.closest() goes up in the DOM hierarchy, find() searches down the hierarchy.


问:
$stateProvider broke when I changed config to factory
If I use "config" instead of "factory", the dependency injection doesn't work in production (on heroku). So I changed it to factory and now the stateProvider doesn't work.</p>

```<code>.factory('AboutService', AboutService);

AboutService.$inject = ['$stateProvider'];

function AboutService($stateProvider) {
  $stateProvider
  .state('about', {
    url: '/about',
    template: '<about></about>'
  });
}
</code>```

答:
config and factory aren't interchangeable and cannot be swapped blindly.

The proper way is

```<code>.config(AboutService);

AboutService.$inject = ['$stateProvider'];

function AboutService($stateProvider) {
  $stateProvider
  .state('about', {
    url: '/about',
    template: '<about></about>'
  });
}
</code>```

Just 1 argument for config, AboutService function. The code above is environment independent.

Body:
If I use "config" instead of "factory", the dependency injection doesn't work in production (on heroku). So I changed it to factory and now the stateProvider doesn't work.

.factory('AboutService', AboutService);

AboutService.$inject = ['$stateProvider'];

function AboutService($stateProvider) {
  $stateProvider
  .state('about', {
    url: '/about',
    template: '<about></about>'
  });
}

Body:
config and factory aren't interchangeable and cannot be swapped blindly.

The proper way is

.config(AboutService);

AboutService.$inject = ['$stateProvider'];

function AboutService($stateProvider) {
  $stateProvider
  .state('about', {
    url: '/about',
    template: '<about></about>'
  });
}

Just 1 argument for config, AboutService function. The code above is environment independent.


问:
Split a list in several files scala
I have the following list,

```<code>10,44,22
10,47,12
15,38,3
15,41,30
16,44,15
16,47,18
22,38,21
22,41,42
34,44,40
34,47,36
40,38,39
40,41,42
45,38,27
45,41,30
46,44,45
46,47,48
</code>```

Then I am creating one file with it is content with the following code:

```<code>  val fstream:FileWriter = new FileWriter("patSPO.csv")
  var out:BufferedWriter = new BufferedWriter(fstream)

  val sl = listSPO.sortBy(l => (l.sub, l.pre))
  for ( a <- 0 to listSPO.size-1){
    out.write(sl(a).sub.toString+","+sl(a).pre.toString+","+sl(a).obj.toString+"\n")
  }
  out.close()
</code>```

However I want to divide the content in a n files, then I try the following for 4 files:

```<code>  val fstream:FileWriter = new FileWriter("patSPO.csv")
  val fstream1:FileWriter = new FileWriter("patSPO1.csv")
  val fstream2:FileWriter = new FileWriter("patSPO2.csv")
  val fstream3:FileWriter = new FileWriter("patSPO3.csv")
  val fstream4:FileWriter = new FileWriter("patSPO4.csv")
  var out:BufferedWriter = new BufferedWriter(fstream)
  var out1:BufferedWriter = new BufferedWriter(fstream1)
  var out2:BufferedWriter = new BufferedWriter(fstream2)
  var out3:BufferedWriter = new BufferedWriter(fstream3)
  var out4:BufferedWriter = new BufferedWriter(fstream4)
  val b :Int = listSPO.size/4
  val sl = listSPO.sortBy(l => (l.sub, l.pre))
  for ( a <- 0 to listSPO.size-1){
    out.write(sl(a).sub.toString+","+sl(a).pre.toString+","+sl(a).obj.toString+"\n")
  }
  for ( a <- 0 to b-1){
    out1.write(sl(a).sub.toString+","+sl(a).pre.toString+","+sl(a).obj.toString+"\n")
  }
  for ( a <- b to (b*2)-1){
    out2.write(sl(a).sub.toString+","+sl(a).pre.toString+","+sl(a).obj.toString+"\n")
  }
  for ( a <- b*2 to (b*3)-1){
    out3.write(sl(a).sub.toString+","+sl(a).pre.toString+","+sl(a).obj.toString+"\n")
  }
  for ( a <- b*3 to (b*4)-1){
    out4.write(sl(a).sub.toString+","+sl(a).pre.toString+","+sl(a).obj.toString+"\n")
  }

  out.close()
  out1.close()
  out2.close()
  out3.close()
  out4.close()
</code>```

Then my question is if exist a general code where I put the number of files to generate, for example 32, and not to write 32 times the out, the for and the fstream?

答:
First, let's make some utilities to eliminate ugly boilerplate:

```<code>def open(
 number: Int = 1,
 prefix: String,
 ext: String
) = (0 to n-1)
  .iterator
  .map { i =>
   "%s%s%s".format(prefix, if(i == 0) "" else i.toString, postfix)
  }.map(new FileWriter(_))
   .map(new BufferedWriter(_))

def toString(l: WhateverTheType) = Seq(
  l.sub,
  l.pre,
  l.obj
).mkString(",") + "\n"
</code>```

And now to the implementation:

```<code>writeToFiles(
  listSPO: List[WhateverTheType],
  numFiles: Int = 1,
  prefix: String = "pasSPO",
 ext: String = ".csv"
) = listSPO
  .grouped((listSPO.size+1)/numFiles)
  .zip(open(numFiles, prefix, ext))
  .foreach { case (input, file) =>
    try {
     input.foreach(file.write(toString(input)))
    } finally {
      file.close
    }
  }
</code>```

Title: Split a list in several files scala

Body:
I have the following list,

10,44,22
10,47,12
15,38,3
15,41,30
16,44,15
16,47,18
22,38,21
22,41,42
34,44,40
34,47,36
40,38,39
40,41,42
45,38,27
45,41,30
46,44,45
46,47,48

Then I am creating one file with it is content with the following code:

  val fstream:FileWriter = new FileWriter("patSPO.csv")
  var out:BufferedWriter = new BufferedWriter(fstream)

  val sl = listSPO.sortBy(l => (l.sub, l.pre))
  for ( a <- 0 to listSPO.size-1){
    out.write(sl(a).sub.toString+","+sl(a).pre.toString+","+sl(a).obj.toString+"\n")
  }
  out.close()

However I want to divide the content in a n files, then I try the following for 4 files:

  val fstream:FileWriter = new FileWriter("patSPO.csv")
  val fstream1:FileWriter = new FileWriter("patSPO1.csv")
  val fstream2:FileWriter = new FileWriter("patSPO2.csv")
  val fstream3:FileWriter = new FileWriter("patSPO3.csv")
  val fstream4:FileWriter = new FileWriter("patSPO4.csv")
  var out:BufferedWriter = new BufferedWriter(fstream)
  var out1:BufferedWriter = new BufferedWriter(fstream1)
  var out2:BufferedWriter = new BufferedWriter(fstream2)
  var out3:BufferedWriter = new BufferedWriter(fstream3)
  var out4:BufferedWriter = new BufferedWriter(fstream4)
  val b :Int = listSPO.size/4
  val sl = listSPO.sortBy(l => (l.sub, l.pre))
  for ( a <- 0 to listSPO.size-1){
    out.write(sl(a).sub.toString+","+sl(a).pre.toString+","+sl(a).obj.toString+"\n")
  }
  for ( a <- 0 to b-1){
    out1.write(sl(a).sub.toString+","+sl(a).pre.toString+","+sl(a).obj.toString+"\n")
  }
  for ( a <- b to (b*2)-1){
    out2.write(sl(a).sub.toString+","+sl(a).pre.toString+","+sl(a).obj.toString+"\n")
  }
  for ( a <- b*2 to (b*3)-1){
    out3.write(sl(a).sub.toString+","+sl(a).pre.toString+","+sl(a).obj.toString+"\n")
  }
  for ( a <- b*3 to (b*4)-1){
    out4.write(sl(a).sub.toString+","+sl(a).pre.toString+","+sl(a).obj.toString+"\n")
  }

  out.close()
  out1.close()
  out2.close()
  out3.close()
  out4.close()

Then my question is if exist a general code where I put the number of files to generate, for example 32, and not to write 32 times the out, the for and the fstream?

Body:
First, let's make some utilities to eliminate ugly boilerplate:

def open(
 number: Int = 1,
 prefix: String,
 ext: String
) = (0 to n-1)
  .iterator
  .map { i =>
   "%s%s%s".format(prefix, if(i == 0) "" else i.toString, postfix)
  }.map(new FileWriter(_))
   .map(new BufferedWriter(_))

def toString(l: WhateverTheType) = Seq(
  l.sub,
  l.pre,
  l.obj
).mkString(",") + "\n"

And now to the implementation:

writeToFiles(
  listSPO: List[WhateverTheType],
  numFiles: Int = 1,
  prefix: String = "pasSPO",
 ext: String = ".csv"
) = listSPO
  .grouped((listSPO.size+1)/numFiles)
  .zip(open(numFiles, prefix, ext))
  .foreach { case (input, file) =>
    try {
     input.foreach(file.write(toString(input)))
    } finally {
      file.close
    }
  }


答:
Need to use find():

```<code>$(this).prev("div").find("select").attr('id');
</code>```

The .closest() is the opposite, goes from bottom to top. While .find() will go from the current place inside the hierarchy.

Title: Get id of previous select tag

Body:
Need to use find():

$(this).prev("div").find("select").attr('id');

The .closest() is the opposite, goes from bottom to top. While .find() will go from the current place inside the hierarchy.


问:
How to find if an array is strictly in an increasing order after omitting only one element
I have given the following problem where I am stuck right now. I am not having the perfect logic for this. Here is the problem below :

Given a sequence of integers as an array, determine whether it is
  possible to obtain a strictly increasing sequence by removing no more than one element from the array.

Example 1:

```<code>For sequence = [1, 3, 2, 1], the output should be false.
There is no one element that can be removed to get a strictly an increasing sequence
</code>```

Example 2:

```<code>For sequence = [1, 3, 2], the output should be true.
You can remove 3 or 2 to get the strictly increasing sequence [1, 2] or [1,3] respectively
</code>```

I have tried as follows :

```<code>boolean almostIncreasingSequence(int[] sequence) {
    ArrayList<Integer> list = new ArrayList<>();

    for(int i=0; i<sequence.length;i++) {
        list.add(sequence[i]);
    }

    int omittedCounter = 0;

    boolean status = true;

    for(int i=1; i<list.size();i++) {
        if(list.get(i-1) >= list.get(i)) {
            omittedCounter ++;
            list.remove(i-1);
            break;
        }
    }

    if (omittedCounter > 0) {
        for(int i=1; i<list.size();i++) {
            if(list.get(i-1) >= list.get(i)) {
                omittedCounter ++;
                list.remove(i-1);
                break;
            }
        }
    }

    if (omittedCounter > 1) {
        status = false;
    }

    return status;
}
</code>```

But I am having trouble when I am given this sequence: [1, 2, 3, 4, 3, 6]

```<code>Output:           false
Expected Output:  true
</code>```

答:
This is possible in linear time O(n) and constant space O(1).

```<code>public static boolean analyse(int[] sequence) {
    if (sequence.length <= 2) return true;
    int a = sequence[0];
    int b = sequence[1];
    int drops = 0;
    if (a >= b) {
        drops++;
        a = b - 1; //drop a, keeping the smallest, fake a value for the first loop
    }
    // consider 3 items at a time, a, b & c
    for (int i = 2; i < sequence.length; i++) {
        int c = sequence[i];
        if (a < b && b < c) {
            // all good, move on
            a = b;
            b = c;
            continue;
        }
        // we'll have to drop one of them
        drops++;
        if (drops > 1) return false;
        // which one will we drop, b or c?
        if (a < c) {
            // drop b (a,b -> a,c)
            b = c;
        } // else drop c (a,b -> a,b)
    }
    return true;
}
</code>```

Body:
I have given the following problem where I am stuck right now. I am not having the perfect logic for this. Here is the problem below :

Given a sequence of integers as an array, determine whether it is
  possible to obtain a strictly increasing sequence by removing no more than one element from the array.

Example 1:

For sequence = [1, 3, 2, 1], the output should be false.
There is no one element that can be removed to get a strictly an increasing sequence

Example 2:

For sequence = [1, 3, 2], the output should be true.
You can remove 3 or 2 to get the strictly increasing sequence [1, 2] or [1,3] respectively

I have tried as follows :

boolean almostIncreasingSequence(int[] sequence) {
    ArrayList<Integer> list = new ArrayList<>();

    for(int i=0; i<sequence.length;i++) {
        list.add(sequence[i]);
    }

    int omittedCounter = 0;

    boolean status = true;

    for(int i=1; i<list.size();i++) {
        if(list.get(i-1) >= list.get(i)) {
            omittedCounter ++;
            list.remove(i-1);
            break;
        }
    }

    if (omittedCounter > 0) {
        for(int i=1; i<list.size();i++) {
            if(list.get(i-1) >= list.get(i)) {
                omittedCounter ++;
                list.remove(i-1);
                break;
            }
        }
    }

    if (omittedCounter > 1) {
        status = false;
    }

    return status;
}

But I am having trouble when I am given this sequence: [1, 2, 3, 4, 3, 6]

Output:           false
Expected Output:  true

Body:
This is possible in linear time O(n) and constant space O(1).

public static boolean analyse(int[] sequence) {
    if (sequence.length <= 2) return true;
    int a = sequence[0];
    int b = sequence[1];
    int drops = 0;
    if (a >= b) {
        drops++;
        a = b - 1; //drop a, keeping the smallest, fake a value for the first loop
    }
    // consider 3 items at a time, a, b & c
    for (int i = 2; i < sequence.length; i++) {
        int c = sequence[i];
        if (a < b && b < c) {
            // all good, move on
            a = b;
            b = c;
            continue;
        }
        // we'll have to drop one of them
        drops++;
        if (drops > 1) return false;
        // which one will we drop, b or c?
        if (a < c) {
            // drop b (a,b -> a,c)
            b = c;
        } // else drop c (a,b -> a,b)
    }
    return true;
}


问:
app:layout_marginBottom is not working well with android constraint layout
Is there any reason why the following layout_marginBottom is not working?
However, if I use layout_marginTop on the second view it does work well</p>

```<code><android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ade4ad">
    <TextView
        android:id="@+id/first"
        android:layout_width="90dp"
        android:layout_height="40dp"
        app:layout_marginBottom="10dp"
        android:background="#000"/>
    <TextView
        android:id="@+id/second"
        android:layout_width="90dp"
        android:layout_height="40dp"
        android:background="#fff"
        app:layout_constraintTop_toBottomOf="@+id/first"/>
</android.support.constraint.ConstraintLayout>
</code>```

答:
This is not LinearLayout or RelativeLayout, its ConstraintLayout so you have to give Left, Right, Bottom, Top Constraint to Relevant Layout, in your case You have to give TextView first Bottom_Top Constraint to TextView second. so you can get Margin between Two TextView.

Your layout should be like below.

```<code><android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ade4ad">
    <TextView
        android:id="@+id/first"
        android:layout_width="90dp"
        android:layout_height="40dp"
        android:background="#000"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent" />
    <TextView
        android:id="@+id/second"
        android:layout_width="90dp"
        android:layout_height="40dp"
        android:background="#fff"
        android:layout_marginTop="10dp"
        app:layout_constraintTop_toBottomOf="@+id/first"
        app:layout_constraintLeft_toLeftOf="@+id/first"
        app:layout_constraintRight_toRightOf="@+id/first" />
</android.support.constraint.ConstraintLayout>
</code>```

Body:
Is there any reason why the following layout_marginBottom is not working?
However, if I use layout_marginTop on the second view it does work well

<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ade4ad">
    <TextView
        android:id="@+id/first"
        android:layout_width="90dp"
        android:layout_height="40dp"
        app:layout_marginBottom="10dp"
        android:background="#000"/>
    <TextView
        android:id="@+id/second"
        android:layout_width="90dp"
        android:layout_height="40dp"
        android:background="#fff"
        app:layout_constraintTop_toBottomOf="@+id/first"/>
</android.support.constraint.ConstraintLayout>

Body:
This is not LinearLayout or RelativeLayout, its ConstraintLayout so you have to give Left, Right, Bottom, Top Constraint to Relevant Layout, in your case You have to give TextView first Bottom_Top Constraint to TextView second. so you can get Margin between Two TextView.

Your layout should be like below.

<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ade4ad">
    <TextView
        android:id="@+id/first"
        android:layout_width="90dp"
        android:layout_height="40dp"
        android:background="#000"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent" />
    <TextView
        android:id="@+id/second"
        android:layout_width="90dp"
        android:layout_height="40dp"
        android:background="#fff"
        android:layout_marginTop="10dp"
        app:layout_constraintTop_toBottomOf="@+id/first"
        app:layout_constraintLeft_toLeftOf="@+id/first"
        app:layout_constraintRight_toRightOf="@+id/first" />
</android.support.constraint.ConstraintLayout>


问:
Insert data to MySql with loop instead of one by one
My Html code is below:

```<code><form name="creditAssessPage2" id="basicform" method="post" action="post.php" enctype="multipart/form-data">
    <tr>
        <td><input type="text" name="finanIns1" id="finanIns1" value=""></td>

        <td id="balance"><input type="number" name="balance1" id="balance1" value="" min="0"></td>
        <td id="MonthyComm"><input type="number" name="monthlyComm1" id="monthlyComm1" value="" min="0"></td>
    </tr>
    <tr>
        <td><input type="text" name="finanIns2" id="finanIns2" value=""></td>

        <td id="balance"><input type="number" name="balance2" id="balance2" value="" min="0"></td>
        <td id="MonthyComm"><input type="number" name="monthlyComm2" id="monthlyComm2" value="" min="0"></td>
    </tr>
    <tr>
        <td><input type="text" name="finanIns3" id="finanIns3" value=""></td>

        <td id="balance"><input type="number" name="balance3" id="balance3" value="" min="0"></td>
        <td id="MonthyComm"><input type="number" name="monthlyComm3" id="monthlyComm3" value="" min="0"></td>
    </tr>
    <tr>

</form>
</code>```

My post.php code is below:

```<code>    require_once 'db/dbfunction.php';
    require_once 'db/dbCreditAssessment.php';

    session_start();
    $con = open_connection();
$finanIns1 = $_POST['finanIns1'];
$balance1 = $_POST['balance1'];
$monthlyComm1 = $_POST['monthlyComm1'];

$finanIns2 = $_POST['finanIns2'];
$balance2 = $_POST['balance2'];
$monthlyComm2 = $_POST['monthlyComm2'];

$finanIns3 = $_POST['finanIns3'];
$balance3 = $_POST['balance3'];
$monthlyComm3 = $_POST['monthlyComm3'];

addemployementdetails($con,$finanIns1,$balance1,$monthlyComm1);
addemployementdetails($con,$finanIns2,$balance2,$monthlyComm2);
addemployementdetails($con,$finanIns3,$balance3,$monthlyComm3);

close_connection($con);
</code>```

my dbCreditAssessment.php code is below:

```<code>function addemployementdetails($con,$finanIns1,$balance1,$monthlyComm1){

    $query = "insert into employementdetails(finance,balance,monthlycomm)
            values('$finanIns1','$balance1','$monthlyComm1')";
                 //echo "{$sqlString}";

                 $insertResult = mysqli_query($con, $query);

                 if($insertResult){
                     echo " Applicant Detail Added !<br />";
                     echo "<a href='index.php'>Back to Home</a>";
                 }
                 else {
                     echo " Error !";
                     echo "{$query}";
                     //header('Location: post.php');
                 }
}
</code>```

this function will repeat 3 times.
Actually, there are a lot more of the same fields to key in. e.g. finanIns1, finanIns2, finanIns3, finanIns4, finanIns5, ect.

Is there any way to use a loop to replace this way of inserting data?
Also, if the fields are empty, the data will not be inserted to Mysql

答:
First, count the finanIns occurrence in the $_POST array. Then use 'for' function to loop it.

```<code>$count = count(preg_grep("/^finanIns[\d]*/", array_keys($_POST)));

for($i = 1; $i <= $count; $i++){
    $finanIns = $_POST['finanIns'.$i];
    $balance = $_POST['balance'.$i];
    $monthlyComm = $_POST['monthlyComm'.$i];

    addemployementdetails($con,$finanIns,$balance,$monthlyComm);
}
</code>```

Remember to sanitize those inputs using mysqli_real_escape_string and trim. Change your code to this:

```<code>$count = count(preg_grep("/^finanIns[\d]*/", array_keys($_POST)));

for($i = 1; $i <= $count; $i++){
    $finanIns = trim(mysqli_real_escape_string($_POST['finanIns'.$i]));
    $balance = trim(mysqli_real_escape_string($_POST['balance'.$i]));
    $monthlyComm = trim(mysqli_real_escape_string($_POST['monthlyComm'.$i]));

    addemployementdetails($con,$finanIns,$balance,$monthlyComm);
}
</code>```

Body:
My Html code is below:

<form name="creditAssessPage2" id="basicform" method="post" action="post.php" enctype="multipart/form-data">

        <input type="text" name="finanIns1" id="finanIns1" value="">

        <input type="number" name="balance1" id="balance1" value="" min="0">
        <input type="number" name="monthlyComm1" id="monthlyComm1" value="" min="0">

        <input type="text" name="finanIns2" id="finanIns2" value="">

        <input type="number" name="balance2" id="balance2" value="" min="0">
        <input type="number" name="monthlyComm2" id="monthlyComm2" value="" min="0">

        <input type="text" name="finanIns3" id="finanIns3" value="">

        <input type="number" name="balance3" id="balance3" value="" min="0">
        <input type="number" name="monthlyComm3" id="monthlyComm3" value="" min="0">

</form>

My post.php code is below:

    require_once 'db/dbfunction.php';
    require_once 'db/dbCreditAssessment.php';

    session_start();
    $con = open_connection();
$finanIns1 = $_POST['finanIns1'];
$balance1 = $_POST['balance1'];
$monthlyComm1 = $_POST['monthlyComm1'];

$finanIns2 = $_POST['finanIns2'];
$balance2 = $_POST['balance2'];
$monthlyComm2 = $_POST['monthlyComm2'];

$finanIns3 = $_POST['finanIns3'];
$balance3 = $_POST['balance3'];
$monthlyComm3 = $_POST['monthlyComm3'];

addemployementdetails($con,$finanIns1,$balance1,$monthlyComm1);
addemployementdetails($con,$finanIns2,$balance2,$monthlyComm2);
addemployementdetails($con,$finanIns3,$balance3,$monthlyComm3);

close_connection($con);

my dbCreditAssessment.php code is below:

function addemployementdetails($con,$finanIns1,$balance1,$monthlyComm1){

    $query = "insert into employementdetails(finance,balance,monthlycomm)
            values('$finanIns1','$balance1','$monthlyComm1')";
                 //echo "{$sqlString}";

                 $insertResult = mysqli_query($con, $query);

                 if($insertResult){
                     echo " Applicant Detail Added !
";
                     echo "Back to Home";
                 }
                 else {
                     echo " Error !";
                     echo "{$query}";
                     //header('Location: post.php');
                 }
}

this function will repeat 3 times.
Actually, there are a lot more of the same fields to key in. e.g. finanIns1, finanIns2, finanIns3, finanIns4, finanIns5, ect.

Is there any way to use a loop to replace this way of inserting data?
Also, if the fields are empty, the data will not be inserted to Mysql

Body:
First, count the finanIns occurrence in the $_POST array. Then use 'for' function to loop it.

$count = count(preg_grep("/^finanIns[\d]*/", array_keys($_POST)));

for($i = 1; $i <= $count; $i++){
    $finanIns = $_POST['finanIns'.$i];
    $balance = $_POST['balance'.$i];
    $monthlyComm = $_POST['monthlyComm'.$i];

    addemployementdetails($con,$finanIns,$balance,$monthlyComm);
}

Remember to sanitize those inputs using mysqli_real_escape_string and trim. Change your code to this:

$count = count(preg_grep("/^finanIns[\d]*/", array_keys($_POST)));

for($i = 1; $i <= $count; $i++){
    $finanIns = trim(mysqli_real_escape_string($_POST['finanIns'.$i]));
    $balance = trim(mysqli_real_escape_string($_POST['balance'.$i]));
    $monthlyComm = trim(mysqli_real_escape_string($_POST['monthlyComm'.$i]));

    addemployementdetails($con,$finanIns,$balance,$monthlyComm);
}


问:
How to prevent direct access to files but allow files in webpages
I'm trying to use mod.rewrite to deny direct access to files on my web server, e.g. http://domain.tld/reports/imareport.pdf or http://domain.tld/img/img1.png, and I've used the answer on this question:

(htaccess) How to prevent a file from DIRECT URL ACCESS?

That page suggests using mod.rewrite like this:

```<code>RewriteEngine on
RewriteRule \.(png|pdf|htm)$ - [F]
</code>```

Using mod.rewrite in this manner works fine for denying access to PDFs, but other files that are ordinarily included in a page such as images and css are not only blocked from direct access, but also blocked when used on a webpage in a normal  tag or whatever.  This is contrary to the question and answer mentioned above.

So... my question is... is there a way to block direct access to files but still allow them in webpages?

答:
Thanks Mark Phillips, I didn't fully appreciate what these two rewrite conditions were doing for me:

```<code>RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost [NC]
RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost.*$ [NC]
</code>```

So I had managed to mess them up.  Things worked as needed when I used the code just as it was.

Body:
I'm trying to use mod.rewrite to deny direct access to files on my web server, e.g. http://domain.tld/reports/imareport.pdf or http://domain.tld/img/img1.png, and I've used the answer on this question:

(htaccess) How to prevent a file from DIRECT URL ACCESS?

That page suggests using mod.rewrite like this:

RewriteEngine on
RewriteRule \.(png|pdf|htm)$ - [F]

Using mod.rewrite in this manner works fine for denying access to PDFs, but other files that are ordinarily included in a page such as images and css are not only blocked from direct access, but also blocked when used on a webpage in a normal  tag or whatever.  This is contrary to the question and answer mentioned above.

So... my question is... is there a way to block direct access to files but still allow them in webpages?

Body:
Thanks Mark Phillips, I didn't fully appreciate what these two rewrite conditions were doing for me:

RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost [NC]
RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost.*$ [NC]

So I had managed to mess them up.  Things worked as needed when I used the code just as it was.


问:
Generated recursive object based on array
I have an array, which is a list of keys: ['one', 'two', 'three'].

I need to generate an object, of the following format:

```<code>{
  path: 'one',
  nested: {
    path: 'two',
    nested: {
      path: 'three'
    }
  }
}
</code>```

So far I've tried a couple of approaches, but they seem quite messy (I have one method which uses while(current = array.pop()) but it requires several conditionals to handle the first and last elements.

Is there a neater recursive strategy?

答:
You can use reduce() method and as accumulator pass object that you want add properties to.

var arr = ['one', 'two', 'three']
var obj = {}

arr.reduce(function(r, e, i) {
  r.path = e;
  return arr[i+1] ? r.nested = {} : r
}, obj)

console.log(obj)```
</div>
</div>
</p>

<p>If you want to use just recursion without loop you can create function like this.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var data = ['one', 'two', 'three']
var obj = {}

function makeObj(arr, n, o) {
  if (n == arr.length - 1) o.path = arr[n]
  else {
    o.path = arr[n];
    o.nested = {}
    makeObj(arr, n += 1, o.nested)
  }
  return o.nested
}

makeObj(data, 0, obj)
console.log(obj)</code>```

Body:
I have an array, which is a list of keys: ['one', 'two', 'three'].

I need to generate an object, of the following format:

{
  path: 'one',
  nested: {
    path: 'two',
    nested: {
      path: 'three'
    }
  }
}

So far I've tried a couple of approaches, but they seem quite messy (I have one method which uses while(current = array.pop()) but it requires several conditionals to handle the first and last elements.

Is there a neater recursive strategy?

Body:
You can use reduce() method and as accumulator pass object that you want add properties to.

var arr = ['one', 'two', 'three']
var obj = {}

arr.reduce(function(r, e, i) {
  r.path = e;
  return arr[i+1] ? r.nested = {} : r
}, obj)

console.log(obj)

If you want to use just recursion without loop you can create function like this.

var data = ['one', 'two', 'three']
var obj = {}

function makeObj(arr, n, o) {
  if (n == arr.length - 1) o.path = arr[n]
  else {
    o.path = arr[n];
    o.nested = {}
    makeObj(arr, n += 1, o.nested)
  }
  return o.nested
}

makeObj(data, 0, obj)
console.log(obj)


答:
find the previous element and find the select tag within that

```<code>$(this).prev().find('select').attr('id')
</code>```

this should work

here is a fiddle https://jsfiddle.net/fxabnk4o/3/

Title: Get id of previous select tag

Body:
I have next structure:

    <select id="house-1-room-1"><?php echo $options; ?></select>
    <input type='text' class='name' name='house-1-room-size-1' placeholder='Room Size'>

<button class="add_field_button">Add Another Room</button>

When  add_field_button clicked, I am trying to get the id of previous select tag, in my case it is house-1-room-1 with jquery (or vanila js).

I've tried:

$(this).parent().prev("select").attr('id');

and

$(this).prev("div").closest("select").attr('id');

And many other combination of above to no avail.

Please help!

Body:
find the previous element and find the select tag within that

$(this).prev().find('select').attr('id')

this should work

here is a fiddle https://jsfiddle.net/fxabnk4o/3/


问:
wrapper function; function that returns function
I am not sure how to write a wrapper function for something that includes magrittr pipe (%>%). I am trying to create a wrapper function that returns addPolyline(), addPolygon() or addCircleMarkers() depending on the layer type but I have not been successful. It seems the answer will be in Hadley's Advanced material but most likely it went over my head. As a simple example, how can I make something like the following example work:

```<code>library(leaflet)

wrapper <- function() {
  myfunc <- function() {addPolylines(data = leaflet::atlStorms2005)}
  return(myfunc)
}

# I want this
leaflet() %>% addTiles() %>% addPolylines(data = leaflet::atlStorms2005)

# but I need a wrapper function
leaflet() %>% addTiles() %>% wrapper()
</code>```

答:
It seems that you need to modify your wrapper function a little and use %>% wrapper()() in the pipe.

```<code>library(leaflet)

wrapper <- function() {
    myfunc <- function(.) {addPolylines(., data = leaflet::atlStorms2005)}
    return(myfunc)
}

# I want this
leaflet() %>% addTiles() %>% addPolylines(data = leaflet::atlStorms2005)

# but I need a wrapper function
leaflet() %>% addTiles() %>% wrapper()()
</code>```

Body:
I am not sure how to write a wrapper function for something that includes magrittr pipe (%>%). I am trying to create a wrapper function that returns addPolyline(), addPolygon() or addCircleMarkers() depending on the layer type but I have not been successful. It seems the answer will be in Hadley's Advanced material but most likely it went over my head. As a simple example, how can I make something like the following example work:

library(leaflet)

wrapper <- function() {
  myfunc <- function() {addPolylines(data = leaflet::atlStorms2005)}
  return(myfunc)
}

# I want this
leaflet() %>% addTiles() %>% addPolylines(data = leaflet::atlStorms2005)

# but I need a wrapper function
leaflet() %>% addTiles() %>% wrapper()

Body:
It seems that you need to modify your wrapper function a little and use %>% wrapper()() in the pipe.

library(leaflet)

wrapper <- function() {
    myfunc <- function(.) {addPolylines(., data = leaflet::atlStorms2005)}
    return(myfunc)
}

# I want this
leaflet() %>% addTiles() %>% addPolylines(data = leaflet::atlStorms2005)

# but I need a wrapper function
leaflet() %>% addTiles() %>% wrapper()()