问:
Constructor getting called twice React Component
The constructor of my react component is getting called twice but I can't figure out why. I am using react-redux to store the language of my app. I have a function that set the default language base on browser's language. LoginPage is the first component that gets render so I called my function in its constructor. Basically what it does is compare and dispatch an action. When I checked my state with redux developer tools I saw that it was getting dispatched twice. I printed dummy data in the constructor and it gets printed twice too.

LoginPage.js

```<code>import React from 'react';
import {connect} from 'react-redux';
import {startLogin} from '../actions/auth';
import {setLanguage} from '../actions/lang';

export class LoginPage extends React.Component{

  constructor(props){
    super(props);
    this.setDefaultLanguage();
    console.log('i am constructor');
  }

  changeLanguage = (e) => {
    const lan = e.target.value;
    this.props.setLanguage(lan);
  };

  setDefaultLanguage = () => {
    const defaultLanguage = navigator.language || navigator.userLanguage || 'en-US';

    if(defaultLanguage == 'es'){
      this.props.setLanguage(defaultLanguage);
    }else{
      this.props.setLanguage('en');
    }
  }

  render(){
    return(
      <div className="box-layout">
        <div className="box-layout__box">
          <h1 className="box-layout__title">Expensify</h1>
          <p>It\'s time to get your expenses under control.</p>
          <button className="button" onClick={this.props.startLogin}>Log in with google</button>
          <select className="select" onChange={this.changeLanguage}>
            <option value="en">English</option>
            <option value="es">Español</option>
          </select>
        </div>
      </div>
    )
  };
}

const mapDispatchToProps = (dispatch) => ({
  startLogin: () => dispatch(startLogin()),
  setLanguage: (language) => dispatch(setLanguage(language))
});

export default connect(undefined, mapDispatchToProps)( LoginPage);
</code>```

App.js

```<code>import React from 'react';
import ReactDom from 'react-dom';
import {Router, Route, Switch} from 'react-router-dom';
import createHistory from 'history/createBrowserHistory';
import ExpenseDashBoardPage from '../components/ExpenseDashBoardPage';
import AddExpensePage from '../components/AddExpensePage';
import EditExpensePage from '../components/EditExpensePage';
import NotFoundPage from '../components/NotFoundPage';
import LoginPage from '../components/LoginPage';
import PrivateRoute from './PrivateRoute';
import PublicRoute from './PublicRoute';

export const history = createHistory();

const AppRouter = () => (
  <Router history={history}>
    <div>
      <Switch>
        <PublicRoute path="/" component={LoginPage} exact={true} />
        <PrivateRoute path="/dashboard" component={ExpenseDashBoardPage} />
        <PrivateRoute path="/create" component={AddExpensePage} />
        <PrivateRoute path="/edit/:id" component={EditExpensePage} />
        <Route component={NotFoundPage} />
      </Switch>
    </div>

  </Router>
)

export default AppRouter;
</code>```

答:
I was having the same issue because I was redirecting the user inside my public routes. So it was rendering the component twice. In case you are using

```<code>history.push('/');
</code>```

This is going to render the component twice.

Body:
The constructor of my react component is getting called twice but I can't figure out why. I am using react-redux to store the language of my app. I have a function that set the default language base on browser's language. LoginPage is the first component that gets render so I called my function in its constructor. Basically what it does is compare and dispatch an action. When I checked my state with redux developer tools I saw that it was getting dispatched twice. I printed dummy data in the constructor and it gets printed twice too.

LoginPage.js

import React from 'react';
import {connect} from 'react-redux';
import {startLogin} from '../actions/auth';
import {setLanguage} from '../actions/lang';

export class LoginPage extends React.Component{

  constructor(props){
    super(props);
    this.setDefaultLanguage();
    console.log('i am constructor');
  }

  changeLanguage = (e) => {
    const lan = e.target.value;
    this.props.setLanguage(lan);
  };

  setDefaultLanguage = () => {
    const defaultLanguage = navigator.language || navigator.userLanguage || 'en-US';

    if(defaultLanguage == 'es'){
      this.props.setLanguage(defaultLanguage);
    }else{
      this.props.setLanguage('en');
    }
  }

  render(){
    return(

Expensify

It\'s time to get your expenses under control.

          <button className="button" onClick={this.props.startLogin}>Log in with google</button>
          <select className="select" onChange={this.changeLanguage}>
            <option value="en">English</option>
            <option value="es">Español</option>
          </select>

    )
  };
}

const mapDispatchToProps = (dispatch) => ({
  startLogin: () => dispatch(startLogin()),
  setLanguage: (language) => dispatch(setLanguage(language))
});

export default connect(undefined, mapDispatchToProps)( LoginPage);

App.js

import React from 'react';
import ReactDom from 'react-dom';
import {Router, Route, Switch} from 'react-router-dom';
import createHistory from 'history/createBrowserHistory';
import ExpenseDashBoardPage from '../components/ExpenseDashBoardPage';
import AddExpensePage from '../components/AddExpensePage';
import EditExpensePage from '../components/EditExpensePage';
import NotFoundPage from '../components/NotFoundPage';
import LoginPage from '../components/LoginPage';
import PrivateRoute from './PrivateRoute';
import PublicRoute from './PublicRoute';

export const history = createHistory();

const AppRouter = () => (
  <Router history={history}>

      <Switch>
        <PublicRoute path="/" component={LoginPage} exact={true} />
        <PrivateRoute path="/dashboard" component={ExpenseDashBoardPage} />
        <PrivateRoute path="/create" component={AddExpensePage} />
        <PrivateRoute path="/edit/:id" component={EditExpensePage} />
        <Route component={NotFoundPage} />
      </Switch>

  </Router>
)

export default AppRouter;

Body:
I was having the same issue because I was redirecting the user inside my public routes. So it was rendering the component twice. In case you are using

history.push('/');

This is going to render the component twice.


来源: stackexchange

问:
How do I change my board from CMMI to Agile in Team Services?
My team is currently using the CMMI board in Team Services and we would like to switch to the Agile board.  I was told we can't just change the template, but I can't figure out how to export all of our open tickets to a new board.  How do I easily change our team's board.  Thanks!</p>

答:
At the moment this is technically not possible. When you choose a Process, during project creation, you can't change it to a new parent later. So you pick CMMI, or Agile or Scrum and later you can only change to a derived template.

What you can do though, is create an inherited process template and customize it until it looks and feels the same as another process template. It's quite a bit of work, but doable.

It is expected that changing from one base template to another will be added somewhere in the future. But at the moment it's not showing up on the TFS/VSTS feature timeline.

There is no easy import/export option either, though there are a few tools, like VSTS Sync Migration Tool that can copy over work items and map them to a new structure. I'll probably just be as much work as creating an inhertited process though.

ContentLicense: CC BY-SA 3.0


问:
Saving a variable as it is in the memory to a file
I have a dictionary that is 2280 bytes according to

```<code>sys.getsizeof(myDictionary)
</code>```

when I save it to a file with pickle

```<code>with open("dictionary.txt", "wb") as fp:   #Pickling
    pickle.dump(myDictionary, fp)
</code>```

it's suddenly about 100KB in size

Is it possible for me to get the exact binary representation of that dictionary and save it to a file?
and later access this file again as a dictionary?

or if it isn't possible, maybe its possible with another programming language? It'd be important to have that file as small as possible

答:
Quote from the docs about sys.getsizeof:

Only the memory consumption directly attributed to the object is accounted for, not the memory consumption of objects it refers to.

Well, objects in Python refer to other objects a lot, so chances are, getsizeof won't help here much.

For example:

```<code>>>> a = {'a': 1, 'b': 2}
>>> sys.getsizeof(a)
240 # WUT
len(pickle.dumps(a))
28 # looks legit
</code>```

Then do:

```<code>>>> p = [1,2,3,4,5]
>>> a['k'] = p
>>> sys.getsizeof(a)
240 # WUT
>>> len(pickle.dumps(a))
51 # looks legit
</code>```

So, the amount of memory this object consumes depends on representation, apparently. If you want to save only the dictionary, well, you'll have to save just a bunch of pointers to basically nowhere (since when you load the saved data they'll be invalid). You can use this recursive recipe to find the size of the objects and its contents.

If you want your file be as small as possible, consider compressing the values in the dictionary or use a different data representation.

Body:
I have a dictionary that is 2280 bytes according to

sys.getsizeof(myDictionary)

when I save it to a file with pickle

with open("dictionary.txt", "wb") as fp:   #Pickling
    pickle.dump(myDictionary, fp)

it's suddenly about 100KB in size

Is it possible for me to get the exact binary representation of that dictionary and save it to a file?
and later access this file again as a dictionary?

or if it isn't possible, maybe its possible with another programming language? It'd be important to have that file as small as possible

Body:
Quote from the docs about sys.getsizeof:

Only the memory consumption directly attributed to the object is accounted for, not the memory consumption of objects it refers to.

Well, objects in Python refer to other objects a lot, so chances are, getsizeof won't help here much.

For example:

>>> a = {'a': 1, 'b': 2}
>>> sys.getsizeof(a)
240 # WUT
len(pickle.dumps(a))
28 # looks legit

Then do:

>>> p = [1,2,3,4,5]
>>> a['k'] = p
>>> sys.getsizeof(a)
240 # WUT
>>> len(pickle.dumps(a))
51 # looks legit

So, the amount of memory this object consumes depends on representation, apparently. If you want to save only the dictionary, well, you'll have to save just a bunch of pointers to basically nowhere (since when you load the saved data they'll be invalid). You can use this recursive recipe to find the size of the objects and its contents.

If you want your file be as small as possible, consider compressing the values in the dictionary or use a different data representation.


问:
How do I initialize a struct in C based on the member's name
In C I often see structs init'ed like this:

```<code>struct size aSize;
aSize.x = 100;
aSize.y = 42;
</code>```

But in other languages you can create struct "like" data structures in one line like:

```<code>aSize = {
    x : 100,
    y : 42
};
</code>```

Is a similar syntax supported in C?

I understand that Javascript's "struct" like data structure is really a hash without defined params, i'm just trying to show the syntax

答:
C99 allows the following for "order agnostic" initilization:

```<code>struct aSize {
    int x;
    int y;
} aSize = { .y = 4, .x = 5 };
</code>```

See this link for a working example

ContentLicense: CC BY-SA 2.5

Body:
In C I often see structs init'ed like this:

struct size aSize;
aSize.x = 100;
aSize.y = 42;

But in other languages you can create struct "like" data structures in one line like:

aSize = {
    x : 100,
    y : 42
};

Is a similar syntax supported in C?

I understand that Javascript's "struct" like data structure is really a hash without defined params, i'm just trying to show the syntax

Body:
C99 allows the following for "order agnostic" initilization:

struct aSize {
    int x;
    int y;
} aSize = { .y = 4, .x = 5 };

See this link for a working example


问:
flask url_for() adding a "/" before the url while pointing to static folder
I have this folder structure for my flask app:

```<code>app.py
 /templates
     login.html
     index.html
 /static
   /css
     main.css
     login.css
   /js
     login.js
   /images
     image.png
</code>```

When I use <link rel="stylesheet" href={{url_for('static',filename='css/main.css')}}> inside login.html, it renders as
 <link rel="stylesheet" href="/static/css/main.css"> (Note the prepended slash before static).

Now, this leads to 404 errors because I intend to run to run this application with /app1/ in the NGINX server block. Due to the prepended slash, the application tries to find main.css in XXX.XXX.XX.XX/static/css/main.css rather than XXX.XXX.XX.XX/app1/static/css/main.css

If I do not use url_for() and write the entire file path inside login.html i.e. <link rel="stylesheet" href="static/css/main.css"> (without prepending the slash before static), it works just fine.

But I want to use url_for() inside the templates, as it is considered a good practice and saves a lot of trouble.

Any help/suggestion would be highly appreciated.

[EDIT]: The existing questions ask about "adding a prefix" to url_for(). This question pertains to understanding why url_for() is prepending "/" in its route, and how to remove the prepended slash.The application is working if I write the entire url path in the template, but that is not a good solution.

答:
If saving the file is creating some trouble why not CDN the bootstrap by providing the link

I hope that helps

Body:
I have this folder structure for my flask app:

app.py
 /templates
     login.html
     index.html
 /static
   /css
     main.css
     login.css
   /js
     login.js
   /images
     image.png

When I use <link rel="stylesheet" href={{url_for('static',filename='css/main.css')}}> inside login.html, it renders as
 <link rel="stylesheet" href="/static/css/main.css"> (Note the prepended slash before static).

Now, this leads to 404 errors because I intend to run to run this application with /app1/ in the NGINX server block. Due to the prepended slash, the application tries to find main.css in XXX.XXX.XX.XX/static/css/main.css rather than XXX.XXX.XX.XX/app1/static/css/main.css

If I do not use url_for() and write the entire file path inside login.html i.e. <link rel="stylesheet" href="static/css/main.css"> (without prepending the slash before static), it works just fine.

But I want to use url_for() inside the templates, as it is considered a good practice and saves a lot of trouble.

Any help/suggestion would be highly appreciated.

[EDIT]: The existing questions ask about "adding a prefix" to url_for(). This question pertains to understanding why url_for() is prepending "/" in its route, and how to remove the prepended slash.The application is working if I write the entire url path in the template, but that is not a good solution.


问:
How can I convert a PDF file to a PRN file?
I have a JAVA program that creates a PDF file.
However I need to send this PDF file to a printer via SDK for this printer that would only accept PRN file type …

I understand that a the PRN file is built by using the specific driver for the specific printer, so the java program should be able to pick the driver for use in order to convert the PDF to a PRN file

As for the question, why wouldn’t I send the PDF file directly to print via the driver, well, this is a zebra printer that prints and encode smart cards, performing printing and encoding is only available if approaching it from the SDK, if I were to sent in directly to the driver , it would only print without encoding the cards

答:
Zebra printers use zpl language. You can design your zpl template and send it to your printer as a prn file.

```<code>^XA
^FX Top section with company logo, name and address.
^CF0,60
^FO50,50^GB100,100,100^FS
^FO75,75^FR^GB100,100,100^FS
^FO88,88^GB50,50,50^FS
^FO220,50^FDInternational Shipping, Inc.^FS
^CF0,40
^FO220,100^FD1000 Shipping Lane^FS
^FO220,135^FDShelbyville TN 38102^FS
^FO220,170^FDUnited States (USA)^FS
^FO50,250^GB700,1,3^FS
^XZ
</code>```

Copy the text above and paste it into the notepad. Save it as abc.prn and send it to your printer.

You will see, it will print a label (I assume you are using a 4x6 printer).

So you can create your own zpl template using this website. http://labelary.com/viewer.html
and this guide
https://www.zebra.com/content/dam/zebra/manuals/en-us/software/zpl-zbi2-pm-en.pdf

Body:
Zebra printers use zpl language. You can design your zpl template and send it to your printer as a prn file.

^XA
^FX Top section with company logo, name and address.
^CF0,60
^FO50,50^GB100,100,100^FS
^FO75,75^FR^GB100,100,100^FS
^FO88,88^GB50,50,50^FS
^FO220,50^FDInternational Shipping, Inc.^FS
^CF0,40
^FO220,100^FD1000 Shipping Lane^FS
^FO220,135^FDShelbyville TN 38102^FS
^FO220,170^FDUnited States (USA)^FS
^FO50,250^GB700,1,3^FS
^XZ

Copy the text above and paste it into the notepad. Save it as abc.prn and send it to your printer.

You will see, it will print a label (I assume you are using a 4x6 printer).

So you can create your own zpl template using this website. http://labelary.com/viewer.html
and this guide
https://www.zebra.com/content/dam/zebra/manuals/en-us/software/zpl-zbi2-pm-en.pdf


问:
Read data from a local JSON file with data binding in ngOnInit() results in undefined variable
I am trying to get a data from json file in the assets folder, and then assign this data to a variable that will be binded to another @Input variable of a child componenet.

Code

Based on multiple solutions on the net, I retrieve my JSON data this way:

```<code>@Injectable()
export class JSONService {

    constructor(private http: HttpClient) { }

    public fromJSON(jsonFileName: string): Observable<any[]> {
      let result: any[] = new Array();
      let pathToJson: string = "assets/" + jsonFileName + ".json";

      return this.http.get(pathToJson).map(data => {
        let result: any[] = new Array();
        // Apply some treatment on data and push it to the result array
        return result;
      });
    }
}
</code>```

I then call my service in the ngOnInit() method of the parent component:

```<code>ngOnInit() {
    this.jsonService.fromJSON("users.json").subscribe(fields => {
      this.fields= fields;
      console.log(this.fields); // Log (I): this.fields is well defined
    });
    console.log(this.fields); // Log (II): this.fields is undefined
}
</code>```

Where the variable fields is binded to a child component:

```<code><child-component [childFields] = "fields"></child-component>
</code>```

Problem

The problem that I am facing is that the asynchronous call to the fromJSON method causes this.fields to be undefined at some point of the lifecycle of the page execution (Log (II) from the code above), and this causes to send an undefined value of the this.fields variable to the child component.

How to avoid to have an undefined value of the fields variable, and make sure that the child component is always loaded with the data from the json file?

答:
Service.ts

```<code>@Injectable()
export class JSONService {

    constructor(private http: HttpClient) { }

    public fromJSON(jsonFileName): Observable<any[]> {
      console.warn('Retriving Default Data from File.......');
    return this.http.get(filename)
      .map(this.extractData)
      .catch(this.handleError);
    }
  private extractData(res: Response) {
    let body = res.json();
    return body || [];
  }

  private handleError(error: any) {
        const errMsg = (error.message) ? error.message :
          error.status ? `${error.status} - ${error.statusText}` : 'Server error';
        console.error(errMsg);
        console.log('Server Error!');
        return Observable.throw(errMsg);
      }
}
</code>```

parent.component.ts

```<code>constructor(public jsonService: jsonService) {
  }

  ngOnInit() {

          this.jsonService.fromJSON('assets/users.json').subscribe(
          function (success) {
            this.data = success;
           this.datahandle(success);
          },
          error => console.log('Getting Server Data Error :: ' +
    JSON.stringify(error)));

}
datahandle(jsonData){

console.log('check data' + JSON.stringify(jsonData)); <-----check data

// may parse your jsonData  if required
this.fields = jsonData ;

let keys = Object.keys(jsonData);
console.log(keys);

}
}
</code>```

parent.component.html

```<code><child-component *ngIf="fields" [childFields] = "fields"></child-component>
</code>```

Body:
I am trying to get a data from json file in the assets folder, and then assign this data to a variable that will be binded to another @Input variable of a child componenet.

Code

Based on multiple solutions on the net, I retrieve my JSON data this way:

@Injectable()
export class JSONService {

    constructor(private http: HttpClient) { }

    public fromJSON(jsonFileName: string): Observable<any[]> {
      let result: any[] = new Array();
      let pathToJson: string = "assets/" + jsonFileName + ".json";

      return this.http.get(pathToJson).map(data => {
        let result: any[] = new Array();
        // Apply some treatment on data and push it to the result array
        return result;
      });
    }
}

I then call my service in the ngOnInit() method of the parent component:

ngOnInit() {
    this.jsonService.fromJSON("users.json").subscribe(fields => {
      this.fields= fields;
      console.log(this.fields); // Log (I): this.fields is well defined
    });
    console.log(this.fields); // Log (II): this.fields is undefined
}

Where the variable fields is binded to a child component:

<child-component [childFields] = "fields"></child-component>

Problem

The problem that I am facing is that the asynchronous call to the fromJSON method causes this.fields to be undefined at some point of the lifecycle of the page execution (Log (II) from the code above), and this causes to send an undefined value of the this.fields variable to the child component.

How to avoid to have an undefined value of the fields variable, and make sure that the child component is always loaded with the data from the json file?

Body:
Service.ts

@Injectable()
export class JSONService {

    constructor(private http: HttpClient) { }

    public fromJSON(jsonFileName): Observable<any[]> {
      console.warn('Retriving Default Data from File.......');
    return this.http.get(filename)
      .map(this.extractData)
      .catch(this.handleError);
    }
  private extractData(res: Response) {
    let body = res.json();
    return body || [];
  }

  private handleError(error: any) {
        const errMsg = (error.message) ? error.message :
          error.status ? `${error.status} - ${error.statusText}` : 'Server error';
        console.error(errMsg);
        console.log('Server Error!');
        return Observable.throw(errMsg);
      }
}

parent.component.ts

constructor(public jsonService: jsonService) {
  }

  ngOnInit() {

          this.jsonService.fromJSON('assets/users.json').subscribe(
          function (success) {
            this.data = success;
           this.datahandle(success);
          },
          error => console.log('Getting Server Data Error :: ' +
    JSON.stringify(error)));

}
datahandle(jsonData){

console.log('check data' + JSON.stringify(jsonData)); <-----check data

// may parse your jsonData  if required
this.fields = jsonData ;

let keys = Object.keys(jsonData);
console.log(keys);

}
}

parent.component.html

<child-component *ngIf="fields" [childFields] = "fields"></child-component>


问:
Saving python file in event of power failure
We are acquiring data from an Arduino strain gauge through the serial port of the Raspberry Pi and Python.  We have it so it will read all the data do the necessary calculations and it will print to a text file however if there is a power failure the data gathered is lost.  This is what we are trying to figure out how to fix or not have happen.

```<code>import serial

ardserial = serial.Serial('/dev/ttyACM0',9600)

counter = 1

def strain():
    a=int(adserial.readlines())
    b=(str(a*(5/16)/166))
    c=float(b)
    with open('textfile1.txt','a+') as text_file:
        text_file.write('Strain Value: ' + str(c) + '\n')

while counter > 0:
    strain()
</code>```

We have it so it will write to the txt file correctly and it will save all the data if we kill the program but we also expected it to save all the data if the power was pulled to the Raspberry Pi.  It does not do this.

I was almost 100% sure that I have done it in the past where if the power was killed it would have the saved data but I can't for the life of me figure it out.  Any help would be... well... helpful thanks.

答:
Write data to disk after each file write:

If you’re starting with a buffered Python file object f, first do
  f.flush(), and then do os.fsync(f.fileno()), to ensure that all
  internal buffers associated with f are written to disk.

Source: Python docs

Body:
We are acquiring data from an Arduino strain gauge through the serial port of the Raspberry Pi and Python.  We have it so it will read all the data do the necessary calculations and it will print to a text file however if there is a power failure the data gathered is lost.  This is what we are trying to figure out how to fix or not have happen.

import serial

ardserial = serial.Serial('/dev/ttyACM0',9600)

counter = 1

def strain():
    a=int(adserial.readlines())
    b=(str(a*(5/16)/166))
    c=float(b)
    with open('textfile1.txt','a+') as text_file:
        text_file.write('Strain Value: ' + str(c) + '\n')

while counter > 0:
    strain()

We have it so it will write to the txt file correctly and it will save all the data if we kill the program but we also expected it to save all the data if the power was pulled to the Raspberry Pi.  It does not do this.

I was almost 100% sure that I have done it in the past where if the power was killed it would have the saved data but I can't for the life of me figure it out.  Any help would be... well... helpful thanks.


问:
regex ^ and $ are not working
I'm trying to  write a regex that matches a number with commas for
every three digits? It must match the following:

```<code>'42'
'1,234'
'6,368,745'
</code>```

but not the following:

```<code>'12,34,567' (which has only two digits between the commas)
'1234' (which lacks commas)
</code>```

so I have tried the following

```<code>((^\d{1,3})((\,\d{3})*$))
^\d{1,3}(,{3})*$
^(\d{1,3}(,{3})*)$
</code>```

but it didn't match anything.
when I tried without ^ and $ then it is not matching the exact pattern.

答:
prithvi,

your first regex works, actually.

Try this test:

```<code>import re

REGEX = re.compile("((^\d{1,3})((\,\d{3})*$))")

for test in ('42', '1,234', '6,368,745', '12,34,567', '1234'):
    print(test, REGEX.match(test) != None)
</code>```

The output is (python 3)

```<code>42 True
1,234 True
6,368,745 True
12,34,567 False
1234 False
</code>```

UPDATE

prithvi asked in the comment about a regex that could be used in the findall method. Since the answer is a bit lengthy I put it here.

For findall the regex should have boundaries, that match something that is not a part of the number.

I suppose, the boundary before the match is either string beginning or a string that is neither digit nor comma. I encode such boundary as (?:^|(?<=[^0-9,]))

Same with the boundary after - it is either end of string or something that is neither digit nor comma: (?:(?=[^0-9,])|$)

How those regex are built.

?: designates a group that is not included in the group list. I use for cleaner math result

?<=[^0-9,] is a a positive lookbehind assertion. It means, that the following regex matches if and only if it is preceded by something that matches [^0-9,] (that is neither a digit nor a comma)

?=[^0-9,] is a lookbehind assertion. It means, that the preceding part of regex matches if and only if it is followed by something that matches [^0-9,] (that is neither a digit nor a comma)

Here is an example:

```<code>REGEX = re.compile("(?:^|(?<=[^0-9,]))(\d{1,3}(?:\,\d{3})*)(?:(?=[^0-9,])|$)")
long_str = '42 1,234 6,368,745 12,34,567 1234'
print(REGEX.findall(long_str))
</code>```

The result is ['1,234', '42', '6,368,745']

Title: regex ^ and $ are not working

Body:
I'm trying to  write a regex that matches a number with commas for
every three digits? It must match the following:

'42'
'1,234'
'6,368,745'

but not the following:

'12,34,567' (which has only two digits between the commas)
'1234' (which lacks commas)

so I have tried the following

((^\d{1,3})((\,\d{3})*$))
^\d{1,3}(,{3})*$
^(\d{1,3}(,{3})*)$

but it didn't match anything.
when I tried without ^ and $ then it is not matching the exact pattern.

Body:
prithvi,

your first regex works, actually.

Try this test:

import re

REGEX = re.compile("((^\d{1,3})((\,\d{3})*$))")

for test in ('42', '1,234', '6,368,745', '12,34,567', '1234'):
    print(test, REGEX.match(test) != None)

The output is (python 3)

42 True
1,234 True
6,368,745 True
12,34,567 False
1234 False

UPDATE

prithvi asked in the comment about a regex that could be used in the findall method. Since the answer is a bit lengthy I put it here.

For findall the regex should have boundaries, that match something that is not a part of the number.

I suppose, the boundary before the match is either string beginning or a string that is neither digit nor comma. I encode such boundary as (?:^|(?<=[^0-9,]))

Same with the boundary after - it is either end of string or something that is neither digit nor comma: (?:(?=[^0-9,])|$)

How those regex are built.

?: designates a group that is not included in the group list. I use for cleaner math result

?<=[^0-9,] is a a positive lookbehind assertion. It means, that the following regex matches if and only if it is preceded by something that matches [^0-9,] (that is neither a digit nor a comma)

?=[^0-9,] is a lookbehind assertion. It means, that the preceding part of regex matches if and only if it is followed by something that matches [^0-9,] (that is neither a digit nor a comma)

Here is an example:

REGEX = re.compile("(?:^|(?<=[^0-9,]))(\d{1,3}(?:\,\d{3})*)(?:(?=[^0-9,])|$)")
long_str = '42 1,234 6,368,745 12,34,567 1234'
print(REGEX.findall(long_str))

The result is ['1,234', '42', '6,368,745']


问:
How to save an imported category under a different name w/ wpallimport woocommerce
I am importing a product list CSV from a wholesalers website and one of the categories for items is "Baseball Caps" - I have renamed this category to "Hats" but now every time i re-import the product list I have to go rename the category "Hats" back to "Baseball Caps" - run the import - then rename it back, otherwise it will create the new category and all the products to that one instead of the one I would like

Is there a function I could write in wpallimports function editor so that when category == "Baseball Caps" it saves it as "Hats" with slug "Hats" as well ?

thank you

答:
Would this work to only replace that string and leave all other strings alone? as there are multiple categories separated by commas. Sorry - haven't scripted since tintin scripting on MUDs a long time ago</p>

```<code>[str_replace("Baseball Caps", "Hats", {categories[1]})]
</code>```

Body:
Would this work to only replace that string and leave all other strings alone? as there are multiple categories separated by commas. Sorry - haven't scripted since tintin scripting on MUDs a long time ago

[str_replace("Baseball Caps", "Hats", {categories[1]})]


问:
How to deny s3 bucket access for an AWS account
I have an AWS account with ID 11111 and I would like to deny access to certain parts of an s3 bucket to the same account the bucket belongs to, even if the role accessing that object has full s3 access.

It is my understanding that setting a DENY rule on a s3 bucket policy should do that, so I tried the s3 policy below

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "",
            "Effect": "Deny",
            "Principal": {
                "AWS": "arn:aws:iam::111111:root"
            },
            "Action": [
                "s3:PutObject",
                "s3:GetObjectVersion",
                "s3:GetObject",
                "s3:DeleteObject"
            ],
            "Resource": [
                "arn:aws:s3:::mybucket/production/*"
            ]
        }
    ]
}

However an ec2 machine in the same account as the s3 bucket with an iam role to allow full access to the bucket (s3:*) is still able to write/read to mybucket/production/*

Am I missing something? Shouldn't the DENY bucket rule take precedence? How does one handle this situation? I want to avoid having to remove the full access from the ec2 role but rather be able to deny on top of that.

答:
I have not actually tested this.

Your S3 policy is limiting access for IAM users. Your goal is to limit access for services and / or roles that services assume.

To deny access to all EC2 instances, add another rule and specify the principal as (or add to your existing Principal entries):

```<code>"Principal": {"Service": "ec2.amazonaws.com"}
</code>```

To limit access to a specific role that EC2 assumes:

```<code>"Principal": { "AWS": "arn:aws:iam::AWS-account-ID:role/role-name" }
</code>```

Body:
I have not actually tested this.

Your S3 policy is limiting access for IAM users. Your goal is to limit access for services and / or roles that services assume.

To deny access to all EC2 instances, add another rule and specify the principal as (or add to your existing Principal entries):

"Principal": {"Service": "ec2.amazonaws.com"}

To limit access to a specific role that EC2 assumes:

"Principal": { "AWS": "arn:aws:iam::AWS-account-ID:role/role-name" }


问:
Get document's name with it's description
Trying to get the name of the active window with it's description, can't find any method.

My problem is that while I can access document's file name with Document.Name, I can't get the commentaries that Word attaches to it, like (Compatibility Mode, Last modified by User etc), without them, the method Windows(Document.Name) doesn't work, is there any solution for this?

My program opens four new documents and switches in a loop the active document, taking information from the original and putting some excerpts in the new ones.

Everything works when there is no commentaries for documents, but as they appear, program breaks, saying:

5941 The requested member of the collection does not exist

Thanks for reading!

答:
This:

```<code>Windows(1).Document
</code>```

will give you the document associated with a window. (You may need to loop through the windows to find the one you're interested in.)

Once you have the document you can access its properties:

```<code>Windows(1).Document.CompatibilityMode
</code>```

Hope that helps

Body:
This:

Windows(1).Document

will give you the document associated with a window. (You may need to loop through the windows to find the one you're interested in.)

Once you have the document you can access its properties:

Windows(1).Document.CompatibilityMode

Hope that helps


问:
Microsoft Dynamics 365 Plugin Error : You cannot start a transaction with a different isolation level than is already set on the current transaction
I am tying to make a custom entity with the name of Country2 by writing a plugin in C# for Microsoft Dynamics 365 CRM. I am trying in this way;

```<code>// Create the custom entity.
                    CreateEntityRequest createrequest = new CreateEntityRequest
                    {
                        //Define the entity
                        Entity = new EntityMetadata
                        {
                            SchemaName = "Country2",
                            DisplayName = new Label("Country2", _languageCode),
                            DisplayCollectionName = new Label("Countries2", _languageCode),
                            Description = new Label("An entity to store information about cities.", 1033),
                            OwnershipType = OwnershipTypes.UserOwned,
                            IsActivity = false,
                        },

                        // Define the primary attribute for the entity
                        PrimaryAttribute = new StringAttributeMetadata
                        {
                            SchemaName = "new_countryname",
                            RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                            MaxLength = 100,
                            FormatName = StringFormatName.Text,
                            DisplayName = new Label("Country Name", _languageCode),
                            Description = new Label("The primary attribute for the Country entity.", _languageCode)
                        }

                    };
                    service.Execute(createrequest);
                    //Entity must be published
                    // Add few attributes to the custom activity entity.
                    CreateAttributeRequest fontFamilyAttributeRequest = new CreateAttributeRequest
                        {
                            EntityName = "Country2",
                            Attribute = new StringAttributeMetadata
                            {
                                SchemaName = prefix + "fontfamily",
                                DisplayName = new Label("Font Family", _languageCode),
                                MaxLength = 100
                            }
                        };
                    CreateAttributeResponse fontFamilyAttributeResponse =
                        (CreateAttributeResponse)service.Execute(
                        fontFamilyAttributeRequest);

                    CreateAttributeRequest fontColorAttributeRequest =
                        new CreateAttributeRequest
                        {
                            EntityName = "Country2",
                            Attribute = new StringAttributeMetadata
                            {
                                SchemaName = prefix + "fontcolor",
                                DisplayName = new Label("Font Color", _languageCode),
                                MaxLength = 50
                            }
                        };
                    CreateAttributeResponse fontColorAttributeResponse =
                        (CreateAttributeResponse)service.Execute(
                        fontColorAttributeRequest);

                    CreateAttributeRequest fontSizeAttributeRequest =
                        new CreateAttributeRequest
                        {
                            EntityName = "Country2",
                            Attribute = new IntegerAttributeMetadata
                            {
                                SchemaName = prefix + "fontSize",
                                DisplayName = new Label("Font Size", _languageCode)
                            }
                        };
                    CreateAttributeResponse fontSizeAttributeResponse =
                        (CreateAttributeResponse)service.Execute(
                        fontSizeAttributeRequest);
                    throw new InvalidPluginExecutionException("The Country custom entity has been created.");
</code>```

In the above code, I tried to make the new entity first then tried to set the PrimaryAttribute and at the end CreateAttributeRequest.

But it prompts an error of;

You cannot start a transaction with a different isolation level than is already set on the current transaction.
  Is there any thing wrong here?

答:
Not sure you can create an entity without a custom prefix. Right now your entity is "Country2", I would change it to "new_country2" Your code follows pretty closely to the example provided online https://msdn.microsoft.com/en-us/library/gg509014.aspx

Try switching it to exactly like online to see if the entity/attribute is created with the same name from that article.

Body:
I am tying to make a custom entity with the name of Country2 by writing a plugin in C# for Microsoft Dynamics 365 CRM. I am trying in this way;

// Create the custom entity.
                    CreateEntityRequest createrequest = new CreateEntityRequest
                    {
                        //Define the entity
                        Entity = new EntityMetadata
                        {
                            SchemaName = "Country2",
                            DisplayName = new Label("Country2", _languageCode),
                            DisplayCollectionName = new Label("Countries2", _languageCode),
                            Description = new Label("An entity to store information about cities.", 1033),
                            OwnershipType = OwnershipTypes.UserOwned,
                            IsActivity = false,
                        },

                        // Define the primary attribute for the entity
                        PrimaryAttribute = new StringAttributeMetadata
                        {
                            SchemaName = "new_countryname",
                            RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                            MaxLength = 100,
                            FormatName = StringFormatName.Text,
                            DisplayName = new Label("Country Name", _languageCode),
                            Description = new Label("The primary attribute for the Country entity.", _languageCode)
                        }

                    };
                    service.Execute(createrequest);
                    //Entity must be published
                    // Add few attributes to the custom activity entity.
                    CreateAttributeRequest fontFamilyAttributeRequest = new CreateAttributeRequest
                        {
                            EntityName = "Country2",
                            Attribute = new StringAttributeMetadata
                            {
                                SchemaName = prefix + "fontfamily",
                                DisplayName = new Label("Font Family", _languageCode),
                                MaxLength = 100
                            }
                        };
                    CreateAttributeResponse fontFamilyAttributeResponse =
                        (CreateAttributeResponse)service.Execute(
                        fontFamilyAttributeRequest);

                    CreateAttributeRequest fontColorAttributeRequest =
                        new CreateAttributeRequest
                        {
                            EntityName = "Country2",
                            Attribute = new StringAttributeMetadata
                            {
                                SchemaName = prefix + "fontcolor",
                                DisplayName = new Label("Font Color", _languageCode),
                                MaxLength = 50
                            }
                        };
                    CreateAttributeResponse fontColorAttributeResponse =
                        (CreateAttributeResponse)service.Execute(
                        fontColorAttributeRequest);

                    CreateAttributeRequest fontSizeAttributeRequest =
                        new CreateAttributeRequest
                        {
                            EntityName = "Country2",
                            Attribute = new IntegerAttributeMetadata
                            {
                                SchemaName = prefix + "fontSize",
                                DisplayName = new Label("Font Size", _languageCode)
                            }
                        };
                    CreateAttributeResponse fontSizeAttributeResponse =
                        (CreateAttributeResponse)service.Execute(
                        fontSizeAttributeRequest);
                    throw new InvalidPluginExecutionException("The Country custom entity has been created.");

In the above code, I tried to make the new entity first then tried to set the PrimaryAttribute and at the end CreateAttributeRequest.

But it prompts an error of;

You cannot start a transaction with a different isolation level than is already set on the current transaction.
  Is there any thing wrong here?


问:
How can I consistently remove the default text from an input element with Selenium?
I'm trying to use Selenium WebDriver to input text to a GWT input element that has default text, "Enter User ID".  Here are a few ways I've tried to get this to work:

```<code>        searchField.click();
        if(!searchField.getAttribute("value").isEmpty()) {
            // clear field, if not already empty
            searchField.clear();
        }
        if(!searchField.getAttribute("value").isEmpty()) {
            // if it still didn't clear, click away and click back
            externalLinksHeader.click();
            searchField.click();
        }

        searchField.sendKeys(username);
</code>```

The strange thing is the above this only works some of the time.  Sometimes, it ends up searching for "Enter User IDus", basically beginning to type "username" after the default text -- and not even finishing that.

Any other better, more reliable ways to clear out default text from a GWT element?

Edited to add: The HTML of the input element.  Unfortunately, there's not much to see, thanks to the JS/GWT hotness.  Here's the field when it's unselected:

```<code><input type="text" class="gwt-TextBox empty" maxlength="40">
</code>```

After I've clicked it and given it focus manually, the default text and the "empty" class are removed.

The JS to setDefaultText() gets called both onBlur() and onChange() if the change results in an empty text field.  Guess that's why the searchField.clear() isn't helping.

I've also stepped through this method in debug mode, and in that case, it never works.  When run normally, it works the majority of the time.  I can't say why, though.

答:
```<code>In case you use c# then solution would be :

// provide some text
webElement.SendKeys("aa");
// this is how you use this in C# , VS
String b = Keys.Backspace.ToString();

// then provide back space few times
webElement.SendKeys(b + b + b + b + b + b + b + b + b + b);
</code>```

Body:
I'm trying to use Selenium WebDriver to input text to a GWT input element that has default text, "Enter User ID".  Here are a few ways I've tried to get this to work:

        searchField.click();
        if(!searchField.getAttribute("value").isEmpty()) {
            // clear field, if not already empty
            searchField.clear();
        }
        if(!searchField.getAttribute("value").isEmpty()) {
            // if it still didn't clear, click away and click back
            externalLinksHeader.click();
            searchField.click();
        }

        searchField.sendKeys(username);

The strange thing is the above this only works some of the time.  Sometimes, it ends up searching for "Enter User IDus", basically beginning to type "username" after the default text -- and not even finishing that.

Any other better, more reliable ways to clear out default text from a GWT element?

Edited to add: The HTML of the input element.  Unfortunately, there's not much to see, thanks to the JS/GWT hotness.  Here's the field when it's unselected:

<input type="text" class="gwt-TextBox empty" maxlength="40">

After I've clicked it and given it focus manually, the default text and the "empty" class are removed.

The JS to setDefaultText() gets called both onBlur() and onChange() if the change results in an empty text field.  Guess that's why the searchField.clear() isn't helping.

I've also stepped through this method in debug mode, and in that case, it never works.  When run normally, it works the majority of the time.  I can't say why, though.


问:
Get thumbnail from website with Bing Web Search API
Currently I am working on a website that uses google search for searching pages in the domain, google returns a thumbnail from a specific page (Most of the time a random image it finds on the page) together with the search result.

Wanting to move to Bing Web Search API, because google will start adding adds to the result, I was wondering if there was any possibility to get a site's thumbnail together with the search on a specific website? Bing Web Search API Docs says that thumbnails are not supported for all webpages, however there is no clear explanation about how to add one. Is there a workaround for this?

Thanks!

答: If you are looking for search for your site only, you should use the Bing Custom Search: https://azure.microsoft.com/en-us/services/cognitive-services/bing-custom-search/. You can create your search instance from customsearch.ai. I see custom search returns thumbnails for (al)most (all) results.  </p>


问:
Calculate working days without holidays fast in PHP
I need to calculate the working days between a huge set of dates. Therefore I am searching for a function that does it quickly

Set all holidays:

```<code>public function getArrayOfHolidays($year, $holidays= array(), $format = 'Y-m-d')
    {
        $special1= new DateTime('2017-10-31');
        array_push($holidays, $special1->format($format));

        $newyear= new DateTime();
        $newyear->modify('1 january ' . $year);
        array_push($holidays, $newyear->format($format));

        $holyThreeKings= new DateTime();
        $holyThreeKings->modify('6 january ' . $year);
        array_push($holidays, $holyThreeKings->format($format));

        $layborDay= new DateTime();
        $layborDay->modify('1 may ' . $year);
        array_push($holidays, $layborDay->format($format));

        $unityDay= new DateTime();
        $unityDay->modify('3 october ' . $year);
        array_push($holidays, $unityDay->format($format));

        $allSaintsDay= new DateTime();
        $allSaintsDay->modify('1 november ' . $year);
        array_push($holidays, $allSaintsDay->format($format));

        $christmasEve= new DateTime();
        $christmasEve->modify('24 december ' . $year);
        array_push($holidays, $christmasEve->format($format));

        $christmas1 = new DateTime();
        $christmas1->modify('25 december ' . $year);
        array_push($holidays, $christmas1->format($format));

        $christmas2 = new DateTime();
        $christmas2->modify('26 december ' . $year);
        array_push($holidays, $christmas2->format($format));

        $silvester = new DateTime();
        $silvester->modify('31 december ' . $year);
        array_push($holidays, $silvester->format($format));

        $easterSunday= new DateTime(date('Y-m-d', easter_date($year)));
        $easterSunday->modify('+1 day');
        array_push($holidays, $easterSunday->format($format));

        $goodFriday = new DateTime($ostersonntag->format('Y-m-d'));
        $goodFriday->modify('last friday');
        array_push($holidays, $goodFriday->format($format));

        $easterMonday= new DateTime($ostersonntag->format('Y-m-d'));
        $easterMonday->modify('next monday');
        array_push($holidays, $easterMonday->format($format));

        $ascensionOfJesus= new DateTime($ostersonntag->format('Y-m-d'));
        $ascensionOfJesus->modify('+39 days');
        array_push($holidays, $ascensionOfJesus->format($format));

        $pentecostSunday= new DateTime($ostersonntag->format('Y-m-d'));
        $pentecostSunday->modify('+49 days');
        array_push($holidays, $pentecostSunday->format($format));

        $pentecostMonday= new DateTime($ostersonntag->format('Y-m-d'));
        $pentecostMonday->modify('+50 days');
        array_push($holidays, $pentecostMonday->format($format));

        $corpusChristi = new DateTime($pentecostMonday->format('Y-m-d'));
        $corpusChristi ->modify('next sunday');
        $corpusChristi ->modify('next thursday');
        array_push($holidays, $corpusChristi ->format($format));

        return $holidays;
    }
</code>```

This runs a maximum of 3 times to make sure I have all holydays for the previous and the next year if there are dates calculated in between years. Therefore should not have that high of an impact. I still wanted to show it because there sure are better ways to do it? Of course I could pre-calculate the next X years and store them in a database, maybe that would be better.

now this is the function I use for calculating the workdays:

```<code>public function getWorkingDays($startDate, $endDate, $holidays)
    {
        // do strtotime calculations just once
        $endDate = strtotime($endDate);
        $startDate = strtotime($startDate);

        //The total number of days between the two dates. We compute the no. of seconds and divide it to 60*60*24
        //We add one to include both dates in the interval.
        $days = ($endDate - $startDate) / 86400 + 1;

        $no_full_weeks = floor($days / 7);
        $no_remaining_days = fmod($days, 7);

        //It will return 1 if it's Monday,.. ,7 for Sunday
        $the_first_day_of_week = date("N", $startDate);
        $the_last_day_of_week = date("N", $endDate);

        //---->The two can be equal in leap years when February has 29 days, the equal sign is added here
        //In the first case the whole interval is within a week, in the second case the interval falls in two weeks.
        if ($the_first_day_of_week <= $the_last_day_of_week) {
            if ($the_first_day_of_week <= 6 && 6 <= $the_last_day_of_week) $no_remaining_days--;
            if ($the_first_day_of_week <= 7 && 7 <= $the_last_day_of_week) $no_remaining_days--;
        } else {
            // (edit by Tokes to fix an edge case where the start day was a Sunday
            // and the end day was NOT a Saturday)

            // the day of the week for start is later than the day of the week for end
            if ($the_first_day_of_week == 7) {
                // if the start date is a Sunday, then we definitely subtract 1 day
                $no_remaining_days--;

                if ($the_last_day_of_week == 6) {
                    // if the end date is a Saturday, then we subtract another day
                    $no_remaining_days--;
                }
            } else {
                // the start date was a Saturday (or earlier), and the end date was (Mon..Fri)
                // so we skip an entire weekend and subtract 2 days
                $no_remaining_days -= 2;
            }
        }

        //The no. of business days is: (number of weeks between the two dates) * (5 working days) + the remainder
        //---->February in none leap years gave a remainder of 0 but still calculated weekends between first and last day, this is one way to fix it
        $workingDays = $no_full_weeks * 5;
        if ($no_remaining_days > 0) {
            $workingDays += $no_remaining_days;
        }

        //We subtract the holidays
        foreach ($holidays as $holiday) {
            $time_stamp = strtotime($holiday);
            //If the holiday doesn't fall in weekend
            if ($startDate <= $time_stamp && $time_stamp <= $endDate && date("N", $time_stamp) != 6 && date("N", $time_stamp) != 7)
                $workingDays--;
        }

        return $workingDays;
    }
</code>```

now that function is called about 40.000 times in a loop which takes about 20secs. Is there a more efficient way to do that? Or is the only option to cache it?

答:
I would suggest that you use the florianv/business composer library to do this:

https://github.com/florianv/business

Documentation is good and it runs faster than anything I have come up with on my own.

Once you define your parameters (opening hours for each day, holidays), you use the "timeline" function to determine how many days are between two dates for a business.

ContentLicense: CC BY-SA 4.0

Body:
I need to calculate the working days between a huge set of dates. Therefore I am searching for a function that does it quickly

Set all holidays:

public function getArrayOfHolidays($year, $holidays= array(), $format = 'Y-m-d')
    {
        $special1= new DateTime('2017-10-31');
        array_push($holidays, $special1->format($format));

        $newyear= new DateTime();
        $newyear->modify('1 january ' . $year);
        array_push($holidays, $newyear->format($format));

        $holyThreeKings= new DateTime();
        $holyThreeKings->modify('6 january ' . $year);
        array_push($holidays, $holyThreeKings->format($format));

        $layborDay= new DateTime();
        $layborDay->modify('1 may ' . $year);
        array_push($holidays, $layborDay->format($format));

        $unityDay= new DateTime();
        $unityDay->modify('3 october ' . $year);
        array_push($holidays, $unityDay->format($format));

        $allSaintsDay= new DateTime();
        $allSaintsDay->modify('1 november ' . $year);
        array_push($holidays, $allSaintsDay->format($format));

        $christmasEve= new DateTime();
        $christmasEve->modify('24 december ' . $year);
        array_push($holidays, $christmasEve->format($format));

        $christmas1 = new DateTime();
        $christmas1->modify('25 december ' . $year);
        array_push($holidays, $christmas1->format($format));

        $christmas2 = new DateTime();
        $christmas2->modify('26 december ' . $year);
        array_push($holidays, $christmas2->format($format));

        $silvester = new DateTime();
        $silvester->modify('31 december ' . $year);
        array_push($holidays, $silvester->format($format));

        $easterSunday= new DateTime(date('Y-m-d', easter_date($year)));
        $easterSunday->modify('+1 day');
        array_push($holidays, $easterSunday->format($format));

        $goodFriday = new DateTime($ostersonntag->format('Y-m-d'));
        $goodFriday->modify('last friday');
        array_push($holidays, $goodFriday->format($format));

        $easterMonday= new DateTime($ostersonntag->format('Y-m-d'));
        $easterMonday->modify('next monday');
        array_push($holidays, $easterMonday->format($format));

        $ascensionOfJesus= new DateTime($ostersonntag->format('Y-m-d'));
        $ascensionOfJesus->modify('+39 days');
        array_push($holidays, $ascensionOfJesus->format($format));

        $pentecostSunday= new DateTime($ostersonntag->format('Y-m-d'));
        $pentecostSunday->modify('+49 days');
        array_push($holidays, $pentecostSunday->format($format));

        $pentecostMonday= new DateTime($ostersonntag->format('Y-m-d'));
        $pentecostMonday->modify('+50 days');
        array_push($holidays, $pentecostMonday->format($format));

        $corpusChristi = new DateTime($pentecostMonday->format('Y-m-d'));
        $corpusChristi ->modify('next sunday');
        $corpusChristi ->modify('next thursday');
        array_push($holidays, $corpusChristi ->format($format));

        return $holidays;
    }

This runs a maximum of 3 times to make sure I have all holydays for the previous and the next year if there are dates calculated in between years. Therefore should not have that high of an impact. I still wanted to show it because there sure are better ways to do it? Of course I could pre-calculate the next X years and store them in a database, maybe that would be better.

now this is the function I use for calculating the workdays:

public function getWorkingDays($startDate, $endDate, $holidays)
    {
        // do strtotime calculations just once
        $endDate = strtotime($endDate);
        $startDate = strtotime($startDate);

        //The total number of days between the two dates. We compute the no. of seconds and divide it to 60*60*24
        //We add one to include both dates in the interval.
        $days = ($endDate - $startDate) / 86400 + 1;

        $no_full_weeks = floor($days / 7);
        $no_remaining_days = fmod($days, 7);

        //It will return 1 if it's Monday,.. ,7 for Sunday
        $the_first_day_of_week = date("N", $startDate);
        $the_last_day_of_week = date("N", $endDate);

        //---->The two can be equal in leap years when February has 29 days, the equal sign is added here
        //In the first case the whole interval is within a week, in the second case the interval falls in two weeks.
        if ($the_first_day_of_week <= $the_last_day_of_week) {
            if ($the_first_day_of_week <= 6 && 6 <= $the_last_day_of_week) $no_remaining_days--;
            if ($the_first_day_of_week <= 7 && 7 <= $the_last_day_of_week) $no_remaining_days--;
        } else {
            // (edit by Tokes to fix an edge case where the start day was a Sunday
            // and the end day was NOT a Saturday)

            // the day of the week for start is later than the day of the week for end
            if ($the_first_day_of_week == 7) {
                // if the start date is a Sunday, then we definitely subtract 1 day
                $no_remaining_days--;

                if ($the_last_day_of_week == 6) {
                    // if the end date is a Saturday, then we subtract another day
                    $no_remaining_days--;
                }
            } else {
                // the start date was a Saturday (or earlier), and the end date was (Mon..Fri)
                // so we skip an entire weekend and subtract 2 days
                $no_remaining_days -= 2;
            }
        }

        //The no. of business days is: (number of weeks between the two dates) * (5 working days) + the remainder
        //---->February in none leap years gave a remainder of 0 but still calculated weekends between first and last day, this is one way to fix it
        $workingDays = $no_full_weeks * 5;
        if ($no_remaining_days > 0) {
            $workingDays += $no_remaining_days;
        }

        //We subtract the holidays
        foreach ($holidays as $holiday) {
            $time_stamp = strtotime($holiday);
            //If the holiday doesn't fall in weekend
            if ($startDate <= $time_stamp && $time_stamp <= $endDate && date("N", $time_stamp) != 6 && date("N", $time_stamp) != 7)
                $workingDays--;
        }

        return $workingDays;
    }

now that function is called about 40.000 times in a loop which takes about 20secs. Is there a more efficient way to do that? Or is the only option to cache it?


问:
Find closest value to determined multiplicated value
I have two values. One is static and equals 24

```<code>int A = 24;
</code>```

and I have entries list :

```<code>[0, 21, 45, 76, 98]
</code>```

All of occurences comes in loop and I want to get closest value which divides on A :

```<code>0 - 24
21 - 24
45 - 48
76 - 72
98 - 96
</code>```

How to calculate this?

答:
To find the largest multiple x of a number n which is less than a given number a, you can use some arithmetic:

```<code>int x = n - n % a;
</code>```

Now if you want to get the nearest multiple, whether larger or smaller than a, you can use an if statement:

```<code>if (a - x > (x + n) - a)
    x = x + a
</code>```

For a list of numbers, just loop over them or use the Stream API.

Body:
I have two values. One is static and equals 24

int A = 24;

and I have entries list :

[0, 21, 45, 76, 98]

All of occurences comes in loop and I want to get closest value which divides on A :

0 - 24
21 - 24
45 - 48
76 - 72
98 - 96

How to calculate this?

Body:
To find the largest multiple x of a number n which is less than a given number a, you can use some arithmetic:

int x = n - n % a;

Now if you want to get the nearest multiple, whether larger or smaller than a, you can use an if statement:

if (a - x > (x + n) - a)
    x = x + a

For a list of numbers, just loop over them or use the Stream API.


问:
How can i pass ireport parameters to java method and how to use return value in my report
I am using  ireport tool in my application . There is a requirement to call java function from ireport tool . everything is ok but when i press "preview" button , ireport do nothing . ireport show me Just "design" window . please Help me
I have see this page
Writing methods in jasper report?
and do all recommendations.

答:
I solved the problem myself
Ive to chengedDate.Test.GreagoryToshamsi($F{datekh}) toDate.Test.GreagoryToshamsi($F{datekh}.toString())`


问:
How do you make a Concourse Linux Machine read executable files? (chmod style)
I am trying to get my Concourse CI Linux VM to run a shell script. But i keep getting the same error:

I fixed this locally (non VM, on a Mac) with chmod +x path/filename.sh to make it executable and adding !#/bin/sh to the shell script.

But i dont know how to get Concourse/VM to know that it's an executable? Is there a chmod command i should put into the task.sh? or the task.yml? Help!

my Concourse CI pipeline.yml

```<code>resources:
- name: my-git-repo
  type: git
  source:
    uri: git@github.com:org-name/my-git-repo.git
    branch: master
    private_key: {{git-private-key}}
- name: my-task
  type: git
  source:
    uri: git@gist.github.com:blahblahblah12345678910blah.git
    private_key: {{git-private-key}}

jobs:
- name: job-build-app
  plan:
  - get: my-git-repo
    trigger: true
  - get: task
  - task: run-build
    file: my-task/task.yml
</code>```

My task.yml:

```<code>---
platform: linux

image_resource:
  type: docker-image
  source: {repository: busybox}

inputs:
- name: my-task

run:
  path: ./my-task/task.sh
</code>```

My task.sh:

```<code>!#/bin/sh
echo this is my task shell script
</code>```

I expected this to just echo/log out the string above.

Instead i get the 500/permission denied error at the top.

答:
The file in the git repo has to be chmod +xed. You're gonna have a hard time doing that in a Gist, since that can't be set in the UI.

You could clone the gist, chmod +x, and re-push, or change your task to run bash my-task/task.sh instead, which won't require it to be executable:

```<code>run:
  path: bash
  args: [./my-task/task.sh]
</code>```

Body:
I am trying to get my Concourse CI Linux VM to run a shell script. But i keep getting the same error:

I fixed this locally (non VM, on a Mac) with chmod +x path/filename.sh to make it executable and adding !#/bin/sh to the shell script.

But i dont know how to get Concourse/VM to know that it's an executable? Is there a chmod command i should put into the task.sh? or the task.yml? Help!

my Concourse CI pipeline.yml

resources:
- name: my-git-repo
  type: git
  source:
    uri: git@github.com:org-name/my-git-repo.git
    branch: master
    private_key: {{git-private-key}}
- name: my-task
  type: git
  source:
    uri: git@gist.github.com:blahblahblah12345678910blah.git
    private_key: {{git-private-key}}

jobs:
- name: job-build-app
  plan:
  - get: my-git-repo
    trigger: true
  - get: task
  - task: run-build
    file: my-task/task.yml

My task.yml:

---
platform: linux

image_resource:
  type: docker-image
  source: {repository: busybox}

inputs:
- name: my-task

run:
  path: ./my-task/task.sh

My task.sh:

!#/bin/sh
echo this is my task shell script

I expected this to just echo/log out the string above.

Instead i get the 500/permission denied error at the top.

Body:
The file in the git repo has to be chmod +xed. You're gonna have a hard time doing that in a Gist, since that can't be set in the UI.

You could clone the gist, chmod +x, and re-push, or change your task to run bash my-task/task.sh instead, which won't require it to be executable:

run:
  path: bash
  args: [./my-task/task.sh]


问:
Application.screenupdating set to false doensn't work
So, I'm new to VBA and I have this code that adds a new row to two tables, one to a table on sheet3 which is visible and the other to a table on sheet5 which is hidden. My problem now is, with ScreenUpdating set to false at the beginning ad true at the end, when the code is run, the screen still flickers showing hidden sheets. How do I get this flickering to stop?

```<code>            Sub Add_Observation()
            '
            Application.ScreenUpdating = False
            Sheet3.Activate
            ActiveSheet.Unprotect
            Sheet5.Visible = True
                    Dim Ar As Integer, Br As Integer, A As Integer
                    '
                    Ar = Columns("B").Find(What:="S/N", After:=Range("B26")).Row 'Searching row of "S/N" header
                    Br = Range("B" & Ar).End(xlDown).Row 'Searching last row in EQUIPMENT table
                    A = (Br + 4)
                    B = (Br + 5)

                    Sheet5.Select
                    Dim Qr As Integer, Dr As Integer, D As Integer, D1 As Integer
                    '
                    Qr = Columns("B").Find(What:="S/N", After:=Range("B16")).Row
                    Dr = Range("B" & Qr).End(xlDown).Row
                    D = (Dr + 4)
                    D1 = (Dr + 2)

               Sheet3.Select
                Cells(Dr, "C").Select

            If Range(Cells(Ar, 1), Cells(A, 1)).EntireRow.Hidden = False Then

                                                                            Sheet3.Activate
                                                                                Rows(A).Insert Shift:=xlDown  'Inserting new row
                                                                                Cells(Br + 1, "B") = Cells(Br, "B") + 1 'Adding a sequential Number
                                                                                Rows(Br).Copy 'Copying format of last row
                                                                                Rows(Br + 1).PasteSpecial Paste:=xlPasteFormats 'Pasting format to new row
                                                                                Application.CutCopyMode = False 'Deactivating copy mode

            Sheet5.Select
            If Range(Cells(Qr, 1), Cells(D, 1)).EntireRow.Hidden = False Then
                                                                            Sheet5.Activate
                                                                                Selection.Rows(D).Insert Shift:=xlDown  'Inserting new row
                                                                                Rows(D1).Insert Shift:=xlDown
                                                                                Cells(Dr + 1, "B") = Cells(Dr, "B") + 1 'Adding a sequential Number
                                                                                Rows(Dr).Copy 'Copying format of last row
                                                                                Rows(Dr + 1).PasteSpecial Paste:=xlPasteFormats 'Pasting format to new row
                                                                                Application.CutCopyMode = False 'Deactivating copy mode

            Application.ScreenUpdating = True
            Else: GoTo G
                End If
            End If
</code>```

G:

```<code>            Sheet3.Activate
                Range(Cells(Ar, 1), Cells(A, 1)).Select
                  Selection.EntireRow.Hidden = False

            Sheet5.Activate
                Range(Cells(Qr, 1), Cells(D, 1)).Select
                Selection.EntireRow.Hidden = False

            Sheet3.Select

            Sheet5.Visible = False
            Cells(Br, "C").Select
            Sheet3.Activate
            ActiveSheet.Protect
            Application.ScreenUpdating = True
            End Sub
</code>```

答:
It's kind of a kludge, but try turning screen updating on and off outside your routine by wrapping the routine in another sub.

Delete all the application.screenupdating lines from your code, otherwise they will override the code below.

```<code>Public Sub callAdd_Observation()
    Application.ScreenUpdating = False
    Call Add_Observation
    Application.ScreenUpdating = True
End Sub
</code>```

Body:
So, I'm new to VBA and I have this code that adds a new row to two tables, one to a table on sheet3 which is visible and the other to a table on sheet5 which is hidden. My problem now is, with ScreenUpdating set to false at the beginning ad true at the end, when the code is run, the screen still flickers showing hidden sheets. How do I get this flickering to stop?

            Sub Add_Observation()
            '
            Application.ScreenUpdating = False
            Sheet3.Activate
            ActiveSheet.Unprotect
            Sheet5.Visible = True
                    Dim Ar As Integer, Br As Integer, A As Integer
                    '
                    Ar = Columns("B").Find(What:="S/N", After:=Range("B26")).Row 'Searching row of "S/N" header
                    Br = Range("B" & Ar).End(xlDown).Row 'Searching last row in EQUIPMENT table
                    A = (Br + 4)
                    B = (Br + 5)

                    Sheet5.Select
                    Dim Qr As Integer, Dr As Integer, D As Integer, D1 As Integer
                    '
                    Qr = Columns("B").Find(What:="S/N", After:=Range("B16")).Row
                    Dr = Range("B" & Qr).End(xlDown).Row
                    D = (Dr + 4)
                    D1 = (Dr + 2)

               Sheet3.Select
                Cells(Dr, "C").Select

            If Range(Cells(Ar, 1), Cells(A, 1)).EntireRow.Hidden = False Then

                                                                            Sheet3.Activate
                                                                                Rows(A).Insert Shift:=xlDown  'Inserting new row
                                                                                Cells(Br + 1, "B") = Cells(Br, "B") + 1 'Adding a sequential Number
                                                                                Rows(Br).Copy 'Copying format of last row
                                                                                Rows(Br + 1).PasteSpecial Paste:=xlPasteFormats 'Pasting format to new row
                                                                                Application.CutCopyMode = False 'Deactivating copy mode

            Sheet5.Select
            If Range(Cells(Qr, 1), Cells(D, 1)).EntireRow.Hidden = False Then
                                                                            Sheet5.Activate
                                                                                Selection.Rows(D).Insert Shift:=xlDown  'Inserting new row
                                                                                Rows(D1).Insert Shift:=xlDown
                                                                                Cells(Dr + 1, "B") = Cells(Dr, "B") + 1 'Adding a sequential Number
                                                                                Rows(Dr).Copy 'Copying format of last row
                                                                                Rows(Dr + 1).PasteSpecial Paste:=xlPasteFormats 'Pasting format to new row
                                                                                Application.CutCopyMode = False 'Deactivating copy mode

            Application.ScreenUpdating = True
            Else: GoTo G
                End If
            End If

G:

            Sheet3.Activate
                Range(Cells(Ar, 1), Cells(A, 1)).Select
                  Selection.EntireRow.Hidden = False

            Sheet5.Activate
                Range(Cells(Qr, 1), Cells(D, 1)).Select
                Selection.EntireRow.Hidden = False

            Sheet3.Select

            Sheet5.Visible = False
            Cells(Br, "C").Select
            Sheet3.Activate
            ActiveSheet.Protect
            Application.ScreenUpdating = True
            End Sub

Body:
It's kind of a kludge, but try turning screen updating on and off outside your routine by wrapping the routine in another sub.

Delete all the application.screenupdating lines from your code, otherwise they will override the code below.

Public Sub callAdd_Observation()
    Application.ScreenUpdating = False
    Call Add_Observation
    Application.ScreenUpdating = True
End Sub


问:
Is there any way to factor out "const" field initializers in C++
In C++ I have a class with some const fields:

```<code>class Obj {
   static const AType defaultAType;
   const AType &cRef;
public:
   Obj() : cRef(defaultAType) { ... }
   Obj(AType &aType) : cRef(aType) { ... }
};
</code>```

This is a simple example.  But a real one might have many fields, and several different constructor overloads.  References and "const" fields can't be initialized in the body of a constructor or in a method called by the constructor to the best of my knowledge.  But it is a pain in the butt to synchronously maintain a number of initializers in lets say 5 separate constructor overloads.  Is there any way to properly factor out these initializers (other than a macro) ??

答:
No. Unless you are using C++11, where you can initialize some of them in class definition:

```<code>struct B
{
    B(int) {}
    constexpr B(double) {}
};

class A
{
    const B b1 = 1;
    static constexpr B b2 = 2.0;
};
</code>```

For const values constructed from constructor input parameters, you need to use initializer list.

Body:
In C++ I have a class with some const fields:

class Obj {
   static const AType defaultAType;
   const AType &cRef;
public:
   Obj() : cRef(defaultAType) { ... }
   Obj(AType &aType) : cRef(aType) { ... }
};

This is a simple example.  But a real one might have many fields, and several different constructor overloads.  References and "const" fields can't be initialized in the body of a constructor or in a method called by the constructor to the best of my knowledge.  But it is a pain in the butt to synchronously maintain a number of initializers in lets say 5 separate constructor overloads.  Is there any way to properly factor out these initializers (other than a macro) ??

Body:
No. Unless you are using C++11, where you can initialize some of them in class definition:

struct B
{
    B(int) {}
    constexpr B(double) {}
};

class A
{
    const B b1 = 1;
    static constexpr B b2 = 2.0;
};

For const values constructed from constructor input parameters, you need to use initializer list.


问:
Component connected to withRouter not receiving correct match properties
I'm having some trouble getting the correct match properties to show in my component connected to withRouter

My router map looks like this

```<code><BrowserRouter>
  <div>
    <Switch>
      <Route path="/" component={HomePage} />
      <Route path="/start/:short_code/*" render={() => <div>Magic</div>} />
      <Route path="/events" component={EventsPage} exact/>
      <Route path="/events/:auction_code" />
      <Route component={NotFoundPage} />
    </Switch>
    <MainMenu />
    <LoginPage />
    <HoldersDrawer />
  </div>
</BrowserRouter>
</code>```

In my HomePage component I have it wrapped in both withRouter and redux

export default withRouter(connect(mapStateToProps)(HomePage));

However, anywhere I attempt to access this.props.match I am only seeing

```<code>{
    isExact:false,
    params:{},
    path:"/",
    url:"/"
}
</code>```

Even if I have set my URL to one of the routes I've outlined

The home page has a QR scanner on it and I want that active no matter which route the user is on, but I also want to be able to access the current route the user is on, on the HomePage
For instance, the user can navigate to events/auction_code and when they perform and action I need to be able to pass the relevant auction_code to the API call said action calls, currently I have to parse that out of the current location pathname data. It would be nice if I could just get it from the match.params object.

Can someone see something I may be doing wrong here that would cause this issue?

答:
The reason that withRouter doesn't provide you the match props of the matched Route is because withRouter gives you access to the history object’s properties and the closest <Route>'s match and in your case the HomePage doesn't have any closest matched Route.

You could achieve what you need by passing on the handler to the Routed component and lifting the action up to the Component that renders the Route. Something like

```<code><BrowserRouter>
  <App/>
</BrowserRouter>
</code>```

and defining App to have handlers like

```<code>class App extends React.Component {
    handlerFunction = (match) => {
       //your action based on match here
    }

    render() {
       return (
         <div>
            <Switch>
              <Route path="/" component={HomePage} />
              <Route path="/start/:short_code/*" render={() => <div>Magic</div>} />
              <Route path="/events" render={(props) => <EventsPage handler={this.handlerFunction} {...props}/>} exact/>
              <Route path="/events/:auction_code" />
              <Route component={NotFoundPage} />
            </Switch>
            <MainMenu />
            <LoginPage />
            <HoldersDrawer />
        </div>
       )
    }
}
</code>```

Body:
I'm having some trouble getting the correct match properties to show in my component connected to withRouter

My router map looks like this

<BrowserRouter>

    <Switch>
      <Route path="/" component={HomePage} />
      <Route path="/start/:short_code/*" render={() =>
Magic
} />
      <Route path="/events" component={EventsPage} exact/>
      <Route path="/events/:auction_code" />
      <Route component={NotFoundPage} />
    </Switch>
    <MainMenu />
    <LoginPage />
    <HoldersDrawer />

</BrowserRouter>

In my HomePage component I have it wrapped in both withRouter and redux

export default withRouter(connect(mapStateToProps)(HomePage));

However, anywhere I attempt to access this.props.match I am only seeing

{
    isExact:false,
    params:{},
    path:"/",
    url:"/"
}

Even if I have set my URL to one of the routes I've outlined

The home page has a QR scanner on it and I want that active no matter which route the user is on, but I also want to be able to access the current route the user is on, on the HomePage
For instance, the user can navigate to events/auction_code and when they perform and action I need to be able to pass the relevant auction_code to the API call said action calls, currently I have to parse that out of the current location pathname data. It would be nice if I could just get it from the match.params object.

Can someone see something I may be doing wrong here that would cause this issue?

Body:
The reason that withRouter doesn't provide you the match props of the matched Route is because withRouter gives you access to the history object’s properties and the closest <Route>'s match and in your case the HomePage doesn't have any closest matched Route.

You could achieve what you need by passing on the handler to the Routed component and lifting the action up to the Component that renders the Route. Something like

<BrowserRouter>
  <App/>
</BrowserRouter>

and defining App to have handlers like

class App extends React.Component {
    handlerFunction = (match) => {
       //your action based on match here
    }

    render() {
       return (
         <div>
            <Switch>
              <Route path="/" component={HomePage} />
              <Route path="/start/:short_code/*" render={() => <div>Magic</div>} />
              <Route path="/events" render={(props) => <EventsPage handler={this.handlerFunction} {...props}/>} exact/>
              <Route path="/events/:auction_code" />
              <Route component={NotFoundPage} />
            </Switch>
            <MainMenu />
            <LoginPage />
            <HoldersDrawer />
        </div>
       )
    }
}


问:
Handle SIGTERM with the cluster module
Hi there where can i find the source code for signal handling when using the cluster module? I want to handle a SIGTERM so that i can "graceful" close the http server but as soon as the master process receives this signal the http server stops listening.

"Termination" handler (This function gets called when SIGTERM or SIGINT)

```<code>function handleTermination(httpServer?: http.Server) {
    if (Store.receive<symbol, boolean>(STORE_KEYS.isTerminating)) {
        return
    }

    Store.store<symbol, boolean>(STORE_KEYS.isTerminating, true)

    if (httpServer) {
        if (!httpServer.listening || isDevelopment) {
            closeAll()
            process.exit(0)
            return
        }

        setTimeout(() => {
            if (process.env.GRACEFUL_SHUTDOWN !== undefined) {
                gracefulCloseSockets()
            }

            httpServer.close(endProcess)
        }, 5000)
    } else {
        endProcess()
    }
}
</code>```

Example router handler

```<code>function timerHandler(_req: RequestObject, respond: ResponseHandler) {
    setTimeout(() => respond('ok'), 2000)
}
</code>```

答: How about process.on( "exit", cb) or process.on( "beforeExit", cb ) ?</p>

Title: Handle SIGTERM with the cluster module

Body:
Hi there where can i find the source code for signal handling when using the cluster module? I want to handle a SIGTERM so that i can "graceful" close the http server but as soon as the master process receives this signal the http server stops listening.

"Termination" handler (This function gets called when SIGTERM or SIGINT)

function handleTermination(httpServer?: http.Server) {
    if (Store.receive<symbol, boolean>(STORE_KEYS.isTerminating)) {
        return
    }

    Store.store<symbol, boolean>(STORE_KEYS.isTerminating, true)

    if (httpServer) {
        if (!httpServer.listening || isDevelopment) {
            closeAll()
            process.exit(0)
            return
        }

        setTimeout(() => {
            if (process.env.GRACEFUL_SHUTDOWN !== undefined) {
                gracefulCloseSockets()
            }

            httpServer.close(endProcess)
        }, 5000)
    } else {
        endProcess()
    }
}

Example router handler

function timerHandler(_req: RequestObject, respond: ResponseHandler) {
    setTimeout(() => respond('ok'), 2000)
}


问:
Gesture problem: UISwipeGestureRecognizer + UISlider
Got a gesture related problem. I implemented UISwipeGestureRecognizer to get swipe left and right events and that is working fine. However the problem I'm facing is that the UISlider's I have in the same view are not playing nice. The sliding motion of the sliders is being mistaken as a swipe left/right.

Any one experienced this problem before, got any ideas how to correct it?

Many thanks.

Here is the code contained within the view controller:

```<code> - (void)viewDidLoad {

            [super viewDidLoad];

                //Setup handling of LEFT and RIGHT swipes
             UISwipeGestureRecognizer *recognizer;

                recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
                [recognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
                [[self view] addGestureRecognizer:recognizer];
                [recognizer release];

                recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
                [recognizer setDirection:(UISwipeGestureRecognizerDirectionLeft)];
                [[self view] addGestureRecognizer:recognizer];
                [recognizer release];
        }

    -(void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer {

      if (recognizer.direction == UISwipeGestureRecognizerDirectionRight) {
       NSLog(@"Swipe Right");
       //Do stuff
      }

      if (recognizer.direction == UISwipeGestureRecognizerDirectionLeft) {
       NSLog(@"Swipe Left");
       //Do stuff
      }
    }
</code>```

答:
The simplest way to handle this is probably to prevent the gesture recognizer from seeing touches on your slider. You can do that by setting yourself as the delegate, and then implementing

```<code>- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if ([touch.view isKindOfClass:[UISlider class]]) {
        // prevent recognizing touches on the slider
        return NO;
    }
    return YES;
}
</code>```

If this doesn't work, it's possible the slider actually has subviews that receive the touch, so you could walk up the superview chain, testing each view along the way.

Body:
Got a gesture related problem. I implemented UISwipeGestureRecognizer to get swipe left and right events and that is working fine. However the problem I'm facing is that the UISlider's I have in the same view are not playing nice. The sliding motion of the sliders is being mistaken as a swipe left/right.

Any one experienced this problem before, got any ideas how to correct it?

Many thanks.

Here is the code contained within the view controller:

 - (void)viewDidLoad {

            [super viewDidLoad];

                //Setup handling of LEFT and RIGHT swipes
             UISwipeGestureRecognizer *recognizer;

                recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
                [recognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
                [[self view] addGestureRecognizer:recognizer];
                [recognizer release];

                recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
                [recognizer setDirection:(UISwipeGestureRecognizerDirectionLeft)];
                [[self view] addGestureRecognizer:recognizer];
                [recognizer release];
        }

    -(void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer {

      if (recognizer.direction == UISwipeGestureRecognizerDirectionRight) {
       NSLog(@"Swipe Right");
       //Do stuff
      }

      if (recognizer.direction == UISwipeGestureRecognizerDirectionLeft) {
       NSLog(@"Swipe Left");
       //Do stuff
      }
    }

Body:
The simplest way to handle this is probably to prevent the gesture recognizer from seeing touches on your slider. You can do that by setting yourself as the delegate, and then implementing

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if ([touch.view isKindOfClass:[UISlider class]]) {
        // prevent recognizing touches on the slider
        return NO;
    }
    return YES;
}

If this doesn't work, it's possible the slider actually has subviews that receive the touch, so you could walk up the superview chain, testing each view along the way.


问:
How can I force the driver to click on a pop up on a page which has not completed loading
I'm using java with selenium IEDriverServer. I would like to know if is possible to click on a pop up on a page which has not completed loading. When I get the pop up, my code is not running until I click on Ok on pop up.

Thanks.

答:
As you mentioned if is possible to click on a pop up I presume it's a JavaScript Popup.

Essentially, until & unless the synchronous/asynchronous JavaScript/AJAX Calls gets executed completely the Page Loading won't be complete. Hence, invoking click() method while Page Loading may not fetch optimum results.


问:
How to switch from the default ConstraintLayout to RelativeLayout in Android Studio
I have the latest android Studio (2.3 beta 3) and it seems ConstraintLayout is the default when creating a project. How can I make Android Studio use the RelativeLayout as the default layout element for new projects ?

答: The easiest way would be to select Relativelayout from the Pallete, and then use it.


问:
Remove black bars from either side of an embedded YouTube video

I've embedded a YouTube Video on this webpage.

I want to remove the two black bars that appear when I click play.

See screenshot here:

I searched on Stack Overflow and the closest I found was this, but it didn't help:

How to remove black bar from the YouTube videos

So I tried adjusting the video with the following CSS:

```<code>  html5-video-container {
      background-position: center;
      background-repeat: no-repeat;
      width: 100%;
      height: 100%;
      left: 0px;
      top: 0px;
      position: absolute;
    }

    video.video-stream.html5-main-video {
      background-position: center;
      background-repeat: no-repeat;
      width: 100%;
      height: 100%;
      left: 0px;
      top: 0px;
      position: absolute;
    }
</code>```

At first I tried just adjusting the video, then I tried adjusting the video container element as well, but neither worked.

Can any CSS gurus help me please?

I would like the video to be the same size as the thumbnail that appears before one clicks play.

Thanks in advance.

答:
This seems to be more of an issue with the YouTube frame than css.

The YouTube frame is as wide as the page, but as tall as the actual video. That means there is going to be a lot of extra space, it has to fill it with something!

As long as the YouTube frame is wider than the actual video, there is going to be black space. You need to make the aspect ratio of the YouTube frame match the actual video.

Body:
I've embedded a YouTube Video on this webpage.

I want to remove the two black bars that appear when I click play.

See screenshot here:

I searched on Stack Overflow and the closest I found was this, but it didn't help:

How to remove black bar from the YouTube videos

So I tried adjusting the video with the following CSS:

  html5-video-container {
      background-position: center;
      background-repeat: no-repeat;
      width: 100%;
      height: 100%;
      left: 0px;
      top: 0px;
      position: absolute;
    }

    video.video-stream.html5-main-video {
      background-position: center;
      background-repeat: no-repeat;
      width: 100%;
      height: 100%;
      left: 0px;
      top: 0px;
      position: absolute;
    }

At first I tried just adjusting the video, then I tried adjusting the video container element as well, but neither worked.

Can any CSS gurus help me please?

I would like the video to be the same size as the thumbnail that appears before one clicks play.

Thanks in advance.


问:
Convert number to string php with text
Is there a way to convert a number to a string with text at certain points?

Example:

700 would be 7 minutes 00 seconds

60 would be 60 seconds

140 would be1 minute 40 seconds

so the 3rd number would add minutes and at the beginning of the number would always be seconds

I have tried number_format($score, 2, "minutes ") and other variations but it seems to not work as I need since 7000 would be 70 minutes and 00 seconds and so on.

答:
I think regex is the best option as it can be two or three (?) digit minutes.

This will match two last digits as seconds, and any digits before that as minutes.

```<code>$n = 700;

Preg_match("/(\d*)(\d{2})/", $n, $match);

Echo ($match[1] ?: 0) . " minutes and ". $match[2] . " seconds";
</code>```

https://3v4l.org/NvaGp

Or you can use list() to make each array item a variable.

```<code>$n = 700;

Preg_match("/(\d*)(\d{2})/", $n, $match);
List($n, $minutes, $seconds) = $match;

Echo ($minutes ?: 0) . " minutes and ". $seconds . " seconds";
</code>```

https://3v4l.org/grWaV

Title: Convert number to string php with text

Body:
I think regex is the best option as it can be two or three (?) digit minutes.

This will match two last digits as seconds, and any digits before that as minutes.

$n = 700;

Preg_match("/(\d*)(\d{2})/", $n, $match);

Echo ($match[1] ?: 0) . " minutes and ". $match[2] . " seconds";

https://3v4l.org/NvaGp

Or you can use list() to make each array item a variable.

$n = 700;

Preg_match("/(\d*)(\d{2})/", $n, $match);
List($n, $minutes, $seconds) = $match;

Echo ($minutes ?: 0) . " minutes and ". $seconds . " seconds";

https://3v4l.org/grWaV


问:
How to automatic convert excel 97 to xlsx
I have a source system which contains excel 97 Data (.xls). I want to use a tool or program which can help me to automatically convert this data to .xlsx (new Excel).
After that I will use Talend or SSIS to load data from xlsx to datawarehouse.

Does anybody know which tools I can use to convert the old excel file automatically?

答:
First of all Sql server integration services can read all Excel files formats including Excel 97, just use the Excel Connection Manager for that

1st Solution - Using Microsoft.Interop.Excel.dll

You can write a code in c# or vb.net using Microsoft.Interop.Excel library to automate the Excel file opening and saving:

Example

Function

```<code>private void ConvertXlsToXlsx(string strFile)
{
    Excel.Application app = new Excel.Application();
    Excel.Workbook wb = app.Workbooks.Open(strFile);
    wb.SaveAs(strFile + "x", Excel.XlFileFormat.xlWorkbookNormal);
    wb.Close(false);
    app.Quit();
    Console.WriteLine("Done!");
}
</code>```

Code

```<code>String Filename;
Filename = "C:\\File.xls";
ConvertXlsToXlsx(Filename);
</code>```

2nd Solution - Using Office Migration Planning Manager

According to this Super User answer, you can use Office Migration Planning Manager.

The toolkit also contains the Office File Converter (OFC), which enables bulk document conversions from binary to OpenXML formats.
  (Technet)

Overview on Technet

Download Link

3rd Solution - Third party applications

Just use google to search for "Xls to Xlsx converter" and you will find a huge number of online and offline converters that can be used.

Body:
First of all Sql server integration services can read all Excel files formats including Excel 97, just use the Excel Connection Manager for that

1st Solution - Using Microsoft.Interop.Excel.dll

You can write a code in c# or vb.net using Microsoft.Interop.Excel library to automate the Excel file opening and saving:

Example

Function

private void ConvertXlsToXlsx(string strFile)
{
    Excel.Application app = new Excel.Application();
    Excel.Workbook wb = app.Workbooks.Open(strFile);
    wb.SaveAs(strFile + "x", Excel.XlFileFormat.xlWorkbookNormal);
    wb.Close(false);
    app.Quit();
    Console.WriteLine("Done!");
}

Code

String Filename;
Filename = "C:\\File.xls";
ConvertXlsToXlsx(Filename);

2nd Solution - Using Office Migration Planning Manager

According to this Super User answer, you can use Office Migration Planning Manager.

The toolkit also contains the Office File Converter (OFC), which enables bulk document conversions from binary to OpenXML formats.
  (Technet)

Overview on Technet

Download Link

3rd Solution - Third party applications

Just use google to search for "Xls to Xlsx converter" and you will find a huge number of online and offline converters that can be used.