问:
Angular 2, routing URL path to route in the app
I have an Angular 2 app hosted on S3. The routing file looks like this.

```<code>const APP_ROUTES: Routes = [
  { path: 'checkout', component: CheckoutComponent },
  { path: 'thankyou', component: ThankyouComponent },
  { path: 'lander', component: LanderComponent },
  { path: '', component: LanderComponent }
];
</code>```

If the user enters www.example.com/checkout I would like it to take them to the checkout route on the app. I figured it would just do this, but S3 is giving me the error No Such Key. Is there a way to do this in Angular 2, or is it something I need to set in S3?  I think the problem is S3 is going to the example.com bucket and then expecting a folder checkout. How would I have it not do that and just the app along with whatever route is specified after the URL?

答:
RouterModule.forRoot(APP_ROUTES)

{ useHash: true } is an option. When you add it, the URL uses Hashes.
Without it, no hashes.

Body:
I have an Angular 2 app hosted on S3. The routing file looks like this.

const APP_ROUTES: Routes = [
  { path: 'checkout', component: CheckoutComponent },
  { path: 'thankyou', component: ThankyouComponent },
  { path: 'lander', component: LanderComponent },
  { path: '', component: LanderComponent }
];

If the user enters www.example.com/checkout I would like it to take them to the checkout route on the app. I figured it would just do this, but S3 is giving me the error No Such Key. Is there a way to do this in Angular 2, or is it something I need to set in S3?  I think the problem is S3 is going to the example.com bucket and then expecting a folder checkout. How would I have it not do that and just the app along with whatever route is specified after the URL?


来源: stackexchange

问:
Appending a div onclick
I have a button and a div, i want to append this div once every time i click on the button, but i have a problem, the HTML code for this div is very large and i don't want that, so my question is there another method to append this div without putting the whole code in my js code? and another problem i want to append the div once only on each click but it appends it multiple times, Here is an example of what I'm talking about, i replaced my large HTML code with a small one, so here is my code:

$(".appendbtn").click(function () {
   $(".appendme").append('
The div that should be appended
');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script
  src="https://code.jquery.com/jquery-2.2.3.min.js"
  integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo="
  crossorigin="anonymous"></script>
<div class="appendme">The div that should be appended</div>
<button class="appendbtn" type="button">Click to append</button></code>```

答:
Lots of answers here point out your naming error ('appendme' used for the container and the item being appended) but your issue is that you have a large string that you want to append. The object that you want to append could be placed within a script tag:

```<code><script type="text/html" id="appendTemplate">
    <div>The div that should be appended</div>
</script>
</code>```

And now your append code will be:

```<code>$(".appendbtn").click(function () {
    var template = $('#appendTemplate").html();
    $(".appendme").append(template);
});
</code>```

When the button is clicked, the html content of the script tag is read into the variable 'template' which you then append to your target element.

ContentLicense: CC BY-SA 3.0

Title: Appending a div onclick

Body:
I have a button and a div, i want to append this div once every time i click on the button, but i have a problem, the HTML code for this div is very large and i don't want that, so my question is there another method to append this div without putting the whole code in my js code? and another problem i want to append the div once only on each click but it appends it multiple times, Here is an example of what I'm talking about, i replaced my large HTML code with a small one, so here is my code:

$(".appendbtn").click(function () {
   $(".appendme").append('
The div that should be appended
');
});

The div that should be appended

<button class="appendbtn" type="button">Click to append</button>

Body:
Lots of answers here point out your naming error ('appendme' used for the container and the item being appended) but your issue is that you have a large string that you want to append. The object that you want to append could be placed within a script tag:

<script type="text/html" id="appendTemplate">
    <div>The div that should be appended</div>
</script>

And now your append code will be:

$(".appendbtn").click(function () {
    var template = $('#appendTemplate").html();
    $(".appendme").append(template);
});

When the button is clicked, the html content of the script tag is read into the variable 'template' which you then append to your target element.


问:
Jquery Add class to next image in  tag using JQuery
How can jQuery be used to add class to next image?

I have set of images in webpage using for loop. They are displayed in table rows.

```<code><table class="table table-bordered">
  <?php
    <td><img class="img1" src="http://s5.tinypic.com/30v0ncn_th.jpg"/></td>

    for ($x = 0; $x < 5; $x++) { ?>
      <td>
        <img class="loopimg" src="http://s5.tinypic.com/30v0ncn_th.jpg"/>
      </td>
    <?php  } ?>
</table>
</code>```

What I would like to achieve is when i click on first image (class="img1"), it add class to the next image , clicking on that would add class to the next image.

```<code>$('.img1').click(function(){
  $(this).parent().next("td").addClass("active");
  alert("class");
});
</code>```

This Jquery code add "active" class to next  tag, i would like class to be added to next image. Thank you in advance

答:
Firstly note that your HTML is invalid as you need to have a
 wrapping all the .

To solve your issue you can get the parent tr from the clicked img element, then find the first .loopimg element within that, like this:

```<code>$('.img1').click(function(){
  $(this).closest('tr').find('.loopimg:first').addClass("active");
});
</code>```

There are also some major issues with your PHP syntax - however I'm going to assume these are just caused by you transcribing the code to the question, as it wouldn't work at all in its current state.

Title: Jquery Add class to next image in <td> tag using JQuery

Body:
How can jQuery be used to add class to next image?

I have set of images in webpage using for loop. They are displayed in table rows.

  <?php

    for ($x = 0; $x < 5; $x++) { ?>

    <?php  } ?>

What I would like to achieve is when i click on first image (class="img1"), it add class to the next image , clicking on that would add class to the next image.

$('.img1').click(function(){
  $(this).parent().next("td").addClass("active");
  alert("class");
});

This Jquery code add "active" class to next  tag, i would like class to be added to next image. Thank you in advance

Body:
Firstly note that your HTML is invalid as you need to have a <tr> wrapping all the <td>.

To solve your issue you can get the parent tr from the clicked img element, then find the first .loopimg element within that, like this:

$('.img1').click(function(){
  $(this).closest('tr').find('.loopimg:first').addClass("active");
});

There are also some major issues with your PHP syntax - however I'm going to assume these are just caused by you transcribing the code to the question, as it wouldn't work at all in its current state.


问:
Accessing base member from derived class in function
I have created Angular2 + Typescript project. I have there alot of tables so I want to have something like base component for that.

There is my base component:

```<code>export abstract class ManagementComponent<T> implements BaseComponent {

    protected selectedItem: T;

    protected items: Array<T>;

}
</code>```

Now there is my child component. I would like to get all items from http and then assign it into base class

```<code>export class CompetencesComponent extends ManagementComponent<Competence> implements OnInit {

    thisField: string;

    constructor(private service: CompetencesService) {
        super();

    }

    ngOnInit(): void {
        this.getCompetences();
    }

    private getCompetences() {
        this.service.getCompetences().subscribe(function (competences: Array<Competence>) {
            this.thisField // ok
            this.items  // not ok
        })
    }
}
</code>```

Any idea how I can access base fields from subscribe methods?

答:
Currently I'd expect that you wouldn't be able to reference either thisField or items, because you should be losing the this context inside your subscription function.

You can switch to an arrow function to retain context:

```<code>this.service.getCompetences().subscribe((competences: Array<Competence>) => { ... }
</code>```

Body:
I have created Angular2 + Typescript project. I have there alot of tables so I want to have something like base component for that.

There is my base component:

export abstract class ManagementComponent<T> implements BaseComponent {

    protected selectedItem: T;

    protected items: Array<T>;

}

Now there is my child component. I would like to get all items from http and then assign it into base class

export class CompetencesComponent extends ManagementComponent<Competence> implements OnInit {

    thisField: string;

    constructor(private service: CompetencesService) {
        super();

    }

    ngOnInit(): void {
        this.getCompetences();
    }

    private getCompetences() {
        this.service.getCompetences().subscribe(function (competences: Array<Competence>) {
            this.thisField // ok
            this.items  // not ok
        })
    }
}

Any idea how I can access base fields from subscribe methods?

Body:
Currently I'd expect that you wouldn't be able to reference either thisField or items, because you should be losing the this context inside your subscription function.

You can switch to an arrow function to retain context:

this.service.getCompetences().subscribe((competences: Array<Competence>) => { ... }


问:
Retrieve url of uploaded file from google form
I have found an extremely good google script for a google form that allows me to retrieve the answers of a google form in a spreadsheet along with the "getEditResponseUrl()" that will help me build a database that can be modified through the google form.

However, I am struggling in getting the url of an "upload file question". The question where the user is supposed to upload a file is the fourth one "facture".

The answer I get in my spreadsheet is only "[Ljava.lang.Object;@508c8b8b" but not the file.

Any idea how to make this work so that I get the url of the file that was uploaded by the user ?

Thank you and Kind regards

```<code>var ss = SpreadsheetApp.openById("spreadsheeturl");  // to be customised
var responseSheet = "Database";  // to be customised

function submitFormFunc(e) {
var items = e.response.getItemResponses();
  var responses={};
  for(var i = 0; i< items.length; i++) {
  responses[items[i].getItem().getTitle()]=items[i].getResponse();
   }

  var responseRow = [];
  responseRow.push(e.response.getTimestamp().toString());
  responseRow.push(e.response.getId());
  responseRow.push(responses["Challenge"]);  // to be customised
  responseRow.push(responses["Client"]);
  responseRow.push(responses["Date"]);
  responseRow.push(responses["Facture"]);
 // to be customised
  // add as many as needed

  responseRow.push(FormApp.getActiveForm().getResponse(e.response.getId()).getEditResponseUrl());

  var isNewItem = alreadyExist(ss,e.response.getId());
  if(isNewItem<0){
    ss.getSheetByName(responseSheet).appendRow(responseRow);
  }
  else{
    ss.getSheetByName(responseSheet).getRange(isNewItem+2, 1, 1, 6).setValues([responseRow]);
  }
}

function alreadyExist(ss,id){
  var ids = ss.getSheetByName(responseSheet).getRange("B2:B").getValues();
  for(var i=0; i< ids.length; i++){
    if(ids[i][0]===id){
      return(i);
    }
  }
  return(-1);
}
</code>```

答:
Here's a snippet from the Form Notifications add-on that converts the uploaded file ids into Google Drive URLs and concatenates the result in case of multiple uploads.</p>

```<code> var urls = answer.toString().split(",").map(function(f) {
                return "https://drive.google.com/open?id=" + f;
             }).join(", ");
</code>```

Body:
I have found an extremely good google script for a google form that allows me to retrieve the answers of a google form in a spreadsheet along with the "getEditResponseUrl()" that will help me build a database that can be modified through the google form.

However, I am struggling in getting the url of an "upload file question". The question where the user is supposed to upload a file is the fourth one "facture".

The answer I get in my spreadsheet is only "[Ljava.lang.Object;@508c8b8b" but not the file.

Any idea how to make this work so that I get the url of the file that was uploaded by the user ?

Thank you and Kind regards

var ss = SpreadsheetApp.openById("spreadsheeturl");  // to be customised
var responseSheet = "Database";  // to be customised

function submitFormFunc(e) {
var items = e.response.getItemResponses();
  var responses={};
  for(var i = 0; i< items.length; i++) {
  responses[items[i].getItem().getTitle()]=items[i].getResponse();
   }

  var responseRow = [];
  responseRow.push(e.response.getTimestamp().toString());
  responseRow.push(e.response.getId());
  responseRow.push(responses["Challenge"]);  // to be customised
  responseRow.push(responses["Client"]);
  responseRow.push(responses["Date"]);
  responseRow.push(responses["Facture"]);
 // to be customised
  // add as many as needed

  responseRow.push(FormApp.getActiveForm().getResponse(e.response.getId()).getEditResponseUrl());

  var isNewItem = alreadyExist(ss,e.response.getId());
  if(isNewItem<0){
    ss.getSheetByName(responseSheet).appendRow(responseRow);
  }
  else{
    ss.getSheetByName(responseSheet).getRange(isNewItem+2, 1, 1, 6).setValues([responseRow]);
  }
}

function alreadyExist(ss,id){
  var ids = ss.getSheetByName(responseSheet).getRange("B2:B").getValues();
  for(var i=0; i< ids.length; i++){
    if(ids[i][0]===id){
      return(i);
    }
  }
  return(-1);
}

Body:
Here's a snippet from the Form Notifications add-on that converts the uploaded file ids into Google Drive URLs and concatenates the result in case of multiple uploads.

 var urls = answer.toString().split(",").map(function(f) {
                return "https://drive.google.com/open?id=" + f;
             }).join(", ");


问:
Python loop print change of state only once
I’m pretty new to Python and I just start to understand the basics.
I’m trying to run a script in a loop to check the temperatures and if the outside temp getting higher than inside or the opposite, the function should print it once and continue to check every 5 seconds, for changed state.
I found a similar questions what was very helpful but if I execute the code it print the outside temp is higher, next I heat up the inside sensor and it prints that it is inside higher, all good except that it doesn’t continue, the loop works but it doesn’t recognize the next change of state.
. </p>

```<code>import RPi.GPIO as GPIO
import time
sensor_name_0 = "test"
printed_out = False
printed_in = False

try:
    while True:
    if sensor_name_0:
        sensor_0 = open('/sys/devices/w1_bus_master1/w1_master_slaves','r').read().split('\n')[0]
        sensor_1 = open('/sys/devices/w1_bus_master1/w1_master_slaves','r').read().split('\n')[1]

        sensorpath = "/sys/bus/w1/devices/"
        sensorfile = "/w1_slave"

    def callsensor_0(sensor_0):
        f = open(sensorpath + sensor_0 + sensorfile, 'r')
        lines = f.readlines()
        f.close()
        temp_line = lines[1].find('t=')
        temp_output = lines[1].strip() [temp_line+2:]
        temp_celsius = float(temp_output) / 1000
        return temp_celsius

    def callsensor_1(sensor_1):
        f = open(sensorpath + sensor_1 + sensorfile, 'r')
        lines = f.readlines()
        f.close()
        temp_line = lines[1].find('t=')
        temp_output = lines[1].strip() [temp_line+2:]
        temp_celsius = float(temp_output) / 1000
        return temp_celsius

    outside = (str('%.1f' % float(callsensor_0(sensor_0))).rstrip('0').rstrip('.'))
    inside = (str('%.1f' % float(callsensor_1(sensor_1))).rstrip('0').rstrip('.'))
    print "loop"

    if outside > inside and not printed_out:
        printed_out = True
        print "outside is higher then inside"
        print  outside

    if outside < inside and not printed_in:
        printed_in = True
        print "inside is higher then outside"
        print  inside

    time.sleep(5)

except KeyboardInterrupt:
print('interrupted!')
</code>```

答: Both the flags printed_in and printed_out are set to True after printing the corresponding messages. You are not setting them back to False because of which the if condition will never get satisified and the messages will never print again. You should set printed_out to False in the if block where you are printing that the inside temperature is higher and similarly set printed_in to False in the if block where you are printing outside temperature is higher

Body:
I’m pretty new to Python and I just start to understand the basics.
I’m trying to run a script in a loop to check the temperatures and if the outside temp getting higher than inside or the opposite, the function should print it once and continue to check every 5 seconds, for changed state.
I found a similar questions what was very helpful but if I execute the code it print the outside temp is higher, next I heat up the inside sensor and it prints that it is inside higher, all good except that it doesn’t continue, the loop works but it doesn’t recognize the next change of state.
.

import RPi.GPIO as GPIO
import time
sensor_name_0 = "test"
printed_out = False
printed_in = False

try:
    while True:
    if sensor_name_0:
        sensor_0 = open('/sys/devices/w1_bus_master1/w1_master_slaves','r').read().split('\n')[0]
        sensor_1 = open('/sys/devices/w1_bus_master1/w1_master_slaves','r').read().split('\n')[1]

        sensorpath = "/sys/bus/w1/devices/"
        sensorfile = "/w1_slave"

    def callsensor_0(sensor_0):
        f = open(sensorpath + sensor_0 + sensorfile, 'r')
        lines = f.readlines()
        f.close()
        temp_line = lines[1].find('t=')
        temp_output = lines[1].strip() [temp_line+2:]
        temp_celsius = float(temp_output) / 1000
        return temp_celsius

    def callsensor_1(sensor_1):
        f = open(sensorpath + sensor_1 + sensorfile, 'r')
        lines = f.readlines()
        f.close()
        temp_line = lines[1].find('t=')
        temp_output = lines[1].strip() [temp_line+2:]
        temp_celsius = float(temp_output) / 1000
        return temp_celsius

    outside = (str('%.1f' % float(callsensor_0(sensor_0))).rstrip('0').rstrip('.'))
    inside = (str('%.1f' % float(callsensor_1(sensor_1))).rstrip('0').rstrip('.'))
    print "loop"

    if outside > inside and not printed_out:
        printed_out = True
        print "outside is higher then inside"
        print  outside

    if outside < inside and not printed_in:
        printed_in = True
        print "inside is higher then outside"
        print  inside

    time.sleep(5)

except KeyboardInterrupt:
print('interrupted!')


问:
Any example or scenario where Angular router Params Observable is usable?
I was learning on Angular Router Params Observable in Pluralsight course(Routing).

```<code>this.route.params.subscribe(params => {let id = params['id']})});
</code>```

I understand within component, when there is change in params, we use above code.

I would like to know an example, or scenario this plays role in real time application?

答:
I use that in my application like this:

Inside component :

```<code>const userId$ = this.route.params.map(params=> params['userId']);
userService.getUser(userId$)
   .subscribe(users => this.users = users);
</code>```

User Service

```<code>getUser(userId$){
   return userId$.flatMap(userId => this.http.get(url+'/'+userId);
}
</code>```

In the above scenario I have declared a relation between routes and userservice . So, when a user clicks on a different user , the url changes and automatically a new http request is sent and the data in UI is updated.
So basically I am saying, observe the route params and if 'userId' value changes do http call and update UI .

Body:
I was learning on Angular Router Params Observable in Pluralsight course(Routing).

this.route.params.subscribe(params => {let id = params['id']})});

I understand within component, when there is change in params, we use above code.

I would like to know an example, or scenario this plays role in real time application?

Body:
I use that in my application like this:

Inside component :

const userId$ = this.route.params.map(params=> params['userId']);
userService.getUser(userId$)
   .subscribe(users => this.users = users);

User Service

getUser(userId$){
   return userId$.flatMap(userId => this.http.get(url+'/'+userId);
}

In the above scenario I have declared a relation between routes and userservice . So, when a user clicks on a different user , the url changes and automatically a new http request is sent and the data in UI is updated.
So basically I am saying, observe the route params and if 'userId' value changes do http call and update UI .


问:
I have a managed assembly and need to debug it but can't
I have an .exe which is a portable program. It is assembled with Microsoft Visual C# / Basic .NET
I managed to find out that in order OllyDBG to be able to open it, it should be running and also JIT compiler producing some code. I am a beginner and not at all understand the full process. When it's running, it doesn't create any other files near it ( though when laucnhing the installable version it creates a temporary .dat file aside it). But the portable version is the same size so I am working with it.
 While it is running, anyway the debugger can't open it ( nor the installed version )... So my question is - what am I missing in order to make it readable. I just need to make a small change in the .exe but I cannot get into it. Please help me with few more details to make it happen.</p>

答:
If it really is a managed application built with a .NET compiler, then the assembly program is actually composed of IL code, which can more or less be reverted back into source code for you to modify. In order to do this, you can use a tool such as ILSpy or .NET Reflector.

There is a possibility that the assembly may have some kind of obfuscation to discourage decompilation, and in that case, you will need either look to the developer of the software for permission, or to a specialized deobfuscation program like de4dot.

Keep in mind, the terms of service of the application may forbid you from modifying the assembly, but this isn't a legal advice forum.


问:
Localizing Manifest files for an Office JS Add-In
When localizing manifest files, according to Localization for Office Add-ins, the English default values can be overridden by adding a XML tag and specifying the country code. For example:

```<code><Description DefaultValue="Hello world.">
    <Override Locale="de-de" Value="Hallo Welt."/>
</Description>`
</code>```

Now this addresses only Germany (de-de). But in Austria (de-at) and in some regions of Switzerland (de-ch), people also speak German.

So, should I know create for each country code a separate line in my manifest files? For example:

```<code><Description DefaultValue="Hello world.">
    <Override Locale="de-de" Value="Hallo Welt."/>
    <Override Locale="de-at" Value="Hallo Welt."/>
    <Override Locale="de-ch" Value="Hallo Welt."/>
</Description>`
</code>```

Is there a better way to achieve this?

Or will my Add-In automatically use German strings for Austria and Switzerland be recognizing the first two letters, so that I don't need to specify the regions for Austria and Switzerland?

Thanks in advance.

Best,
Mourad

答:
You are in the right direction, according to Localization for Office Add-ins the Locale attribute of the Override element have to follow to RFC 3066. This means you should be able to use "Primary-subtag" only, without specifying "Subtag" (in your case "de") and your code would looks like ...

```<code><Description DefaultValue="Hello world.">
    <Override Locale="de" Value="Hallo Welt."/>
</Description>`
</code>```

The fall back mechanism supposed to work according to RFC.
Unfortunately, this looks like doesn't work in the real life for all clients. There are difference for desktop and OWA clients on how they consume Locale. Confirmed by Microsoft Outlook team work around is in this thread: Language Override entries that can work in Outlook 2016 and OWA. Indeed, if you work with yet another Office product (Excel, Word, etc.) you may have differences between online and desktop versions as well.

Body:
When localizing manifest files, according to Localization for Office Add-ins, the English default values can be overridden by adding a XML tag and specifying the country code. For example:

<Description DefaultValue="Hello world.">
    <Override Locale="de-de" Value="Hallo Welt."/>
</Description>`

Now this addresses only Germany (de-de). But in Austria (de-at) and in some regions of Switzerland (de-ch), people also speak German.

So, should I know create for each country code a separate line in my manifest files? For example:

<Description DefaultValue="Hello world.">
    <Override Locale="de-de" Value="Hallo Welt."/>
    <Override Locale="de-at" Value="Hallo Welt."/>
    <Override Locale="de-ch" Value="Hallo Welt."/>
</Description>`

Is there a better way to achieve this?

Or will my Add-In automatically use German strings for Austria and Switzerland be recognizing the first two letters, so that I don't need to specify the regions for Austria and Switzerland?

Thanks in advance.

Best,
Mourad

Body:
You are in the right direction, according to Localization for Office Add-ins the Locale attribute of the Override element have to follow to RFC 3066. This means you should be able to use "Primary-subtag" only, without specifying "Subtag" (in your case "de") and your code would looks like ...

<Description DefaultValue="Hello world.">
    <Override Locale="de" Value="Hallo Welt."/>
</Description>`

The fall back mechanism supposed to work according to RFC.
Unfortunately, this looks like doesn't work in the real life for all clients. There are difference for desktop and OWA clients on how they consume Locale. Confirmed by Microsoft Outlook team work around is in this thread: Language Override entries that can work in Outlook 2016 and OWA. Indeed, if you work with yet another Office product (Excel, Word, etc.) you may have differences between online and desktop versions as well.


问:
How do I manually configure a JdbcTemplate in Spring Boot?
Here's my basic DAO implementation class:

```<code>@Repository
public class MeetingDaoImpl implements MeetingDao {

  @Autowired
  JdbcTemplate jdbcTemplate;

  public boolean insertNewMeeting(String initials, String meetingId, int numYears) {

    int numRowsAffected = jdbcTemplate.update(SQLConstants.INSERT_NEW_MEETING,
        new Object[] {initials.toLowerCase(), meetingId, numYears});

    return numRowsAffected > 0;

  }
}
</code>```

The jdbcTemplate automatically reads the spring.datasource properties from my application.properties file, which is great, but it includes my DB password which is something I don't want to commit. Instead, I'd like to read it from a local server.properties file instead which I can easily read from a Java class.

Is there a way to configure the jdbcTemplate with Java? I've seen multiple examples using a bean and XML, but none with Java.

答:
Just declare a JdbcTemplate bean:

```<code>@Bean
JdbcTemplate jdbcTemplate() throws IllegalAccessException, InvocationTargetException, InstantiationException {
    // extract this 4 parameters using your own logic
    final String driverClassName = "org.h2.Driver";
    final String jdbcUrl = "jdbc:h2:mem:test";
    final String username = "sa";
    final String password = "";
    // Build dataSource manually:
    final Class<?> driverClass = ClassUtils.resolveClassName(driverClassName, this.getClass().getClassLoader());
    final Driver driver = (Driver) ClassUtils.getConstructorIfAvailable(driverClass).newInstance();
    final DataSource dataSource = new SimpleDriverDataSource(driver, jdbcUrl, username, password);
    // or using DataSourceBuilder:
    final DataSource dataSource = DataSourceBuilder.create().driverClassName(driverClassName).url(jdbcUrl).username(username).password(password).build();
    // and make the jdbcTemplate
    return new JdbcTemplate(dataSource);
}
</code>```

Another way is not to setup datasource parameters in your application.properties file, but to declare it on runtime instead. When you're running your app you can override any properties defined within application.properties or define a new ones.

For example:

java -jar my-spring-boot-app.jar --spring.datasource.url=jdbc:h2:mem:test --spring.datasource.username=sa --spring.datasource.password=secret

The more sophisticated way is to use spring-cloud-config-server or Consul for managing your settings.

Body:
Here's my basic DAO implementation class:

@Repository
public class MeetingDaoImpl implements MeetingDao {

  @Autowired
  JdbcTemplate jdbcTemplate;

  public boolean insertNewMeeting(String initials, String meetingId, int numYears) {

    int numRowsAffected = jdbcTemplate.update(SQLConstants.INSERT_NEW_MEETING,
        new Object[] {initials.toLowerCase(), meetingId, numYears});

    return numRowsAffected > 0;

  }
}

The jdbcTemplate automatically reads the spring.datasource properties from my application.properties file, which is great, but it includes my DB password which is something I don't want to commit. Instead, I'd like to read it from a local server.properties file instead which I can easily read from a Java class.

Is there a way to configure the jdbcTemplate with Java? I've seen multiple examples using a bean and XML, but none with Java.

Body:
Just declare a JdbcTemplate bean:

@Bean
JdbcTemplate jdbcTemplate() throws IllegalAccessException, InvocationTargetException, InstantiationException {
    // extract this 4 parameters using your own logic
    final String driverClassName = "org.h2.Driver";
    final String jdbcUrl = "jdbc:h2:mem:test";
    final String username = "sa";
    final String password = "";
    // Build dataSource manually:
    final Class<?> driverClass = ClassUtils.resolveClassName(driverClassName, this.getClass().getClassLoader());
    final Driver driver = (Driver) ClassUtils.getConstructorIfAvailable(driverClass).newInstance();
    final DataSource dataSource = new SimpleDriverDataSource(driver, jdbcUrl, username, password);
    // or using DataSourceBuilder:
    final DataSource dataSource = DataSourceBuilder.create().driverClassName(driverClassName).url(jdbcUrl).username(username).password(password).build();
    // and make the jdbcTemplate
    return new JdbcTemplate(dataSource);
}

Another way is not to setup datasource parameters in your application.properties file, but to declare it on runtime instead. When you're running your app you can override any properties defined within application.properties or define a new ones.

For example:

java -jar my-spring-boot-app.jar --spring.datasource.url=jdbc:h2:mem:test --spring.datasource.username=sa --spring.datasource.password=secret

The more sophisticated way is to use spring-cloud-config-server or Consul for managing your settings.


问:
Maven fails dependencies
I cant understand, why is failing this dependency in  my pom.xml:

```<code><dependency>
            <groupId>statistics</groupId>
            <artifactId>statistics-1.0-SNAPSHOT</artifactId>
            <version>1.0</version>
   </dependency>
</code>```

But I have got the root well done:

C:\m2\repository\statistics\statistics-1.0-SNAPSHOT\1.0

Any help??

Im working of course in mode offline.

答:
Your dependency looks weird with the duplicate versionreference. Maven is looking for ${localrepository}/groupId/artifactId/version/artifactId-version.type, where the dots in the groupId (if any) are used as directory-separators.
So in you case Maven is looking for C:\m2\repository\statistics\statistics-1.0-SNAPSHOT\1.0\statistics-1.0-SNAPSHOT-1.0.jar.
However, what you probably want is

```<code><dependency>
        <groupId>statistics</groupId>
        <artifactId>statistics</artifactId>
        <version>1.0-SNAPSHOT</version>
</dependency>
</code>```

Title: Maven fails dependencies

Body:
I cant understand, why is failing this dependency in  my pom.xml:

<dependency>
            <groupId>statistics</groupId>
            <artifactId>statistics-1.0-SNAPSHOT</artifactId>
            <version>1.0</version>
   </dependency>

But I have got the root well done:

C:\m2\repository\statistics\statistics-1.0-SNAPSHOT\1.0

Any help??

Im working of course in mode offline.

Body:
Your dependency looks weird with the duplicate versionreference. Maven is looking for ${localrepository}/groupId/artifactId/version/artifactId-version.type, where the dots in the groupId (if any) are used as directory-separators.
So in you case Maven is looking for C:\m2\repository\statistics\statistics-1.0-SNAPSHOT\1.0\statistics-1.0-SNAPSHOT-1.0.jar.
However, what you probably want is

<dependency>
        <groupId>statistics</groupId>
        <artifactId>statistics</artifactId>
        <version>1.0-SNAPSHOT</version>
</dependency>


问:
Find current country from iPhone device
I have to get the current country in the iPhone settings. Can anyone tell me how to get the current country in iPhone application.

I have to use the current country for parsing the RSS feed in which I need to pass the current country.

Please help me out to find the country .

Thanks in advance.

答:
Swift 3.0 latest working code is</p>

```<code>if let countryCode = (Locale.current as NSLocale).object(forKey: .countryCode) as? String {
    print(countryCode)
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Find current country from iPhone device

Body:
Swift 3.0 latest working code is

if let countryCode = (Locale.current as NSLocale).object(forKey: .countryCode) as? String {
    print(countryCode)
}


问:
How to create a selector ID from a variable
In my HTML document, I want to have 9 checkboxes. When a checkbox is selected, I want a corresponding block of text to show. I'm trying to create a single function for this, that uses a parameter to select the corresponding box, but I've been unsuccesfull so far. I'm not experienced with HTML of jQuery at all, so I've got no idea what the problem is.

The code I currently have is as follows:

$(document).ready(function() {
    for ($i = 0; $i < 9; $i++) {
        $("input[name=checkbox" + $i + "]").click(function () {
            $('#box' + $i).toggle();
        });
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="checkbox1" value="alpha"> Checkbox 1 <br>
<input type="checkbox" name="checkbox2" value="beta"> Checkbox 2 <br>

<div id = "box1" style="display:none">Checkbox 1 is selected</div>
<div id = "box2" style="display:none">Checkbox 2 is selected</div></code>```

Can anyone please help me understand why the .toggle doesn't work correctly?

答:
Because of how variable scoping works in for loops, your toggle is actually targeting #box9, as that was the last value of $i. Luckily in this case, there's really no need for a loop at all.

We can apply the handler to all checkboxes by using a Starts With Selector (^=). From there, we can get the number of the clicked checkbox by grabbing it's name and removing the word "checkbox" from it.

Then we can simply append that number to "#box" to select the corresponding element to toggle.

$("input[name^=checkbox]").click(function () {
    //$(this) refers to the checkbox that was clicked
    var num = $(this).attr("name").replace("checkbox","");
    var $box = $("#box" + num);
    $box.toggle();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="checkbox1" value="alpha"> Checkbox 1 <br>
<input type="checkbox" name="checkbox2" value="beta"> Checkbox 2 <br>

<div id = "box1" style="display:none">Checkbox 1 is selected</div>
<div id = "box2" style="display:none">Checkbox 2 is selected</div></code>```

If you have other checkboxes with name="checkboxX" that you don't want this to apply to...

...you'll need to separate them into groups, most easily done just by applying a class to the ones you want.

```<code><input type="checkbox" name="checkbox1" class="clickable" />
<input type="checkbox" name="checkbox2" class="clickable" />
<input type="checkbox" name="checkbox3" />
</code>```

Then simply replace the selector in the code provided above to target only those with the class clickable:

```<code>$("input[type=checkbox].clickable").click(function () {
    //...
});
</code>```

In this example, checkbox3 would not trigger the event because it doesn't have the class applied.

Body:
In my HTML document, I want to have 9 checkboxes. When a checkbox is selected, I want a corresponding block of text to show. I'm trying to create a single function for this, that uses a parameter to select the corresponding box, but I've been unsuccesfull so far. I'm not experienced with HTML of jQuery at all, so I've got no idea what the problem is.

The code I currently have is as follows:

$(document).ready(function() {
    for ($i = 0; $i < 9; $i++) {
        $("input[name=checkbox" + $i + "]").click(function () {
            $('#box' + $i).toggle();
        });
    }
});

<input type="checkbox" name="checkbox1" value="alpha"> Checkbox 1

<input type="checkbox" name="checkbox2" value="beta"> Checkbox 2

Checkbox 1 is selected

Checkbox 2 is selected

Can anyone please help me understand why the .toggle doesn't work correctly?

Body:
Because of how variable scoping works in for loops, your toggle is actually targeting #box9, as that was the last value of $i. Luckily in this case, there's really no need for a loop at all.

We can apply the handler to all checkboxes by using a Starts With Selector (^=). From there, we can get the number of the clicked checkbox by grabbing it's name and removing the word "checkbox" from it.

Then we can simply append that number to "#box" to select the corresponding element to toggle.

$("input[name^=checkbox]").click(function () {
    //$(this) refers to the checkbox that was clicked
    var num = $(this).attr("name").replace("checkbox","");
    var $box = $("#box" + num);
    $box.toggle();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="checkbox1" value="alpha"> Checkbox 1 <br>
<input type="checkbox" name="checkbox2" value="beta"> Checkbox 2 <br>

<div id = "box1" style="display:none">Checkbox 1 is selected</div>
<div id = "box2" style="display:none">Checkbox 2 is selected</div>

If you have other checkboxes with name="checkboxX" that you don't want this to apply to...

...you'll need to separate them into groups, most easily done just by applying a class to the ones you want.

<input type="checkbox" name="checkbox1" class="clickable" />
<input type="checkbox" name="checkbox2" class="clickable" />
<input type="checkbox" name="checkbox3" />

Then simply replace the selector in the code provided above to target only those with the class clickable:

$("input[type=checkbox].clickable").click(function () {
    //...
});

In this example, checkbox3 would not trigger the event because it doesn't have the class applied.


问:
Android Simple Horizontal RecyclerView very slow and not smooth
I'm trying to implement Horizontal Recycler View but its not scrolling smooth at all.

tried all of the following solution i found in google but none of them worked:

```<code>popularCategoriesRecyclerView.setHasFixedSize(true);
popularCategoriesRecyclerView.setItemViewCacheSize(10);
popularCategoriesRecyclerView.setDrawingCacheEnabled(true);
popularCategoriesRecyclerView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_LOW);
setHasStableIds(true);
</code>```

I've also tried using Picasso/Glide and even not loading the image at all, but it still doesn't scroll smoothly.

Here is my code:

```<code>public class MainActivity extends AppCompatActivity {

    private RecyclerView popularCategoriesRecyclerView;
    private RecyclerView.Adapter popularCategoriesAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RootCategory demoCategory = CreateDemoModelService.create();

        popularCategoriesRecyclerView = (RecyclerView)findViewById(R.id.popular_categories_recycler_view);
        popularCategoriesRecyclerView.setHasFixedSize(true);
        popularCategoriesRecyclerView.setItemViewCacheSize(10);
        popularCategoriesRecyclerView.setDrawingCacheEnabled(true);
        popularCategoriesRecyclerView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_LOW);

        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,true);
            popularCategoriesRecyclerView.setLayoutManager(layoutManager);

        popularCategoriesAdapter = new FavoriteCategoryAdapter(demoCategory.getFavoriteCategories());
        popularCategoriesRecyclerView.setAdapter(popularCategoriesAdapter);
    }
}
</code>```

and the adapter:

```<code>public class FavoriteCategoryAdapter extends RecyclerView.Adapter {
    private List<Category> categories;

    public static class ViewHolder extends RecyclerView.ViewHolder {
        TextView tv;
        ImageView iv;

        ViewHolder(View v) {
            super(v);
            tv = (TextView)v.findViewById(R.id.adapter_favorite_category_tv);
            iv = (ImageView)v.findViewById(R.id.adapter_favorite_category_iv);
        }
    }

    public FavoriteCategoryAdapter(List<Category> categories) {
        this.categories = categories;
        setHasStableIds(true);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_popular_category,parent,false);
        return new FavoriteCategoryAdapter.ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        Category category = categories.get(position);
        FavoriteCategoryAdapter.ViewHolder viewHolder = (FavoriteCategoryAdapter.ViewHolder) holder;

        if (viewHolder.tv.getText() != null && viewHolder.tv.getText().equals(category.getName()))
            return;

        Context context = viewHolder.iv.getContext();
        Resources resources = context.getResources();
        final int resourceId = resources.getIdentifier(category.getIconName() + "_popular", "drawable",
            context.getPackageName());

        Picasso.with(context).load(resourceId).fit().centerCrop().into(viewHolder.iv);

        viewHolder.tv.setText(category.getName());
    }

    @Override
    public int getItemCount() {
        return categories.size();
    }
}
</code>```

adapter_category.xml:

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"     android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/adapter_popular_category_bg">

    <ImageView
        android:id="@+id/adapter_favorite_category_iv"
        android:layout_width="90dp"
        android:layout_height="90dp"
        android:scaleType="fitCenter"/>

    <TextView
        android:id="@+id/adapter_favorite_category_tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="3dp"
        android:paddingBottom="3dp"
        android:textColor="@android:color/white"
        android:gravity="center"
        android:background="@drawable/adapter_popular_category_tv_bg"/>
</LinearLayout>
</code>```

activity_main.xml:

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:layout_marginRight="10dp"
            android:layout_gravity="right"
            android:text="@string/activity_main_popular"
            android:textColor="#75A735"
            android:textAppearance="@style/TextAppearance.AppCompat.Medium"/>

        <android.support.v7.widget.RecyclerView
            android:id="@+id/popular_categories_recycler_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:layout_marginBottom="10dp"
            android:padding="0dp"
            android:scrollbars="horizontal"/>

    </LinearLayout>

</LinearLayout>
</code>```

Can someone help me? Am i doing something wrong?

答:
Ok, i found out what was the problem.

My Activity had a background image that apparently was too big (found it because it wasn't showing on some devices), so after i reduced the resolution of the background image, everything works smoothly as expected.

Body:
I'm trying to implement Horizontal Recycler View but its not scrolling smooth at all.

tried all of the following solution i found in google but none of them worked:

popularCategoriesRecyclerView.setHasFixedSize(true);
popularCategoriesRecyclerView.setItemViewCacheSize(10);
popularCategoriesRecyclerView.setDrawingCacheEnabled(true);
popularCategoriesRecyclerView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_LOW);
setHasStableIds(true);

I've also tried using Picasso/Glide and even not loading the image at all, but it still doesn't scroll smoothly.

Here is my code:

public class MainActivity extends AppCompatActivity {

    private RecyclerView popularCategoriesRecyclerView;
    private RecyclerView.Adapter popularCategoriesAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RootCategory demoCategory = CreateDemoModelService.create();

        popularCategoriesRecyclerView = (RecyclerView)findViewById(R.id.popular_categories_recycler_view);
        popularCategoriesRecyclerView.setHasFixedSize(true);
        popularCategoriesRecyclerView.setItemViewCacheSize(10);
        popularCategoriesRecyclerView.setDrawingCacheEnabled(true);
        popularCategoriesRecyclerView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_LOW);

        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,true);
            popularCategoriesRecyclerView.setLayoutManager(layoutManager);

        popularCategoriesAdapter = new FavoriteCategoryAdapter(demoCategory.getFavoriteCategories());
        popularCategoriesRecyclerView.setAdapter(popularCategoriesAdapter);
    }
}

and the adapter:

public class FavoriteCategoryAdapter extends RecyclerView.Adapter {
    private List<Category> categories;

    public static class ViewHolder extends RecyclerView.ViewHolder {
        TextView tv;
        ImageView iv;

        ViewHolder(View v) {
            super(v);
            tv = (TextView)v.findViewById(R.id.adapter_favorite_category_tv);
            iv = (ImageView)v.findViewById(R.id.adapter_favorite_category_iv);
        }
    }

    public FavoriteCategoryAdapter(List<Category> categories) {
        this.categories = categories;
        setHasStableIds(true);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_popular_category,parent,false);
        return new FavoriteCategoryAdapter.ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        Category category = categories.get(position);
        FavoriteCategoryAdapter.ViewHolder viewHolder = (FavoriteCategoryAdapter.ViewHolder) holder;

        if (viewHolder.tv.getText() != null && viewHolder.tv.getText().equals(category.getName()))
            return;

        Context context = viewHolder.iv.getContext();
        Resources resources = context.getResources();
        final int resourceId = resources.getIdentifier(category.getIconName() + "_popular", "drawable",
            context.getPackageName());

        Picasso.with(context).load(resourceId).fit().centerCrop().into(viewHolder.iv);

        viewHolder.tv.setText(category.getName());
    }

    @Override
    public int getItemCount() {
        return categories.size();
    }
}

adapter_category.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"     android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/adapter_popular_category_bg">

    <ImageView
        android:id="@+id/adapter_favorite_category_iv"
        android:layout_width="90dp"
        android:layout_height="90dp"
        android:scaleType="fitCenter"/>

    <TextView
        android:id="@+id/adapter_favorite_category_tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="3dp"
        android:paddingBottom="3dp"
        android:textColor="@android:color/white"
        android:gravity="center"
        android:background="@drawable/adapter_popular_category_tv_bg"/>
</LinearLayout>

activity_main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:layout_marginRight="10dp"
            android:layout_gravity="right"
            android:text="@string/activity_main_popular"
            android:textColor="#75A735"
            android:textAppearance="@style/TextAppearance.AppCompat.Medium"/>

        <android.support.v7.widget.RecyclerView
            android:id="@+id/popular_categories_recycler_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:layout_marginBottom="10dp"
            android:padding="0dp"
            android:scrollbars="horizontal"/>

    </LinearLayout>

</LinearLayout>

Can someone help me? Am i doing something wrong?


问:
Connect to Service Fabric Application
I have deployed a 5 node cluster on Azure SF with 3 applications. I have deployed my html web app with Jquery on Azure App Service , now i want to call one of application API hosted on cluster from my web app.
In $.ajax request what value should i pass to url property access my API?

SF EndPoint :https://xyz.southcentralus.cloudapp.azure.com:19000

API :  fabric:/ApplicationAPI

My SF and App service are in same VNet with load balancer on my SF cluster

答:
Your cluster will be reachable by the public DNS entry that was created when you created the cluster.

https://xyz.southcentralus.cloudapp.azure.com

Now...in order for you to reach your services you need to open up the ports on the load balancer. If you specified a listening port on fabric:/ApplicationAPI/SomeService on port 8217 as an example, you would create a load balancer rule from port X to port 8217 on the backend pool. Port X would be whatever port you want to use when using the above domain name.

Note:
You could set up some sort of gateway in front of the load balancer so that you can create path based rules to forward the traffic so you're not accessing everything on weird port numbers.

Title: Connect to Service Fabric Application


问:
This application is currently offline. To enable the application, remove the app_offline.htm file from the application root directory
can any body suggest me how to remove the app_offline.htm file from application root directory in asp.net web application.when i run the page it doesnt show the design of html source </p>

答: Just go to the root of your web directory, it should be there.  it is something that VS puts there during certain tasks.</p>


问:
Copy RequestParams to RequestHeaders before handling in RestController
To replace a legacy system and not breaking the interface, I'm looking for a way to implement the following scenario:

If a REST client hasn't set a specific HTTP header (applicationId) but sends it as a query-paramter (aka RequestParameter), this value should be taken as a method parameter in a Spring Boot RestController.

The current method looks like this:

```<code>@RequestMapping(value = "/something", method = RequestMethod.GET)
    public void doSomething(@RequestHeader("applicationId") String applicationId) { }
</code>```

I think there could be two possible ways:

Annotate the method somehow to map a query-parameter OR a header to a method parameter

Write an Interceptor which reads all query-parameters of a request and set non-existing headers with their values. This way, the method wouldn't have to be touched at all.

In both ways I'm not sure how to implement them (don't know if 1. is even possible). I tried with an own HandlerInterceptor which reads query-params in preHandle (successfully) but isn't able to set headers in the request before it is forwarded to the RestController.

答:
Write a Filter that wraps the incoming request using a HttpServletRequestWrapper. This wrapper should override the getHeader method.

```<code>public ParameterToHeaderWrappingRequestFilter extends OncePerRequestFilter {

    protected void doFilterInternal(
        HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws ServletException, IOException {
        filterChain.doFilter(new ParameterToHeaderWrappingRequest(request), response, filterChain);
    }
}
</code>```

Register this filter as a @Bean in your Spring Boot application and it will be applied automatically.

```<code>public class ParameterToHeaderWrappingRequest extends HttpServletRequestWrapper {

    public String getHeader(String name) {
        String header = super.getHeader(name);
        if (header == null) {
            header = getParameter(name);
        }
        return header;
    }
}
</code>```

Something like that should do the trick. Depending on your needs you might want/need to override some additional header based methods and you probably want to limit the number of headers to override with parameters.

The rest of your code can now be written as is.

Body:
To replace a legacy system and not breaking the interface, I'm looking for a way to implement the following scenario:

If a REST client hasn't set a specific HTTP header (applicationId) but sends it as a query-paramter (aka RequestParameter), this value should be taken as a method parameter in a Spring Boot RestController.

The current method looks like this:

@RequestMapping(value = "/something", method = RequestMethod.GET)
    public void doSomething(@RequestHeader("applicationId") String applicationId) { }

I think there could be two possible ways:

Annotate the method somehow to map a query-parameter OR a header to a method parameter

Write an Interceptor which reads all query-parameters of a request and set non-existing headers with their values. This way, the method wouldn't have to be touched at all.

In both ways I'm not sure how to implement them (don't know if 1. is even possible). I tried with an own HandlerInterceptor which reads query-params in preHandle (successfully) but isn't able to set headers in the request before it is forwarded to the RestController.

Body:
Write a Filter that wraps the incoming request using a HttpServletRequestWrapper. This wrapper should override the getHeader method.

public ParameterToHeaderWrappingRequestFilter extends OncePerRequestFilter {

    protected void doFilterInternal(
        HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws ServletException, IOException {
        filterChain.doFilter(new ParameterToHeaderWrappingRequest(request), response, filterChain);
    }
}

Register this filter as a @Bean in your Spring Boot application and it will be applied automatically.

public class ParameterToHeaderWrappingRequest extends HttpServletRequestWrapper {

    public String getHeader(String name) {
        String header = super.getHeader(name);
        if (header == null) {
            header = getParameter(name);
        }
        return header;
    }
}

Something like that should do the trick. Depending on your needs you might want/need to override some additional header based methods and you probably want to limit the number of headers to override with parameters.

The rest of your code can now be written as is.


问:
Grid control in SSMS
I notice in SSMS (SQL Server Management Studio 2016), the query results return within a blink of a second (above 10k+ rows). The result table/grid scroll perfectly smooth, and have an extremely low memory footprint (~80MB) on SSMS. This grid/view-like control way out perform either ListView (~200MB, 2-3 seconds) and DataGrid (~600MB, 8-10 seconds). Even if I turn off all visualization or tweak cancententscroll or fix its height to optimize the speed, they still perform far behind the grid in SSMS, still with sluggish scrolling and GUI operation.

What is behind the grid control used in SSMS that make it so smooth?

答:
SSMS grid is not C++, it's not a ListView nor a DataGrid, it does not uses Windows native controls, it's "just" a custom .NET control named GridControl (in a Microsoft.SqlServer.Management.UI.Grid namespace) that belongs to an assembly named Microsoft.SqlServer.GridControl.dll.

You can find it in various places: in the GAC, in %ProgramFiles(x86)%\Common Files\Microsoft Shared\SQL Server Developer Tools, in %ProgramFiles(x86)%\Microsoft SQL Server Management Studio 18\Common7\IDE, in Visual Studio files, etc.

It's not a redistributable binary AFAIK, so you're not supposed to ship it, it's not documented, and it's not a full-featured grid like others. However, as you found out, it's lightweight and it can be fast, as fast as your underlying data access.

If you want to play with it, here's a small Winforms C# sample (a 10000 x 256 grid, which is 2,5 million cells that opens instantly) that demonstrates how to use it:

```<code>using System;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.SqlServer.Management.UI.Grid;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        private GridControl _control = new GridControl();

        public Form1()
        {
            InitializeComponent();

            for (int i = 0; i < 256; i++)
            {
                _control.AddColumn(new GridColumnInfo { HeaderType = GridColumnHeaderType.Text, IsUserResizable = true });
                _control.SetHeaderInfo(i, "Column " + i, null);
            }

            _control.Dock = DockStyle.Fill;
            _control.GridStorage = new GridStorage();
            Controls.Add(_control);
        }
    }

    // represents a datasource
    public class GridStorage : IGridStorage
    {
        public long EnsureRowsInBuf(long FirstRowIndex, long LastRowIndex)
        {
            return NumRows(); // pagination, dynamic load, virtualization, could happen here
        }

        public void FillControlWithData(long nRowIndex, int nColIndex, IGridEmbeddedControl control)
        {
            // for cell edition
            control.SetCurSelectionAsString(GetCellDataAsString(nRowIndex, nColIndex));
        }

        public string GetCellDataAsString(long nRowIndex, int nColIndex)
        {
            // get cell data
            return nRowIndex + " x " + nColIndex;
        }

        public int IsCellEditable(long nRowIndex, int nColIndex)
        {
            return 1; // 1 means yes, 0 means false
        }

        public long NumRows()
        {
            return 10000;
        }

        public bool SetCellDataFromControl(long nRowIndex, int nColIndex, IGridEmbeddedControl control)
        {
            // when a cell has changed, you're supposed to change your data here
            return true;
        }

        public Bitmap GetCellDataAsBitmap(long nRowIndex, int nColIndex) => throw new NotImplementedException();
        public void GetCellDataForButton(long nRowIndex, int nColIndex, out ButtonCellState state, out Bitmap image, out string buttonLabel) => throw new NotImplementedException();
        public GridCheckBoxState GetCellDataForCheckBox(long nRowIndex, int nColIndex) => throw new NotImplementedException();
    }
}
</code>```

Here is what it looks like. You can scroll without any slowdown, on a decent computer.

Title: Grid control in SSMS

Body:
SSMS grid is not C++, it's not a ListView nor a DataGrid, it does not uses Windows native controls, it's "just" a custom .NET control named GridControl (in a Microsoft.SqlServer.Management.UI.Grid namespace) that belongs to an assembly named Microsoft.SqlServer.GridControl.dll.

You can find it in various places: in the GAC, in %ProgramFiles(x86)%\Common Files\Microsoft Shared\SQL Server Developer Tools, in %ProgramFiles(x86)%\Microsoft SQL Server Management Studio 18\Common7\IDE, in Visual Studio files, etc.

It's not a redistributable binary AFAIK, so you're not supposed to ship it, it's not documented, and it's not a full-featured grid like others. However, as you found out, it's lightweight and it can be fast, as fast as your underlying data access.

If you want to play with it, here's a small Winforms C# sample (a 10000 x 256 grid, which is 2,5 million cells that opens instantly) that demonstrates how to use it:

using System;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.SqlServer.Management.UI.Grid;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        private GridControl _control = new GridControl();

        public Form1()
        {
            InitializeComponent();

            for (int i = 0; i < 256; i++)
            {
                _control.AddColumn(new GridColumnInfo { HeaderType = GridColumnHeaderType.Text, IsUserResizable = true });
                _control.SetHeaderInfo(i, "Column " + i, null);
            }

            _control.Dock = DockStyle.Fill;
            _control.GridStorage = new GridStorage();
            Controls.Add(_control);
        }
    }

    // represents a datasource
    public class GridStorage : IGridStorage
    {
        public long EnsureRowsInBuf(long FirstRowIndex, long LastRowIndex)
        {
            return NumRows(); // pagination, dynamic load, virtualization, could happen here
        }

        public void FillControlWithData(long nRowIndex, int nColIndex, IGridEmbeddedControl control)
        {
            // for cell edition
            control.SetCurSelectionAsString(GetCellDataAsString(nRowIndex, nColIndex));
        }

        public string GetCellDataAsString(long nRowIndex, int nColIndex)
        {
            // get cell data
            return nRowIndex + " x " + nColIndex;
        }

        public int IsCellEditable(long nRowIndex, int nColIndex)
        {
            return 1; // 1 means yes, 0 means false
        }

        public long NumRows()
        {
            return 10000;
        }

        public bool SetCellDataFromControl(long nRowIndex, int nColIndex, IGridEmbeddedControl control)
        {
            // when a cell has changed, you're supposed to change your data here
            return true;
        }

        public Bitmap GetCellDataAsBitmap(long nRowIndex, int nColIndex) => throw new NotImplementedException();
        public void GetCellDataForButton(long nRowIndex, int nColIndex, out ButtonCellState state, out Bitmap image, out string buttonLabel) => throw new NotImplementedException();
        public GridCheckBoxState GetCellDataForCheckBox(long nRowIndex, int nColIndex) => throw new NotImplementedException();
    }
}

Here is what it looks like. You can scroll without any slowdown, on a decent computer.

ContentLicense: CC BY-SA 4.0


问:
Symfony EasyAdmin - How to create custom field in form, displaying text informations
I am not sure, how to implement quite simple text field, into the configured form template. I have configured individual fields at yml file.

But what if I want, in the middle of the form, some text formatted informations (fetching data from another entities).

I have learned how to make custom edit template for the entities, by overriding "app/Resources/views/easy_admin/Entity/edit.html.twig".

But it allows me to change the template only around the form fields. The actual form is rendered by "{{ form(form) }}".

So, I need to edit this form() creation or customize the template somehow.

Is the only solution for this custom text field, to create custom form field type in Symfony? Or are there other methods to achieve this?

答:
hope this helps

in the .twig file:

```<code>{% for name in value %}
    <li>
        <span>{{ include('@EasyAdmin/default/edit.html.twig', { value: name.name }) }}</span>
    </li>
{% endfor %}
</code>```

it means that the variable $name (collection) entered from the entity should be displayed inside this "for loop"
you can use the same technique to parse your desired html content

[edit.html.twig is located in app/Resources/views/easy_admin]

Body:
hope this helps

in the .twig file:

{% for name in value %}
    <li>
        <span>{{ include('@EasyAdmin/default/edit.html.twig', { value: name.name }) }}</span>
    </li>
{% endfor %}

it means that the variable $name (collection) entered from the entity should be displayed inside this "for loop"
you can use the same technique to parse your desired html content

[edit.html.twig is located in app/Resources/views/easy_admin]


问:
set up website on local machine
I have a fast dedicated internet connection and a static IP address at my office. I also have a web site that I want to host on my server machine (win server 2003). I know how to setup a web site through IIS but have no clue how to point my domain to my site and configure my server to serve for that domain. Can anyone point me to a preferably step-by-step guide on how to achieve this?</p>

答:
As far as DNS goes, the easiest thing to do would be to use a service like EveryDNS to configure your domain to point to your IP. At your domain registrar, set the nameservers to EveryDNS's nameservers:

```<code>ns1.everydns.net
ns2.everydns.net
ns3.everydns.net
ns4.everydns.net
</code>```

Then you want to create an "A" record for your domain, with the value being the IP address you're hosting the site at. I don't use IIS, so there may be some additional configuration necessary on the server, but with the HTTP servers that I've used (Apache, lighttpd) that's all that's necessary to get the site up and running.

Good luck!

p.s. You mention that you want to serve the site off your internet connection. Unless it's a small hobby site, I'd recommend going with a hosting provider for several reasons:

Often bandwidth isn't symmetrical - i.e. the downlink speed exceeds the uplink speed. When browsing the internet the downlink is the limiting factor, but when serving up content the uplink is the bottleneck.

Those that you share the connection with at the office may saturate the connection, or become frustrated if the site you're serving does.

It's likely that you don't have a SLA, which means that if the internet goes down, your provider has no contractual obligation to restore connectivity in a timely manner.

If these caveats don't apply or worry you, then go right ahead. However, any of the above apply, then I suggest looking into getting a hosting provider.

OwnerDisplayName: Emin

Title: set up website on local machine

Body:
As far as DNS goes, the easiest thing to do would be to use a service like EveryDNS to configure your domain to point to your IP. At your domain registrar, set the nameservers to EveryDNS's nameservers:

ns1.everydns.net
ns2.everydns.net
ns3.everydns.net
ns4.everydns.net

Then you want to create an "A" record for your domain, with the value being the IP address you're hosting the site at. I don't use IIS, so there may be some additional configuration necessary on the server, but with the HTTP servers that I've used (Apache, lighttpd) that's all that's necessary to get the site up and running.

Good luck!

p.s. You mention that you want to serve the site off your internet connection. Unless it's a small hobby site, I'd recommend going with a hosting provider for several reasons:

Often bandwidth isn't symmetrical - i.e. the downlink speed exceeds the uplink speed. When browsing the internet the downlink is the limiting factor, but when serving up content the uplink is the bottleneck.

Those that you share the connection with at the office may saturate the connection, or become frustrated if the site you're serving does.

It's likely that you don't have a SLA, which means that if the internet goes down, your provider has no contractual obligation to restore connectivity in a timely manner.

If these caveats don't apply or worry you, then go right ahead. However, any of the above apply, then I suggest looking into getting a hosting provider.

OwnerDisplayName: nobody

LastEditorDisplayName: nobody


问:
Loading local xml file in Windows Phone 7 (WP7)
I am trying to load up an XML file that lives in my Windows Phone 7 solution. I'd like to know the proper way to include the file in the project and then reference it with code. My current code is giving me an error of

NotSupportedException
"An exception occurred during a WebClient request."

here is the stub of my WebClient code

```<code>WebClient workbenchAdConfigRequest = new WebClient();
workbenchAdConfigRequest.OpenReadCompleted += new OpenReadCompletedEventHandler(workbenchAdConfigRequest_OpenReadCompleted);
workbenchAdConfigRequest.OpenReadAsync(new Uri("/SampleData/SampleData.xml", UriKind.Relative));
</code>```

and the event handler is

```<code>private void workbenchAdConfigRequest_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
    {
        try
        {
            XElement xml = XElement.Load(e.Result);
        }
        catch
        {
            //return
        }
    }
</code>```

on the file /SampleData/SampleData.xml I have set the properties to be

Build Action: Embedded Reference
Copy to Output Directory: Do Not Copy
Custom Tool: MSBuild:Compile

Can you load a local file from the "file path" of the application?

答:
You can also set the "Build Action" to "Content" in the properties of your XML file, and then in the code behind:

```<code>using System.Xml.Linq;
</code>```

......

```<code>XElement appDataXml;

StreamResourceInfo xml = Application.GetResourceStream(new Uri("yourxmlfilename.xml", UriKind.Relative));
appDataXml = XElement.Load(xml.Stream);
</code>```

Body:
I am trying to load up an XML file that lives in my Windows Phone 7 solution. I'd like to know the proper way to include the file in the project and then reference it with code. My current code is giving me an error of

NotSupportedException
"An exception occurred during a WebClient request."

here is the stub of my WebClient code

WebClient workbenchAdConfigRequest = new WebClient();
workbenchAdConfigRequest.OpenReadCompleted += new OpenReadCompletedEventHandler(workbenchAdConfigRequest_OpenReadCompleted);
workbenchAdConfigRequest.OpenReadAsync(new Uri("/SampleData/SampleData.xml", UriKind.Relative));

and the event handler is

private void workbenchAdConfigRequest_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
    {
        try
        {
            XElement xml = XElement.Load(e.Result);
        }
        catch
        {
            //return
        }
    }

on the file /SampleData/SampleData.xml I have set the properties to be

Build Action: Embedded Reference
Copy to Output Directory: Do Not Copy
Custom Tool: MSBuild:Compile

Can you load a local file from the "file path" of the application?

Body:
You can also set the "Build Action" to "Content" in the properties of your XML file, and then in the code behind:

using System.Xml.Linq;

......

XElement appDataXml;

StreamResourceInfo xml = Application.GetResourceStream(new Uri("yourxmlfilename.xml", UriKind.Relative));
appDataXml = XElement.Load(xml.Stream);


问:
Sencha Architect creates ViewModel and ViewController Automaticly
I am working on Sencha Architect and following this video which made by Sencha dev-team to walks around basics of application.

I got errors when i run the project and later figure out that somehow Sencha Architect created 'ViewModel' and 'ViewController' automatically.

Why could be? or is there any setting in application to block?

Here is a sample folder structure of 'View'. Files with '(*)' symbol not created by me..

```<code>view/
.. TicketDataView.js
.. TicketDataViewViewController.js (*)
.. TicketDataViewViewModel.js (*)
.. TicketPanel.js
.. TicketPanelViewController.js (*)
.. TicketPanelViewModel.js (*)
</code>```

答:
and i overcome on this situation with deleting 'ViewModel' and 'ViewController' files yet in Sencha Architect:

On 'Project Inspector' zone, clicked on 'TicketDataView' and it shows related items such as 'TicketDataViewViewModel' and 'TicketDataViewViewController'.

Just right-click to see 'Delete' button and deleted those unnecessary files. So the app.js and metadata/Application.js files updated as well...

As well as changed the Project Settings:

General> Overwrite index file on save: unchecked (leave blank)

Framework> Build Tools: Disabled

Then saved the project and opened index.html and changed script tags for ext-all.js, theme.js and link tag for theme.css to cdnjs' library.  Sencha CDN links not working! so imported cdnjs instead of it.

Body:
I am working on Sencha Architect and following this video which made by Sencha dev-team to walks around basics of application.

I got errors when i run the project and later figure out that somehow Sencha Architect created 'ViewModel' and 'ViewController' automatically.

Why could be? or is there any setting in application to block?

Here is a sample folder structure of 'View'. Files with '(*)' symbol not created by me..

view/
.. TicketDataView.js
.. TicketDataViewViewController.js (*)
.. TicketDataViewViewModel.js (*)
.. TicketPanel.js
.. TicketPanelViewController.js (*)
.. TicketPanelViewModel.js (*)


问:
Django Reportlab generates empty pdf
I'm using reportlab to create a pdf. I am using Reportlab Paragraphs. The problem is everytime i download it, it generates an empty txt.
I tested it without django and it works without a problem. If i'm using canvas it works but it doesn't suit what i need.

views.py

```<code>from django.http import HttpResponse
from django.shortcuts import render
from reportlab.lib.enums import TA_JUSTIFY
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.pagesizes import letter

def genereaza_pdf(request):
    if request.method == 'POST':
        response = HttpResponse(content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename="example.pdf"'
        doc = SimpleDocTemplate("example.pdf", pagesize=letter, rightMargin=70, leftMargin=70, topMargin=70,
                                bottomMargin=60)
        report = []

        styles = getSampleStyleSheet()
        styles.add(ParagraphStyle(name="Times", fontName='Times-Roman', fontSize=15, alignment=TA_JUSTIFY))

        p_text = "<u>ANEXA 1</u>"
        report.append(Paragraph(p_text, styles["Times"]))
        report.append(Spacer(1, 5))
        doc.build(report)
        return response
    return render(request, 'pdf_test.html')
</code>```

pdf_test.html

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Download pdf</title>
</head>
<body>
    <form method="POST">
        {% csrf_token %}
        <button type="submit">Download</button>
    </form>
</body>
</html>
</code>```

What seems to be the problem?

答:
You have to write the file to stream. Try this:</p>

```<code>from io import BytesIO
def genereaza_pdf(request):
    if request.method == 'POST':
        response = HttpResponse(content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename="example.pdf"'
        buff = BytesIO()
        doc = SimpleDocTemplate(buff, pagesize=letter, rightMargin=70, leftMargin=70, topMargin=70,
                                bottomMargin=60)
        report = []

        styles = getSampleStyleSheet()
        styles.add(ParagraphStyle(name="Times", fontName='Times-Roman', fontSize=15, alignment=TA_JUSTIFY))

        p_text = "<u>ANEXA 1</u>"
        report.append(Paragraph(p_text, styles["Times"]))
        report.append(Spacer(1, 5))
        doc.build(report)
        response.write(buff.getvalue())
        buff.close()
        return response
    return render(request, 'pdf_test.html')
</code>```

Title: Django Reportlab generates empty pdf

Body:
I'm using reportlab to create a pdf. I am using Reportlab Paragraphs. The problem is everytime i download it, it generates an empty txt.
I tested it without django and it works without a problem. If i'm using canvas it works but it doesn't suit what i need.

views.py

from django.http import HttpResponse
from django.shortcuts import render
from reportlab.lib.enums import TA_JUSTIFY
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.pagesizes import letter

def genereaza_pdf(request):
    if request.method == 'POST':
        response = HttpResponse(content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename="example.pdf"'
        doc = SimpleDocTemplate("example.pdf", pagesize=letter, rightMargin=70, leftMargin=70, topMargin=70,
                                bottomMargin=60)
        report = []

        styles = getSampleStyleSheet()
        styles.add(ParagraphStyle(name="Times", fontName='Times-Roman', fontSize=15, alignment=TA_JUSTIFY))

        p_text = "ANEXA 1"
        report.append(Paragraph(p_text, styles["Times"]))
        report.append(Spacer(1, 5))
        doc.build(report)
        return response
    return render(request, 'pdf_test.html')

pdf_test.html

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Download pdf</title>

    <form method="POST">
        {% csrf_token %}
        <button type="submit">Download</button>
    </form>

What seems to be the problem?

Body:
You have to write the file to stream. Try this:

from io import BytesIO
def genereaza_pdf(request):
    if request.method == 'POST':
        response = HttpResponse(content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename="example.pdf"'
        buff = BytesIO()
        doc = SimpleDocTemplate(buff, pagesize=letter, rightMargin=70, leftMargin=70, topMargin=70,
                                bottomMargin=60)
        report = []

        styles = getSampleStyleSheet()
        styles.add(ParagraphStyle(name="Times", fontName='Times-Roman', fontSize=15, alignment=TA_JUSTIFY))

        p_text = "<u>ANEXA 1</u>"
        report.append(Paragraph(p_text, styles["Times"]))
        report.append(Spacer(1, 5))
        doc.build(report)
        response.write(buff.getvalue())
        buff.close()
        return response
    return render(request, 'pdf_test.html')


问:
C# LINQ OrderBy several clauses
I'm currently working on an application in ASP.NET MVC 4.5. I need to write a LINQ query to order a list of Projects by different StatusIds.

Given is a list of Projects with this ViewModel:

```<code>public class ProjectVm
{
   public int ProjectId { get; set; }
   public string Title { get; set; }
   public Status StatusId { get; set; }
}
</code>```

My project status enum:

```<code>public enum Status : byte
{
    Draft = 1,
    Pending = 2,
    Validated = 3,
    Refused = 4
}
</code>```

The idea is to bring the List<ProjectVm> in a certain order, thus first ordered by 1 Draft, second by 2 Pending, third by 4 Refused and fourth by 3 Validated.

My current query looks like this:

```<code>projects = projects.OrderBy(x => x.StatusId).ToList();
</code>```

Unfortunately this query doesn't respect the desired order (4 comes before 3).

Do you know how to apply a condition on this query to bring the projects into the right order (1, 2, 4, 3) ?

Thanks!

答:
There's not a clean way to do it completely inline - you could do something like:

```<code>projects.OrderBy(x => x == Status.Validated ? int.MaxValue : (int)x.StatusId)
</code>```

to force Validated to be at the end, but I would write a function:

```<code>private int CustomOrder(Status status)
{
    switch(status)
    {
       // force Validated to the end
        case Status.Validated:
            return int.MaxValue;
        default:
            return (int)status;
    }
}
</code>```

and call it from the query:

```<code>projects.OrderBy(x => CustomOrder(x))
</code>```

Since you can add comments and organize the code to make it clearer what your intent is.

Another option would be to put the values in array in the order you want, then order by their position in the array:

```<code>Status[] order = new [] {Draft, Pending, Refused, Validated};

projects.OrderBy(x => Array.IndexOf(order,x));
</code>```

Title: C# LINQ OrderBy several clauses

Body:
I'm currently working on an application in ASP.NET MVC 4.5. I need to write a LINQ query to order a list of Projects by different StatusIds.

Given is a list of Projects with this ViewModel:

public class ProjectVm
{
   public int ProjectId { get; set; }
   public string Title { get; set; }
   public Status StatusId { get; set; }
}

My project status enum:

public enum Status : byte
{
    Draft = 1,
    Pending = 2,
    Validated = 3,
    Refused = 4
}

The idea is to bring the List<ProjectVm> in a certain order, thus first ordered by 1 Draft, second by 2 Pending, third by 4 Refused and fourth by 3 Validated.

My current query looks like this:

projects = projects.OrderBy(x => x.StatusId).ToList();

Unfortunately this query doesn't respect the desired order (4 comes before 3).

Do you know how to apply a condition on this query to bring the projects into the right order (1, 2, 4, 3) ?

Thanks!

Body:
There's not a clean way to do it completely inline - you could do something like:

projects.OrderBy(x => x == Status.Validated ? int.MaxValue : (int)x.StatusId)

to force Validated to be at the end, but I would write a function:

private int CustomOrder(Status status)
{
    switch(status)
    {
       // force Validated to the end
        case Status.Validated:
            return int.MaxValue;
        default:
            return (int)status;
    }
}

and call it from the query:

projects.OrderBy(x => CustomOrder(x))

Since you can add comments and organize the code to make it clearer what your intent is.

Another option would be to put the values in array in the order you want, then order by their position in the array:

Status[] order = new [] {Draft, Pending, Refused, Validated};

projects.OrderBy(x => Array.IndexOf(order,x));


问:
Prevent expansion of wildcards in non-quoted python script argument when running in UNIX environment
I have a python script that I'd like to supply with an argument (usually) containing wildcards, referring to a series of files that I'd like to do stuff with. Example here:

```<code>#!/usr/bin/env python

import argparse
import glob

parser = argparse.ArgumentParser()
parser.add_argument('-i', action="store", dest="i")
results = parser.parse_args()
print 'argument i is: ', results.i
list_of_matched_files = glob.glob(results.i)
</code>```

In this case, everything works great if the user adds quotes to the passed argument like so:

```<code>./test_script.py -i "foo*.txt"
</code>```

...but often times the users forget to add quotes to the argument and are stumped when the list only contains the first match because UNIX already expanded the list and argparse only then gets the first list element.

Is there a way (within the script) to prevent UNIX from expanding the list before passing it to python? Or maybe even just to test if the argument doesn't contain quotes and then warn the user?

答:
Its not UNIX that is doing the expansion, it is the shell.

Bash has an option set -o noglob (or -f) which turns off globbing (filename expansion), but that is non-standard.

If you give an end-user access to the command-line then they really should know about quoting.  For example, the commonly used find command has a -name parameter which can take glob constructs but they have to be quoted in a similar manner.  Your program is no different to any other.

If users can't handle that then maybe you should give them a different interface.  You could go to the extreme of writing a GUI or a web/HTML front-end, but that's probably over the top.

Or why not prompt for the filename pattern?  You could, for example, use a -p option to indicate prompting, e.g:

```<code>import argparse
import glob

parser = argparse.ArgumentParser()
parser.add_argument('-i', action="store", dest="i")
parser.add_argument('-p', action="store_true", default=False)

results = parser.parse_args()

if results.p:
    pattern = raw_input("Enter filename pattern: ")
else:
    pattern = results.i

list_of_matched_files = glob.glob(pattern)
print list_of_matched_files
</code>```

(I have assumed Python 2 because of your print statement)

Here the input is not read by the shell but by python, which will not expand glob constructs unless you ask it to.

Body:
I have a python script that I'd like to supply with an argument (usually) containing wildcards, referring to a series of files that I'd like to do stuff with. Example here:

#!/usr/bin/env python

import argparse
import glob

parser = argparse.ArgumentParser()
parser.add_argument('-i', action="store", dest="i")
results = parser.parse_args()
print 'argument i is: ', results.i
list_of_matched_files = glob.glob(results.i)

In this case, everything works great if the user adds quotes to the passed argument like so:

./test_script.py -i "foo*.txt"

...but often times the users forget to add quotes to the argument and are stumped when the list only contains the first match because UNIX already expanded the list and argparse only then gets the first list element.

Is there a way (within the script) to prevent UNIX from expanding the list before passing it to python? Or maybe even just to test if the argument doesn't contain quotes and then warn the user?

Body:
Its not UNIX that is doing the expansion, it is the shell.

Bash has an option set -o noglob (or -f) which turns off globbing (filename expansion), but that is non-standard.

If you give an end-user access to the command-line then they really should know about quoting.  For example, the commonly used find command has a -name parameter which can take glob constructs but they have to be quoted in a similar manner.  Your program is no different to any other.

If users can't handle that then maybe you should give them a different interface.  You could go to the extreme of writing a GUI or a web/HTML front-end, but that's probably over the top.

Or why not prompt for the filename pattern?  You could, for example, use a -p option to indicate prompting, e.g:

import argparse
import glob

parser = argparse.ArgumentParser()
parser.add_argument('-i', action="store", dest="i")
parser.add_argument('-p', action="store_true", default=False)

results = parser.parse_args()

if results.p:
    pattern = raw_input("Enter filename pattern: ")
else:
    pattern = results.i

list_of_matched_files = glob.glob(pattern)
print list_of_matched_files

(I have assumed Python 2 because of your print statement)

Here the input is not read by the shell but by python, which will not expand glob constructs unless you ask it to.


问:
Plot a graph using python2.7 for a program starting and ending at various timestamps
I have a program that is starting and ending at various times and I have captured the timings.

Example:

```<code>[('05:43:44', '05:43:51'), ('05:59:32', '05:59:39'), ('06:14:46', '06:41:03'), ('06:41:16', '06:42:57')]
</code>```

The start and end times are paired together for an instance in a tuple as shown below.

```<code>{ Example [(1st start time, 1st end time), (2nd start time, 2nd end time) ..and so on }
</code>```

I want to plot the curve for the start, end times for the program and a meaningful graph. Please provide me ideas how to do plot this in Python 2.7.

I tried to run this, but get Value Error

Test Data:

  [('05:43:44', '05:59:32', '06:14:46', '06:41:16'),('05:43:51', '05:59:39', '06:41:03', '06:42:57')]*

```<code>import matplotlib.pyplot as plt
plt.scatter(*zip(*zipped_files))
plt.show()
</code>```

Error:

```<code>ValueErrorTraceback (most recent call last)
<ipython-input-84-713cb20ee252> in <module>()
1 import matplotlib.pyplot as plt
2
----> 3 plt.scatter(*zip(*zipped_files))
4 plt.show()
ValueError: invalid literal for float(): 05:43:44
</code>```

答:
Looks like you want to generate a best fit for plotting start times against end times. You can use matplotlib to do this:

```<code>from matplotlib import pyplot as plt
l = EXAMPLE LIST
starts = list(i[0] for i in l)
ends = list(i[1] for i in l)
plt.plot(starts, ends, -b)
plt.show()
</code>```

You can use polyfit to generate best fit lines/curves as desired. Hope this helps at least give a general idea of what to do, even if it's not exactly what you were looking for.

Body:
I have a program that is starting and ending at various times and I have captured the timings.

Example:

[('05:43:44', '05:43:51'), ('05:59:32', '05:59:39'), ('06:14:46', '06:41:03'), ('06:41:16', '06:42:57')]

The start and end times are paired together for an instance in a tuple as shown below.

{ Example [(1st start time, 1st end time), (2nd start time, 2nd end time) ..and so on }

I want to plot the curve for the start, end times for the program and a meaningful graph. Please provide me ideas how to do plot this in Python 2.7.

I tried to run this, but get Value Error

Test Data:

  [('05:43:44', '05:59:32', '06:14:46', '06:41:16'),('05:43:51', '05:59:39', '06:41:03', '06:42:57')]*

import matplotlib.pyplot as plt
plt.scatter(*zip(*zipped_files))
plt.show()

Error:

ValueErrorTraceback (most recent call last)
<ipython-input-84-713cb20ee252> in <module>()
1 import matplotlib.pyplot as plt
2
----> 3 plt.scatter(*zip(*zipped_files))
4 plt.show()
ValueError: invalid literal for float(): 05:43:44

Body:
Looks like you want to generate a best fit for plotting start times against end times. You can use matplotlib to do this:

from matplotlib import pyplot as plt
l = EXAMPLE LIST
starts = list(i[0] for i in l)
ends = list(i[1] for i in l)
plt.plot(starts, ends, -b)
plt.show()

You can use polyfit to generate best fit lines/curves as desired. Hope this helps at least give a general idea of what to do, even if it's not exactly what you were looking for.


问:
The relationship could not be changed because one or more of the foreign-key properties is non-nullable
I am getting this error when I GetById() on an entity and then set the collection of child entities to my new list which comes from the MVC view.

The operation failed: The
  relationship could not be changed
  because one or more of the foreign-key
  properties is non-nullable. When a
  change is made to a relationship, the
  related foreign-key property is set to
  a null value. If the foreign-key does
  not support null values, a new
  relationship must be defined, the
  foreign-key property must be assigned
  another non-null value, or the
  unrelated object must be deleted.

I don't quite understand this line:

The relationship could not be changed
  because one or more of the foreign-key
  properties is non-nullable.

Why would I change the relationship between 2 entities? It should remain the same throughout the lifetime of the whole application.

The code the exception occurs on is simple assigning modified child classes in a collection to the existing parent class.  This would hopefully cater for removal of child classes, addition of new ones and modifications.  I would have thought Entity Framework handles this.

The lines of code can be distilled to:

```<code>var thisParent = _repo.GetById(1);
thisParent.ChildItems = modifiedParent.ChildItems();
_repo.Save();
</code>```

答:
I also solved my problem with Mosh's answer and I thought PeterB's answer was a bit of since it used an enum as foreign key. Remember that you will need to add a new migration after adding this code.

I can also recommend this blog post for other solutions:

http://www.kianryan.co.uk/2013/03/orphaned-child/

Code:

```<code>public class Child
{
    [Key, Column(Order = 0), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public string Heading { get; set; }
    //Add other properties here.

    [Key, Column(Order = 1)]
    public int ParentId { get; set; }

    public virtual Parent Parent { get; set; }
}
</code>```

Body:
I am getting this error when I GetById() on an entity and then set the collection of child entities to my new list which comes from the MVC view.

The operation failed: The
  relationship could not be changed
  because one or more of the foreign-key
  properties is non-nullable. When a
  change is made to a relationship, the
  related foreign-key property is set to
  a null value. If the foreign-key does
  not support null values, a new
  relationship must be defined, the
  foreign-key property must be assigned
  another non-null value, or the
  unrelated object must be deleted.

I don't quite understand this line:

The relationship could not be changed
  because one or more of the foreign-key
  properties is non-nullable.

Why would I change the relationship between 2 entities? It should remain the same throughout the lifetime of the whole application.

The code the exception occurs on is simple assigning modified child classes in a collection to the existing parent class.  This would hopefully cater for removal of child classes, addition of new ones and modifications.  I would have thought Entity Framework handles this.

The lines of code can be distilled to:

var thisParent = _repo.GetById(1);
thisParent.ChildItems = modifiedParent.ChildItems();
_repo.Save();

Body:
I also solved my problem with Mosh's answer and I thought PeterB's answer was a bit of since it used an enum as foreign key. Remember that you will need to add a new migration after adding this code.

I can also recommend this blog post for other solutions:

http://www.kianryan.co.uk/2013/03/orphaned-child/

Code:

public class Child
{
    [Key, Column(Order = 0), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public string Heading { get; set; }
    //Add other properties here.

    [Key, Column(Order = 1)]
    public int ParentId { get; set; }

    public virtual Parent Parent { get; set; }
}


问:
Jquery Add class to next image in  tag using JQuery
How can jQuery be used to add class to next image?

I have set of images in webpage using for loop. They are displayed in table rows.

```<code><table class="table table-bordered">
  <?php
    <td><img class="img1" src="http://s5.tinypic.com/30v0ncn_th.jpg"/></td>

    for ($x = 0; $x < 5; $x++) { ?>
      <td>
        <img class="loopimg" src="http://s5.tinypic.com/30v0ncn_th.jpg"/>
      </td>
    <?php  } ?>
</table>
</code>```

What I would like to achieve is when i click on first image (class="img1"), it add class to the next image , clicking on that would add class to the next image.

```<code>$('.img1').click(function(){
  $(this).parent().next("td").addClass("active");
  alert("class");
});
</code>```

This Jquery code add "active" class to next  tag, i would like class to be added to next image. Thank you in advance

答:
Add class to td children:

```<code>$('.table .img').click(function(){
    $(this).parent().next("td").children('img').addClass("active");
    alert("class");
});
</code>```

I change selector to .table .img to work with any table image.

Body:
How can jQuery be used to add class to next image?

I have set of images in webpage using for loop. They are displayed in table rows.

  <?php

    for ($x = 0; $x < 5; $x++) { ?>

    <?php  } ?>

What I would like to achieve is when i click on first image (class="img1"), it add class to the next image , clicking on that would add class to the next image.

$('.img1').click(function(){
  $(this).parent().next("td").addClass("active");
  alert("class");
});

This Jquery code add "active" class to next  tag, i would like class to be added to next image. Thank you in advance

Body:
Add class to td children:

$('.table .img').click(function(){
    $(this).parent().next("td").children('img').addClass("active");
    alert("class");
});

I change selector to .table .img to work with any table image.


问:
Text Editor for gigabyte sized files

Possible Duplicate:

  Text editor to open big (giant, huge, large) text files

I saw text editor to open big text files but that question referred to megabyte sized files. I work with 7GB csv files and find that even vim and gedit take a long time to open up.

What text editor do you use for for gigabyte sized files?

Appreciate any advice I can get.

答: don't know about others but i use vim (on windows) for editing GB files and it works every time. http://vim.sourceforge.net/</p>

Title: Text Editor for gigabyte sized files