问:
How can I merge an existing jsonb field when upserting a record in Postgres?
Say I have a table on Postgres with a jsonb column containing {"a": 1, "b": 2}. Now I'd like to upsert a record with the same id and {"b": 10, "c": 20} as the jsonb column value.

Consequently, I'd like the jsonb field of the row to contain {"a": 1, "b": 10, "c": 20}. How can this be achieved?

答:
If you want an "upsert", you can do this with insert ... on conflict...

```<code>insert into the_table (id, json_column)
values (1, '{"b": 10, "c": 20}'::jsonb)
on conflict (id) do update
   set json_column = table_name.json_column || excluded.json_column;
</code>```

Body:
If you want an "upsert", you can do this with insert ... on conflict...

insert into the_table (id, json_column)
values (1, '{"b": 10, "c": 20}'::jsonb)
on conflict (id) do update
   set json_column = table_name.json_column || excluded.json_column;


来源: stackexchange

问:
Getting a scala stacktrace
When my scala-js code throws an error, I'd like to send a sensible stacktrace back to my server to put in the logs.  By "sensible stacktrace" I mean something that gives the Scala methods, filenames, and line numbers rather than the transpiled javascript code.

I've made good progress by getting the source map and using the Javascript source-map library (https://github.com/mozilla/source-map) to translate each element of the stacktrace from javascript to the corresponding Scala code.

My issue:  I need the column number of the javascript code that threw the error but don't see how to obtain it.  Printing a StackTraceElement gives a result similar to

```<code>oat.browser.views.query.QueryRunView$.renderParamsTable$1(https://localhost:9443/assets/browser-fastopt.js:34787:188)
</code>```

I need the "188" at the end of the line but don't see how to get it other than calling toString and parsing the result.  Looking at the StackTraceElement code, the column number is a private variable with nothing in the API to access it.

Is there another approach to this that I'm completely overlooking? Anything built into scala-js that converts a javascript stacktrace to a Scala stacktrace?

答: I subsequently found the StackTraceJS library which does what I needed.  I combined a ScalaJS facade for it with a facade for JSNlog to come up with a package that meets my needs pretty well.  See jsnlog-facade.  It logs to the browser console and/or the server, with Scala stack traces.  Demo code included.</p>

ContentLicense: CC BY-SA 3.0

Title: Getting a scala stacktrace

Body:
When my scala-js code throws an error, I'd like to send a sensible stacktrace back to my server to put in the logs.  By "sensible stacktrace" I mean something that gives the Scala methods, filenames, and line numbers rather than the transpiled javascript code.

I've made good progress by getting the source map and using the Javascript source-map library (https://github.com/mozilla/source-map) to translate each element of the stacktrace from javascript to the corresponding Scala code.

My issue:  I need the column number of the javascript code that threw the error but don't see how to obtain it.  Printing a StackTraceElement gives a result similar to

oat.browser.views.query.QueryRunView$.renderParamsTable$1(https://localhost:9443/assets/browser-fastopt.js:34787:188)

I need the "188" at the end of the line but don't see how to get it other than calling toString and parsing the result.  Looking at the StackTraceElement code, the column number is a private variable with nothing in the API to access it.

Is there another approach to this that I'm completely overlooking? Anything built into scala-js that converts a javascript stacktrace to a Scala stacktrace?


问:
Ajax get function with endpoints
I have an endpoint on the server:

```<code>app.get('/A/:A_Id/B/:B_Id/C?', callbackFunction);
</code>```

After I type "http://xx.xx.xx.xx:3000/A/1/B/1/C?startTimeUtc=03:00:00&endTimeUtc=05:00:00" the server responds with data in callbackFunction, I can see the data in address http://xx.xx.xx.xx:3000/A/1/B/1/C?startTimeUtc=03:00:00&endTimeUtc=05:00:00 (the startTimeUtc and endTimeUtc can change depending on the user inputs),
but I am not able to get data with an ajax get function:

```<code>  $.ajax({
      type: 'GET',
      url: '/A/:A_ID/B/:B_ID/C?', success: function(result){
      // result is NaN
}
</code>```

What should be the correct endpoint in this case?

答:
You can do something like:

```<code>var url = "http://xx.xx.xx.xx:3000/A/" + A_ID + "/B/" + B_ID + "/C?startTimeUtc=" + startTime + "&endTimeUtc=" + endTime;

$.get( url, function( data ) {
    console.log(data);
});
</code>```

Where A_ID, B_ID, startTime and endTime are the variables containing the respective values.

Title: Ajax get function with endpoints

Body:
I have an endpoint on the server:

app.get('/A/:A_Id/B/:B_Id/C?', callbackFunction);

After I type "http://xx.xx.xx.xx:3000/A/1/B/1/C?startTimeUtc=03:00:00&endTimeUtc=05:00:00" the server responds with data in callbackFunction, I can see the data in address http://xx.xx.xx.xx:3000/A/1/B/1/C?startTimeUtc=03:00:00&endTimeUtc=05:00:00 (the startTimeUtc and endTimeUtc can change depending on the user inputs),
but I am not able to get data with an ajax get function:

  $.ajax({
      type: 'GET',
      url: '/A/:A_ID/B/:B_ID/C?', success: function(result){
      // result is NaN
}

What should be the correct endpoint in this case?

Body:
You can do something like:

var url = "http://xx.xx.xx.xx:3000/A/" + A_ID + "/B/" + B_ID + "/C?startTimeUtc=" + startTime + "&endTimeUtc=" + endTime;

$.get( url, function( data ) {
    console.log(data);
});

Where A_ID, B_ID, startTime and endTime are the variables containing the respective values.


问:
Swift - App Extension to open PDF files
I want my app to be able to copy PDF files from Safari, just like adobe reader can copy them from Safari.

Is this a private API that adobe reader uses?
I can't find any guide about such action and by reading apple documentation I became more confused and now I have no idea if I need to use a UIActivityViewController or a UIDocumentInteractionController.

答:
You need to look into the Document Interaction API

You should specifically look into the Registering Your Support of File Types and Opening Files From Other Apps sections.

Once you've registered PDF as a file type your app supports, your app will appear in the list that shows when you press the More... button.

If your app is the only app that can open PDFs, it will appear instead of "Adobe Acrobat" on the right.

If you have multiple apps that can open PDFs on your phone, iOS will choose one, but you have no control over which one. Even the user has no control over which one.

Title: Swift - App Extension to open PDF files


问:
Watson Conversation_Nodes that has no response
So I wrote this JSON code just like the following

```<code>{
  "context": {
    "action": {
      "dates": "$dates",
      "command": [
        "check-dates"
      ]
    },
    "output": {
      "text": {
        "values": [
          "$dates, Do you want to pick this as a designated date?"
        ]
      }
    }
  },
  "output": {}
}
</code>```

The problem is that this doesn't count as a response as I've expected and I tried to erase that last "output" thing but it just pops out whenever I click the node again for some reasons. Any suggestion is more than a welcome :D Thanks

答:
Your JSON have some incorrect syntax. You have not closed all JSON values in the context

For have some answer:

```<code>{
  "context": {
    "action": {
      "dates": "$dates",
      "command": [
        "check-dates"
      ]
    }
  },
  "output": {
    "text": {
      "values": [
        "Your answer here."
      ],
      "selection_policy": "sequential"
    }
  }
}
</code>```

If you don't want one response for the user, give the [] empty like:

```<code>{
  "context": {
    "action": {
      "dates": "$dates",
      "command": [
        "check-dates"
      ]
    }
  },
  "output": {
    "text": {
      "values": [
        ""
      ],
      "selection_policy": "sequential"
    }
  }
}
</code>```

I recommend, for you make sure if your Syntax from your JSON is correct here.

Body:
So I wrote this JSON code just like the following

{
  "context": {
    "action": {
      "dates": "$dates",
      "command": [
        "check-dates"
      ]
    },
    "output": {
      "text": {
        "values": [
          "$dates, Do you want to pick this as a designated date?"
        ]
      }
    }
  },
  "output": {}
}

The problem is that this doesn't count as a response as I've expected and I tried to erase that last "output" thing but it just pops out whenever I click the node again for some reasons. Any suggestion is more than a welcome :D Thanks

Body:
Your JSON have some incorrect syntax. You have not closed all JSON values in the context

For have some answer:

{
  "context": {
    "action": {
      "dates": "$dates",
      "command": [
        "check-dates"
      ]
    }
  },
  "output": {
    "text": {
      "values": [
        "Your answer here."
      ],
      "selection_policy": "sequential"
    }
  }
}

If you don't want one response for the user, give the [] empty like:

{
  "context": {
    "action": {
      "dates": "$dates",
      "command": [
        "check-dates"
      ]
    }
  },
  "output": {
    "text": {
      "values": [
        ""
      ],
      "selection_policy": "sequential"
    }
  }
}

I recommend, for you make sure if your Syntax from your JSON is correct here.


问:
Using .NET Standard in Xamarin iOS
I have added a reference to a .NET Standard Library (1.3) in my Xamarin iOS project.

In runtime, when I create an instance of a class defined in the .NET Standard Library, it throws this exception:

Unhandled Exception:

System.TypeLoadException: Could not find method due to a type load
  error

For example, it happens when I do:

```<code>var c = new Customer();
</code>```

What's happening and how can I fix it?

答: Finally I did it: The problem was that I had to include transitive references. That is, my project A references B, and B references C. So I had to include A => C. Not pretty obvious. I also had to include all the NuGet packages my references use. Building and running now!</p>

Title: Using .NET Standard in Xamarin iOS

Body:
I have added a reference to a .NET Standard Library (1.3) in my Xamarin iOS project.

In runtime, when I create an instance of a class defined in the .NET Standard Library, it throws this exception:

Unhandled Exception:

System.TypeLoadException: Could not find method due to a type load
  error

For example, it happens when I do:

var c = new Customer();

What's happening and how can I fix it?


问:
iOS Apple Pay - Customize PKPaymentButton
I'm using PKPaymentButton for ApplePay integration but want to know if I can customize it easily.

```<code>let applePayButton = PKPaymentButton(type: PKPaymentButtonType.setUp, style: PKPaymentButtonStyle.black)
</code>```

Can we change the button style?
After setup of ApplePay, I wanted to change the buttonType to .buy but didn't find a solution.

Can we remove corner radius?
Default ApplePay button has corner radius. I don't like it and tried to remove it. So, I tried to work with layer but it didn't work.

```<code>applePayButton.layer.cornerRadius = 0
</code>```

Please let me know if I can change the ApplePay button properties easily.

答: In the Apple Pay Identity Guidelines, Apple states that you should not change the corner radius of the Apple Pay button (PKPaymentButton).

Body:
I'm using PKPaymentButton for ApplePay integration but want to know if I can customize it easily.

let applePayButton = PKPaymentButton(type: PKPaymentButtonType.setUp, style: PKPaymentButtonStyle.black)

Can we change the button style?
After setup of ApplePay, I wanted to change the buttonType to .buy but didn't find a solution.

Can we remove corner radius?
Default ApplePay button has corner radius. I don't like it and tried to remove it. So, I tried to work with layer but it didn't work.

applePayButton.layer.cornerRadius = 0

Please let me know if I can change the ApplePay button properties easily.


问:
Time dependent Master data via History tables in SAP HANA
I was looking for the best way to capture historical data in HANA for master data tables without the VALID_TO and VALID_FROM fields.

From my understanding, we have 2 options here.

Create a custom history table and run a stored procedure that populates this history table from the original table. Here we compromise with the real-time reporting capability on top of this table.

Enable the History table flag in SLT for this table so that SLT creates this as a history table which solves this problem.

Option 2 looks like a clear winner to me but I would like your thoughts on this as well.

Let me know.

Thanks,

Shyam

答:
You asked for thoughts...
I would not use history tables for modeling time dependent master data. That's not the way history tables work. Think of them as system versioned temporal tables using commit IDs for the validity range. There are several posts on this topic in the SAP community.

Most applications I know need application time validity ranges instead (or sometimes both). Therefore I would rather model the time dependency explicitly using valid from / valid to. This gives you the opportunity e.g. to model temporal joins in CalcViews or query the data using "standard" SQL. The different ETL tools like EIM SDI or BODS have also options for populating such time dependent tables using special transformations like "table comparison" or "history preserving". Just search the web for "slowly changing dimensions" for the concepts.

In the future maybe temporal tables as defined in SQL 2011 could be an option as well, but I do not know when those will be available in HANA.


问:
How to chop off characters after a space?
I have a variable - 2 words separated by a single space : $var = "xxxx yyyy". In perl, how do i use regular expressions to make $var = "xxxx"

Thanks,
Trinity

答:
Replace \s.+$ by nothing:

```<code>$var =~ s/ .+$//
</code>```

(as per elusive's comment)

ContentLicense: CC BY-SA 2.5

Body:
Replace \s.+$ by nothing:

$var =~ s/ .+$//

(as per elusive's comment)


问:
Play/Stop button to control a loop
I'd like to start and stop a loop with play and start button but it doesn't work. I've got an infinite loop when I press test button.

```<code>import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Vibration } from '@ionic-native/vibration';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})

export class HomePage {

  isPlayed: boolean = false;

  constructor(public navCtrl: NavController, private vibration: Vibration) {

  }

  play(){
    this.isPlayed = true;
    this.test();
    console.log(this.isPlayed);
  }

  stop(){
    this.isPlayed = false;
    this.test();
    console.log(this.isPlayed);
  }

  test(){
    while (this.isPlayed == true) {
      console.log("test")
  }
}
}
</code>```

And the HTML :

```<code><ion-header>
  <ion-navbar>
    <ion-title>
      Pulse
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <button ion-button (click)="play()">
    Play
  </button>
  <button ion-button (click)="stop()">
    Stop
  </button>
  <button ion-button (click)="test()">
    Test
  </button>
  {{counter}}
</ion-content>
</code>```

答:
I think while loop wont work. you can try with try with setInterval and clearInterval</p>

```<code> public timer;

   play() {
        this.timer= setInterval(function () {
             console.log("test") // this is inside your loop
        }, 100);
    };

    stop() {
        clearInterval( this.timer);
    };
</code>```

Title: Play/Stop button to control a loop

Body:
I'd like to start and stop a loop with play and start button but it doesn't work. I've got an infinite loop when I press test button.

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Vibration } from '@ionic-native/vibration';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})

export class HomePage {

  isPlayed: boolean = false;

  constructor(public navCtrl: NavController, private vibration: Vibration) {

  }

  play(){
    this.isPlayed = true;
    this.test();
    console.log(this.isPlayed);
  }

  stop(){
    this.isPlayed = false;
    this.test();
    console.log(this.isPlayed);
  }

  test(){
    while (this.isPlayed == true) {
      console.log("test")
  }
}
}

And the HTML :

<ion-header>
  <ion-navbar>
    <ion-title>
      Pulse
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <button ion-button (click)="play()">
    Play
  </button>
  <button ion-button (click)="stop()">
    Stop
  </button>
  <button ion-button (click)="test()">
    Test
  </button>
  {{counter}}
</ion-content>

Body:
I think while loop wont work. you can try with try with setInterval and clearInterval

 public timer;

   play() {
        this.timer= setInterval(function () {
             console.log("test") // this is inside your loop
        }, 100);
    };

    stop() {
        clearInterval( this.timer);
    };


问:
How to put contact form on slider
I am trying to put my form on a slider in such a way that slider seems to be running in the background of form. If I am using position absolute, then I have to apply a lot of margin and top pixels because there is a navbar above the slider and position absolute applies with respect to the parent element(navbar).

How can I exactly target the position absolute w.r.t my form, not navbar (parent element)?
Or

If you guys think that there can be a better option to deal with this then do share ideas!

Thanks in advance!

Here is the demo link

HTML code:

```<code>    <section id="main-slider" class="carousel">

    <!--start-->
    <div id="ninja-slider">
        <div class="slider-inner">
            <ul>
                <li  class="dummySlide">
                    <a class="ns-img" href="img/002.jpg"></a>
                </li>

                <li>
                    <a class="ns-img" href="img/003.jpg"></a>
                </li>

                <li>
                    <a class="ns-img" href="img/004.jpg"></a>
                </li>

                <li>
                    <a class="ns-img" href="img/005.jpg"></a>
                </li>

                <li>
                    <a class="ns-img" href="img/zess.jpg"></a>
                </li>
            </ul>
            <div class="navsWrapper">
                <div id="ninja-slider-prev"></div>
                <div id="ninja-slider-next"></div>
            </div>
        </div>
    </div>
    <!--end-->

    </section><!--/#main-slider-->

            <form role="form">

<!--First Row-->
   <div class="row">
        <div class="form-group col-md-6">
            <label for="inputTopic" class="control-label">Title</label>
            <select class="form-control" name="title">
                    <option value="0">Select</option>
                    <option value="one">Mr.</option>
                    <option value="two">Miss</option>
                    <option value="three">Mrs.</option>
                    <option value="four">Dr.</option>
                </select>
        </div>

        <div class="form-group col-md-6">
            <label for="inputTopic" class="control-label">Sur-Name</label>
                <input type="text" class="form-control"  name="surname" />
        </div>
    </div>
</form>
</code>```

答:
```<code><div class="row" style="position:relative; top:-200px; z-index:3; text-align:center;">
</code>```

Where you declare the

put this code

  <div class="row" style="position:relative; top:-200px; z-index:3; text-align:center;"

This will definitely work

Title: How to put contact form on slider

Body:
I am trying to put my form on a slider in such a way that slider seems to be running in the background of form. If I am using position absolute, then I have to apply a lot of margin and top pixels because there is a navbar above the slider and position absolute applies with respect to the parent element(navbar).

How can I exactly target the position absolute w.r.t my form, not navbar (parent element)?
Or

If you guys think that there can be a better option to deal with this then do share ideas!

Thanks in advance!

Here is the demo link

HTML code:

            <form role="form">

            Title
            <select class="form-control" name="title">
                    <option value="0">Select</option>
                    <option value="one">Mr.</option>
                    <option value="two">Miss</option>
                    <option value="three">Mrs.</option>
                    <option value="four">Dr.</option>
                </select>

            Sur-Name
                <input type="text" class="form-control"  name="surname" />

</form>

Body:
<div class="row" style="position:relative; top:-200px; z-index:3; text-align:center;">

Where you declare the <div class="row">

put this code

  <div class="row" style="position:relative; top:-200px; z-index:3; text-align:center;"

This will definitely work


问:
output 2d boolean masked value by tensorflow
I have a [n,m] input and [n,m] boolean mask. How could I output a [n,x] filtered matrix, instead of [x] array?

For example, input

```<code>x = [[1,2,3],[4,5,6]]
</code>```

and a boolean mask

```<code>bm = [[1,0,1],[1,0,0]]
</code>```

I tried to use tf.boolean_mask() and I got [1,3,4].
How could I get a 2D result like

```<code>result =  [[1,3],[4]]
</code>```

Thanks!

答: This operation could not exist in TF because TF operates on the tensors and returns tensors. The result you received has different number of elements and not a tensor.</p>

Body:
I have a [n,m] input and [n,m] boolean mask. How could I output a [n,x] filtered matrix, instead of [x] array?

For example, input

x = [[1,2,3],[4,5,6]]

and a boolean mask

bm = [[1,0,1],[1,0,0]]

I tried to use tf.boolean_mask() and I got [1,3,4].
How could I get a 2D result like

result =  [[1,3],[4]]

Thanks!


问:
Find S3 Bucket Owner
If there is a bucket that I have read/write access on from my AWS account, is there any way to get the CanonicalUser id of the owner?

Reading the ACL Policy seems to be impossible unless you are the owner : /.

答:
Use get-bucket-acl, if you have read permission of the bucket. It would give output like this</p>

```<code>{
    "Owner": {
        "DisplayName": "my-username",
        "ID": "7009a8971cd538e11f6b6606438875e7c86c5b672f46db45460ddcd087d36c32"
    },
    "Grants": [
        {
            "Grantee": {
                "DisplayName": "my-username",
                "ID": "7009a8971cd538e11f6b6606438875e7c86c5b672f46db45460ddcd087d36c32"
            },
            "Permission": "FULL_CONTROL"
        }
    ]
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Find S3 Bucket Owner

Body:
Use get-bucket-acl, if you have read permission of the bucket. It would give output like this

{
    "Owner": {
        "DisplayName": "my-username",
        "ID": "7009a8971cd538e11f6b6606438875e7c86c5b672f46db45460ddcd087d36c32"
    },
    "Grants": [
        {
            "Grantee": {
                "DisplayName": "my-username",
                "ID": "7009a8971cd538e11f6b6606438875e7c86c5b672f46db45460ddcd087d36c32"
            },
            "Permission": "FULL_CONTROL"
        }
    ]
}


问:
Executing a stored procedure works from Management Studio and localhost but not when published to a server
I am converting a website from Oracle to SQL Server 2016. The website is built in ASP.NET Framework 4 using Visual Studio 2015. The original developer made extensive use of Oracle packages for data manipulation and I have successfully converted everything to stored procedures and user-defined functions. I have successfully rewritten all of the web pages to use the new syntax. I can run the website on the localhost with no errors and am trying to get it to work on our development web server.

The problem: all stored procedures return the same error:

The EXECUTE permission was denied on the object 'USP_My_Procedure', database 'WEB_DB', schema 'WEBDATA'

The user is a member of a Database role which is granted DELETE, EXECUTE, INSERT, REFERENCES, SELECT, UPDATE, and VIEW DEFINITION permissions on the WEBDATA schema:

I am able to SELECT, INSERT, UPDATE, and DELETE data directly from the webpages on the development server when stored procedures are not used. I am able to run the stored procedures from Management Studio when logged on using the application's SQL account. I just can't use the stored procedures to do the work from the website. Unfortunately, I don't have time to rewrite the entire application to eliminate the stored procedures.

Does anyone have any ideas of what to look for? Thank you.

答:
Assuming your database connection string is using trusted security...

If you deployed an ASP.NET application to a development server you are likely using IIS.  If so, then you are likely using an Application Pool.  Verify the Application Pool identity has sufficient privileges on the database.  Performing a test includes connecting to the SQL Server as the security context the application pool identity is based on, then simply try to execute the failing stored procedure in a query window (using this security context).

To view Application Pools...

Open Internet Information Services (IIS) Manager (A.K.A., inetmgr.exe)

In left hand pane, expand server node and click to select 'Application Pools'

In middle pane, click to select any application pool

in right hand pane click to select 'Advanced Settings...'

in section 'Process Model' notice value for 'Identity' (this value can be changed to a domain user account which can be assigned to SQL Server resources).

If you have more than one application pool the trick is to identify the one being used by your ASP.NET application...


问:
mutate_at column names error
I'm trying to apply the anytime() function from the anytime package in a dplyr chain to all columns ending with Date

I'm however getting this error.

```<code>Error: Unsupported Type
</code>```

when I use

```<code>invoicePayment <- head(raw.InvoicePayment) %>%
  mutate_at(ends_with("Date"), funs(anytime))
</code>```

but it's fine when I use

```<code>invoicePayment <- head(raw.InvoicePayment) %>%
  select(ends_with("Date")) %>%
  mutate_at(ends_with("Date"), funs(anytime))
</code>```

Any help is appreciated,
Thanks,

Title: mutate_at column names error

Body:
I'm trying to apply the anytime() function from the anytime package in a dplyr chain to all columns ending with Date

I'm however getting this error.

Error: Unsupported Type

when I use

invoicePayment <- head(raw.InvoicePayment) %>%
  mutate_at(ends_with("Date"), funs(anytime))

but it's fine when I use

invoicePayment <- head(raw.InvoicePayment) %>%
  select(ends_with("Date")) %>%
  mutate_at(ends_with("Date"), funs(anytime))

Any help is appreciated,
Thanks,

Body:
We may need to wrap with vars

library(anytime)
library(dplyr)
df1 %>%
    mutate_at(vars(ends_with("Date")), anytime)
#  col1           col2_Date           col3_Date
#1    1 2017-06-07 05:30:00 2017-06-07 05:30:00
#2    2 2017-06-08 05:30:00 2017-06-06 05:30:00
#3    3 2017-06-09 05:30:00 2017-06-05 05:30:00
#4    4 2017-06-10 05:30:00 2017-06-04 05:30:00
#5    5 2017-06-11 05:30:00 2017-06-03 05:30:00

data

df1 <- data.frame(col1 = 1:5, col2_Date = Sys.Date() + 0:4, col3_Date = Sys.Date() - 0:4)


问:
cross build error: libtool: line 1112: lib: command not found
I'm attempting to cross-build an application from Linux for windows using M Cross Environment which is really just a system of makefiles which help use the Mingw-w64 tools. The build system for the application is autotools.

When I try the build I get and error like the following:

```<code>libtool: link: lib -OUT:.libs/liby12.lib  y12mae.o y12maf.o y12mbe.o y12mbf.o y12mce.o y12mcf.o y12mde.o y12mdf.o y12mfe.o y12mge.o y12mhe.o
../../libtool: line 1112: lib: command not found
make[4]: *** [liby12.la] Error 127
make[4]: Leaving directory `/opt/mxe/tmp-mbdyn-i686-w64-mingw32.static/mbdyn-1.7.1.build_/libraries/liby12'
make[3]: *** [all-recursive] Error 1
make[3]: Leaving directory `/opt/mxe/tmp-mbdyn-i686-w64-mingw32.static/mbdyn-1.7.1.build_/libraries'
make[2]: *** [all-recursive] Error 1
make[2]: Leaving directory `/opt/mxe/tmp-mbdyn-i686-w64-mingw32.static/mbdyn-1.7.1.build_'
make[1]: *** [build-only-mbdyn_i686-w64-mingw32.static] Error 2
make[1]: Leaving directory `/opt/mxe'
</code>```

Can anyone explain what the problem is?

Someone else has a similar problem in this stackoverflow question, although they appear to be building natively on windows. There is also discussion on a mailing list here. Neither of these sources gives enough information for someone with my limited knowledge of libtool to solve the problem (I don't even know what line 1112 is referring to, i.e. line 1112 of what exactly, libtool itself? This is a comment line in libtool).

EDIT:

I have discovered the following thread:

http://cygwin.1069669.n5.nabble.com/libtool-link-object-name-conflicts-in-archive-td107913.html#a107969

which is actually about compiling on cygwin the same application I am cross-compiling (mbdyn, but an earlier version). It seems the issue might be due to configure creating a libtool script in the source directory. I'm guessing this clashes with the cross-compiler libtool script or something like this.

So what is the correct way to fix this libtool issue?

答: The problem was actually answered in the link posted. The problem was that AC_PROG_F77 needed to be called outside a conditional statement in configure.ac. Otherwise libtool gets confused when doing the cross compile as the fortran compiler is specified and the conditional is never triggered.

Body:
I'm attempting to cross-build an application from Linux for windows using M Cross Environment which is really just a system of makefiles which help use the Mingw-w64 tools. The build system for the application is autotools.

When I try the build I get and error like the following:

libtool: link: lib -OUT:.libs/liby12.lib  y12mae.o y12maf.o y12mbe.o y12mbf.o y12mce.o y12mcf.o y12mde.o y12mdf.o y12mfe.o y12mge.o y12mhe.o
../../libtool: line 1112: lib: command not found
make[4]: *** [liby12.la] Error 127
make[4]: Leaving directory `/opt/mxe/tmp-mbdyn-i686-w64-mingw32.static/mbdyn-1.7.1.build_/libraries/liby12'
make[3]: *** [all-recursive] Error 1
make[3]: Leaving directory `/opt/mxe/tmp-mbdyn-i686-w64-mingw32.static/mbdyn-1.7.1.build_/libraries'
make[2]: *** [all-recursive] Error 1
make[2]: Leaving directory `/opt/mxe/tmp-mbdyn-i686-w64-mingw32.static/mbdyn-1.7.1.build_'
make[1]: *** [build-only-mbdyn_i686-w64-mingw32.static] Error 2
make[1]: Leaving directory `/opt/mxe'

Can anyone explain what the problem is?

Someone else has a similar problem in this stackoverflow question, although they appear to be building natively on windows. There is also discussion on a mailing list here. Neither of these sources gives enough information for someone with my limited knowledge of libtool to solve the problem (I don't even know what line 1112 is referring to, i.e. line 1112 of what exactly, libtool itself? This is a comment line in libtool).

EDIT:

I have discovered the following thread:

http://cygwin.1069669.n5.nabble.com/libtool-link-object-name-conflicts-in-archive-td107913.html#a107969

which is actually about compiling on cygwin the same application I am cross-compiling (mbdyn, but an earlier version). It seems the issue might be due to configure creating a libtool script in the source directory. I'm guessing this clashes with the cross-compiler libtool script or something like this.

So what is the correct way to fix this libtool issue?


问:
How to set a placeholder for a Image control (while it downloads)?
I have an app that show a list of images. The image source is set to a http URL, and the images are downloaded and display automatically.

However, while the app is taking time to download, the image control shows nothing. The user experience is not good this way.

How may I display a loading placeholder image, or a loading gauge, for each of the image control?

答:
Interesting how many options there are for tackling this problem.

You might also like to consider Ben Gracewood's image caching implementation or what appears to be a development on that idea in his blog comments.

One-time Cached Images in Windows Phone 7 « Ben.geek.nz

Peter Nowaks Mobile Blog - “Intelligent” Image Caching for WP 7

Some background on the discussion leading up to this here if it's of interest.

Image control cache duration?


问:
R warning: "number of items to replace is not a multiple of replacement length" seems incorrect
I have an example R script that looks like this:

```<code># Create example data
date <- c("11/09/2016", "11/02/2016", "11/16/2016", "11/23/2016")
column_two <- c(4, 2, 3, 4)
# Populate a data frame and make sure the dates have the correct class
mydata <- data.frame(date, column_two)
mydata$date <- strptime(mydata$date, format="%m/%d/%Y")

print("The contents of mydata are:")
print(mydata)

# Create a dummy list (or vector, or array, or what is it?)
foo <- rep(NA, 5)
print("foo is initialized to:")
print(foo)
print("The class of foo is:")
print(class(foo))

earlydate <- min(mydata$date)
print(sprintf("Earliest date is: %s", earlydate))
print("The class of earlydate is:")
print(class(earlydate))
print(sprintf("Length of earliest date is: %d", length(earlydate)))
print(sprintf("Length of foo[2] is: %d", length(foo[2])))

# Attempt to set one variable equal to another
foo[2] <- earlydate

print("After assignment, foo looks like this:")
print(foo)
print("Now the classes of foo, foo[2], and foo[[2]] are:")
print(class(foo))
print(class(foo[2]))
print(class(foo[[2]]))
</code>```

The printed output from the script looks like this:

```<code>> source("test_warning.R")
[1] "The contents of mydata are:"
        date column_two
1 2016-11-09          4
2 2016-11-02          2
3 2016-11-16          3
4 2016-11-23          4
[1] "foo is initialized to:"
[1] NA NA NA NA NA
[1] "The class of foo is:"
[1] "logical"
[1] "Earliest date is: 2016-11-02"
[1] "The class of earlydate is:"
[1] "POSIXlt" "POSIXt"
[1] "Length of earliest date is: 1"
[1] "Length of foo[2] is: 1"
[1] "After assignment, foo looks like this:"
[[1]]
[1] NA

[[2]]
[1] 0

[[3]]
[1] NA

[[4]]
[1] NA

[[5]]
[1] NA

[1] "Now the classes of foo, foo[2], and foo[[2]] are:"
[1] "list"
[1] "list"
[1] "numeric"
Warning message:
In foo[2] <- earlydate :
  number of items to replace is not a multiple of replacement length
>
</code>```

I have so many questions:

Why do I get a warning when foo[2] and earlydate are manifestly the same length?

Why is the value of foo[2] set to 0 rather than to the value of earlydate?

It's obvious that R is automatically coercing the foo variable and its elements into new classes; why don't any of those classes (for foo, or foo[2], or foo[[2]]) seem to match the class ("POSIXlt" "POSIXt") of the earlydate variable?

How would I initialize foo correctly so that it becomes a vector, or list, or array-like thing containing individual elements which are capable of supporting this type of value assignment without raising the warning and resulting in this type of counter-intuitive behavior?

答:
Well, behind the scenes of POSIXlt is actually a list.

```<code>> class(unclass(earlydate))
[1] "list"
> length(unclass(earlydate))
[1] 11
</code>```

The assignment takes 0 because that's the first element of the list; it's the count of seconds and is 0 for earlydate.

```<code>> unclass(earlydate)[1]
$sec
[1] 0
</code>```

I don't really know why R doesn't automatically coerce the foo variable into the POSIXlt class; my guess is that coercion to dates in general is hard. It's clear what to do here where all of foo is NA, but what if one of the elements is already an integer or a string? But to coerce it yourself first, use as.POSIXlt.

```<code>foo <- rep(as.POSIXlt(NA), 5)
</code>```

Depending what else you'll be doing with it, you may also find using POSIXct to be better solution, as discussed in this answer to Integer to POSIXlt. It stores the date as number of seconds since the origin, so is not a list underneath and so is better suited for certain kinds of computation and storage.

Body:
I have an example R script that looks like this:

# Create example data
date <- c("11/09/2016", "11/02/2016", "11/16/2016", "11/23/2016")
column_two <- c(4, 2, 3, 4)
# Populate a data frame and make sure the dates have the correct class
mydata <- data.frame(date, column_two)
mydata$date <- strptime(mydata$date, format="%m/%d/%Y")

print("The contents of mydata are:")
print(mydata)

# Create a dummy list (or vector, or array, or what is it?)
foo <- rep(NA, 5)
print("foo is initialized to:")
print(foo)
print("The class of foo is:")
print(class(foo))

earlydate <- min(mydata$date)
print(sprintf("Earliest date is: %s", earlydate))
print("The class of earlydate is:")
print(class(earlydate))
print(sprintf("Length of earliest date is: %d", length(earlydate)))
print(sprintf("Length of foo[2] is: %d", length(foo[2])))

# Attempt to set one variable equal to another
foo[2] <- earlydate

print("After assignment, foo looks like this:")
print(foo)
print("Now the classes of foo, foo[2], and foo[[2]] are:")
print(class(foo))
print(class(foo[2]))
print(class(foo[[2]]))

The printed output from the script looks like this:

> source("test_warning.R")
[1] "The contents of mydata are:"
        date column_two
1 2016-11-09          4
2 2016-11-02          2
3 2016-11-16          3
4 2016-11-23          4
[1] "foo is initialized to:"
[1] NA NA NA NA NA
[1] "The class of foo is:"
[1] "logical"
[1] "Earliest date is: 2016-11-02"
[1] "The class of earlydate is:"
[1] "POSIXlt" "POSIXt"
[1] "Length of earliest date is: 1"
[1] "Length of foo[2] is: 1"
[1] "After assignment, foo looks like this:"
[[1]]
[1] NA

[[2]]
[1] 0

[[3]]
[1] NA

[[4]]
[1] NA

[[5]]
[1] NA

[1] "Now the classes of foo, foo[2], and foo[[2]] are:"
[1] "list"
[1] "list"
[1] "numeric"
Warning message:
In foo[2] <- earlydate :
  number of items to replace is not a multiple of replacement length
>

I have so many questions:

Why do I get a warning when foo[2] and earlydate are manifestly the same length?

Why is the value of foo[2] set to 0 rather than to the value of earlydate?

It's obvious that R is automatically coercing the foo variable and its elements into new classes; why don't any of those classes (for foo, or foo[2], or foo[[2]]) seem to match the class ("POSIXlt" "POSIXt") of the earlydate variable?

How would I initialize foo correctly so that it becomes a vector, or list, or array-like thing containing individual elements which are capable of supporting this type of value assignment without raising the warning and resulting in this type of counter-intuitive behavior?

Body:
Well, behind the scenes of POSIXlt is actually a list.

> class(unclass(earlydate))
[1] "list"
> length(unclass(earlydate))
[1] 11

The assignment takes 0 because that's the first element of the list; it's the count of seconds and is 0 for earlydate.

> unclass(earlydate)[1]
$sec
[1] 0

I don't really know why R doesn't automatically coerce the foo variable into the POSIXlt class; my guess is that coercion to dates in general is hard. It's clear what to do here where all of foo is NA, but what if one of the elements is already an integer or a string? But to coerce it yourself first, use as.POSIXlt.

foo <- rep(as.POSIXlt(NA), 5)

Depending what else you'll be doing with it, you may also find using POSIXct to be better solution, as discussed in this answer to Integer to POSIXlt. It stores the date as number of seconds since the origin, so is not a list underneath and so is better suited for certain kinds of computation and storage.


问:
The width of the TD is ignored in Outlook 2007/2010/2013
I have created 2 child tables within a parent table. The width of the tables look fine in all the email clients except Outlook 2007/2010/2013 and 2016. The right columns shifts towards the right and ignores the TD width(5%) on both the sides. Can anyone help me out with this?

Here is the code:

`

```<code>                    <!-- Second slider -->
                    <tr>
                        <td align="center" valign="top">
                            <table class="parentTable" border="0" cellpadding="0" cellspacing="0" style="table-layout:fixed;">
                                <tr>
                                    <!-- 1st column - spacing -->
                                    <!-- <td valign="top" width="5%"> </td> -->

                                    <!-- 2nd column - left section -->
                                    <td valign="top" width="50%">
                                        <table class="childTable" border="0" cellpadding="0" cellspacing="0" style="table-layout:fixed;border:none;border-collapse:collapse;mso-table-lspace:0;mso-table-rspace:0;">
                                            <tr>
                                                <td valign="top" width="5%" > </td>
                                                <td width="40%">
                                                    <table class="list-table_1" border="0" cellpadding="0" cellspacing="0" style="border:none;border-collapse:collapse;mso-table-lspace:0;mso-table-rspace:0;">
                                                        <tr>
                                                            <td valign="top" align="left" >
                                                                <p class="heading_1" style="font-family: Georgia, serif;">Left Column Content 1</p>
                                                            </td>
                                                        </tr>

                                                        <tr>
                                                            <td valign="top" align="center" height="10"> </td>
                                                        </tr>
                                                        <tr>
                                                            <td valign="top" align="center" >
                                                                <img src="" class="img-responsive" alt="" style="max-width: 100%;" />
                                                            </td>
                                                        </tr>

                                                        <tr>
                                                            <td valign="top" align="center" height="5"> </td>
                                                        </tr>
                                                        <tr>
                                                            <td valign="top" align="left" >
                                                                <p class="heading_2" style="font-family:Georgia, serif;">Left Column Content 2</p>
                                                            </td>
                                                        </tr>
                                                    </table>
                                                </td>
                                                <td valign="top" width="5%" style="border-right:1px solid #0060af;"> </td>
                                            </tr>
                                        </table>
                                    </td>

                                    <td valign="top" width="50%">
                                        <table class="childTable" border="0" cellpadding="0" cellspacing="0" style="table-layout:fixed;border:none;border-collapse:collapse;mso-table-lspace:0;mso-table-rspace:0;">
                                            <tr>
                                                <td valign="top" width="5%" > </td>
                                                <td width="40%">
                                                    <table class="list-table_1" border="0" cellpadding="0" cellspacing="0" style="border:none;border-collapse:collapse;mso-table-lspace:0;mso-table-rspace:0;">
                                                        <tr>
                                                            <td valign="top" align="left" >
                                                                <p class="heading_1" style="font-family: Georgia, serif;">Right Column Content 1</p>
                                                            </td>
                                                        </tr>

                                                        <tr>
                                                            <td valign="top" align="center" height="10"> </td>
                                                        </tr>
                                                        <tr>
                                                            <td valign="top" align="center" >
                                                                <img src="" class="img-responsive" alt="" style="max-width: 100%;" />
                                                            </td>
                                                        </tr>

                                                        <tr>
                                                            <td valign="top" align="center" height="5"> </td>
                                                        </tr>
                                                        <tr>
                                                            <td valign="top" align="left" >
                                                                <p class="heading_2" style="font-family:Georgia, serif;">Right Column Content 2</p>
                                                            </td>
                                                        </tr>

                                                    </table>
                                                </td>
                                                <td valign="top" width="5%"> </td>
                                            </tr>
                                        </table>
                                    </td>
                                </tr>
                            </table>
                        </td>
                    </tr>
                    <!-- Second slider ends -->

                </table>

            </td>
        </tr>
    </table>
</code>```

`

Thanks

答:
Not sure if this will help you, but I've encountered issues before where Outlook will ignore widths and heights of empty table cells, even if there is an NBSP.

You might try adding something like an underscore in the same color as your background and see if that makes any difference. A small transparent PNG may also work.

Another possible method is to use padding on the TD rather than specifying a width.

Body:
I have created 2 child tables within a parent table. The width of the tables look fine in all the email clients except Outlook 2007/2010/2013 and 2016. The right columns shifts towards the right and ignores the TD width(5%) on both the sides. Can anyone help me out with this?

Here is the code:

`

Left Column Content 1

Left Column Content 2

Right Column Content 1

Right Column Content 2

`

Thanks


问:
Switching players
I'm made a program that calculates the current health of a player and switches between them. I need help switching between players. This is what i have so far:</p>

```<code>class Player():

    def turn(life):
        players = ['Player 1', 'Player 2']
        life = 100
        for player in players:
            while life >= 0:
                print (life)
                print ("+, -, or end turn")
                choice = input("> ")

                if choice == "+":
                    print ("Damage taken")
                    healing = int(input("> "))
                    life += healing
                elif choice == "-":
                    print ("Damage taken")
                    damage = int(input("> "))
                    life -= damage
                elif choice == "end turn" or "end":
                    return

            else:
                print ("You lose!")

play = Player()
play.turn()
</code>```

答:
Here is a start:</p>

```<code>class Player:
    def __init__(self, name, health=100):
        self.name = name
        self.health = health

    def hit(self, n):
        assert n >= 0
        self.health -= n

    def heal(self, n):
        assert n >= 0
        self.health += n

    @property
    def is_dead(self):
        return self.health <= 0

class Game:
    def __init__(self):
        self.players = [Player("Adam"), Player("Bert")]

    def turn(self, me, him):
        # fill this in!

    def play(self):
        a, b = self.players
        while True:
            self.turn(a, b)
            if b.is_dead:
                print("{} won!".format(a.name))
                break
            else:
                # swap players
                a, b = b, a

if __name__ == "__main__":
    Game().play()
</code>```

Title: Switching players

Body:
I'm made a program that calculates the current health of a player and switches between them. I need help switching between players. This is what i have so far:

class Player():

    def turn(life):
        players = ['Player 1', 'Player 2']
        life = 100
        for player in players:
            while life >= 0:
                print (life)
                print ("+, -, or end turn")
                choice = input("> ")

                if choice == "+":
                    print ("Damage taken")
                    healing = int(input("> "))
                    life += healing
                elif choice == "-":
                    print ("Damage taken")
                    damage = int(input("> "))
                    life -= damage
                elif choice == "end turn" or "end":
                    return

            else:
                print ("You lose!")

play = Player()
play.turn()

Body:
Here is a start:

class Player:
    def __init__(self, name, health=100):
        self.name = name
        self.health = health

    def hit(self, n):
        assert n >= 0
        self.health -= n

    def heal(self, n):
        assert n >= 0
        self.health += n

    @property
    def is_dead(self):
        return self.health <= 0

class Game:
    def __init__(self):
        self.players = [Player("Adam"), Player("Bert")]

    def turn(self, me, him):
        # fill this in!

    def play(self):
        a, b = self.players
        while True:
            self.turn(a, b)
            if b.is_dead:
                print("{} won!".format(a.name))
                break
            else:
                # swap players
                a, b = b, a

if __name__ == "__main__":
    Game().play()


问:
Why doesn't SingletonSet implement SortedSet
In order so reduce memory consumption, I'm rewriting a class that has a SortedSet<Integer>. In 80% of cases, this collection contains only a single element . So I thought I could use a SingeltonSet in these cases and a normal TreeSet in other cases. Now I noticed that SingletonSet, as returned by Collections.singleton(), does not implement SortedSet. Is there any reason for this shortcoming? A single element can always be considered sorted I'd say. Do I have to write my own SingletonSet implementation?

答: The SortedSet interface defines methods that require a Comparator for the set elements. Thus elements maintained by a SortedSet have to be comparable. If the singleton returned by Collections.singleton() would implement SortedSet, then Collections.singleton() could accept Comparables only (which is not what we want).


问:
OCaml Makefile: No Rule to Make Target
I'm following this OCamlbuild example, and accordingly have created the Makefile below:

```<code>OCB_FLAGS = -use-ocamlfind -I src -I lib
OCB = ocamlbuild $(OCB_FLAGS)

check: ocamlfind query core async
clean: $(OCB) -clean
byte: $(OCB) main.byte
native: $(OCB) main.native

.PHONY: check clean byte native
</code>```

The root directory contains two sub-directories, src and lib. The src sub-directory contains the file main.ml.

When I execute any of the targets, e.g. make clean, make byte, etc., I receive the error message:

make: *** No rule to make target 'ocamlfind', needed by 'check'.
  Stop.

or

make: *** No rule to make target 'ocamlbuild', needed by 'byte'.
  Stop.

I'd appreciate help in understanding the cause of and solution to this error. Thanks.

答:
This line:

```<code>clean: $(OCB) -clean
</code>```

Means that clean has two dependencies, $(OCB) and -clean. So it tries to build ocamlbuild first.

You want this, as in the linked makefile:

```<code>clean:
        $(OCB) -clean
</code>```

This means that clean has no dependencies, and is "done" by running $(OCB) -clean.

Note that you need an actual tab character before the $ character, not 8 spaces.

Title: OCaml Makefile: No Rule to Make Target

Body:
I'm following this OCamlbuild example, and accordingly have created the Makefile below:

OCB_FLAGS = -use-ocamlfind -I src -I lib
OCB = ocamlbuild $(OCB_FLAGS)

check: ocamlfind query core async
clean: $(OCB) -clean
byte: $(OCB) main.byte
native: $(OCB) main.native

.PHONY: check clean byte native

The root directory contains two sub-directories, src and lib. The src sub-directory contains the file main.ml.

When I execute any of the targets, e.g. make clean, make byte, etc., I receive the error message:

make: *** No rule to make target 'ocamlfind', needed by 'check'.
  Stop.

or

make: *** No rule to make target 'ocamlbuild', needed by 'byte'.
  Stop.

I'd appreciate help in understanding the cause of and solution to this error. Thanks.

Body:
This line:

clean: $(OCB) -clean

Means that clean has two dependencies, $(OCB) and -clean. So it tries to build ocamlbuild first.

You want this, as in the linked makefile:

clean:
        $(OCB) -clean

This means that clean has no dependencies, and is "done" by running $(OCB) -clean.

Note that you need an actual tab character before the $ character, not 8 spaces.


问:
how to set variable/custom id value to Html.TextBoxFor - MVC, C#, Razor
How does one give a TextBoxFor a variable ID value?

Example Attempt:

```<code> @var variable = model.codeOne;

<div>
@Html.TextBoxFor(item => item.OperationNo, new { id = "@("materialCostInput"+
variable)" })
</div>
</code>```

I have looked around the forum for an answer to this question, but have yet to find a similar question.

答:
This is a more complete answer:

```<code>public class SuperModel
{
    public string OperationNo { get; set; }

}

//Create an edmx to your table
public class HomeController : Controller
{
    [HttpPost]
    public ActionResult Index2003(SuperModel sm, FormCollection formCollection)
    {
        var theId = formCollection.Keys[0];
        return View();
    }

    public ActionResult Index2003()
    {
        SuperModel sm = new SuperModel { OperationNo = "op1" };
        return View(sm);
    }
</code>```

Controller:

```<code>@model Testy20161006.Controllers.SuperModel
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index2003</title>
</head>
<body>
    <div>
        @using (Html.BeginForm())
        {
            var variable = "456";
            @Html.TextBoxFor(item => item.OperationNo, new { Name = "materialCostInput" + variable })
            <input type="submit" value="submit" />
        }
    </div>
</body>
</html>
</code>```

Body:
How does one give a TextBoxFor a variable ID value?

Example Attempt:

 @var variable = model.codeOne;

@Html.TextBoxFor(item => item.OperationNo, new { id = "@("materialCostInput"+
variable)" })

I have looked around the forum for an answer to this question, but have yet to find a similar question.

Body:
This is a more complete answer:

public class SuperModel
{
    public string OperationNo { get; set; }

}

//Create an edmx to your table
public class HomeController : Controller
{
    [HttpPost]
    public ActionResult Index2003(SuperModel sm, FormCollection formCollection)
    {
        var theId = formCollection.Keys[0];
        return View();
    }

    public ActionResult Index2003()
    {
        SuperModel sm = new SuperModel { OperationNo = "op1" };
        return View(sm);
    }

Controller:

@model Testy20161006.Controllers.SuperModel
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index2003</title>
</head>
<body>
    <div>
        @using (Html.BeginForm())
        {
            var variable = "456";
            @Html.TextBoxFor(item => item.OperationNo, new { Name = "materialCostInput" + variable })
            <input type="submit" value="submit" />
        }
    </div>
</body>
</html>


问:
matlab contour data for 2D normal cumulative probability density
I have this 2D normal distribution defined as

```<code>mu = [0 0];
Sigma = [1 0.5^0.5; 0.5^0.5 1];
</code>```

Is there a way to get the contour data when the cumulative probability say is 95%. I do not want the plot but the value of the (x,y) points that results in 95% contour.

It would be very kind if someone can help. Thanks in advance

答:
You can use a numerical solver to find the contour as follows:

```<code>% plot the distribution
figure;
x = (-5:0.5:5)';
y = (-5:0.5:5)';
[X1,X2] = meshgrid(x',y');
X = [X1(:) X2(:)];
p = mvncdf(X,mu,Sigma);
X3 = reshape(p,length(x),length(y));
surf(X1,X2,X3);

x = (-5:0.1:5)'; % define the x samples at which the contour should be calculated
y0 = zeros(size(x)); % initial guess
y = fsolve(@(y) mvncdf([x y], mu, Sigma) - 0.95, y0); % solve your problem
z = mvncdf([x y],mu,Sigma); % calculate the correspond cdf values
hold on
plot3(x(z>0.94), y(z>0.94), z(z>0.94), 'LineWidth', 5); % plot only the valid solutions, i.e. a solution does not exist for all sample points of x.
</code>```

To obtain a better numerical representation of the desired contour, you can repeat the above approach for chosen y values. So, your line will better fill the whole graph.

As an alternative, one may use contour to calculate the points on the contour as follows:

```<code>figure
[c, h] = contour(X1, X2, X3, [0.95 0.95]);
c(3, :) = mvncdf(c',mu,Sigma);

figure(1)
plot3(c(1, :)', c(2, :)', c(3, :)', 'LineWidth', 5);
xlim([-5 5])
ylim([-5 5])
</code>```

A disadvantage of this approach is that you do not have control over the coarseness of the sampled contour. Secondly, this method uses (interpolation of) the 3D cdf, which is less accurate than the values calculated with fsolve.

Body:
I have this 2D normal distribution defined as

mu = [0 0];
Sigma = [1 0.5^0.5; 0.5^0.5 1];

Is there a way to get the contour data when the cumulative probability say is 95%. I do not want the plot but the value of the (x,y) points that results in 95% contour.

It would be very kind if someone can help. Thanks in advance

Body:
You can use a numerical solver to find the contour as follows:

% plot the distribution
figure;
x = (-5:0.5:5)';
y = (-5:0.5:5)';
[X1,X2] = meshgrid(x',y');
X = [X1(:) X2(:)];
p = mvncdf(X,mu,Sigma);
X3 = reshape(p,length(x),length(y));
surf(X1,X2,X3);

x = (-5:0.1:5)'; % define the x samples at which the contour should be calculated
y0 = zeros(size(x)); % initial guess
y = fsolve(@(y) mvncdf([x y], mu, Sigma) - 0.95, y0); % solve your problem
z = mvncdf([x y],mu,Sigma); % calculate the correspond cdf values
hold on
plot3(x(z>0.94), y(z>0.94), z(z>0.94), 'LineWidth', 5); % plot only the valid solutions, i.e. a solution does not exist for all sample points of x.

To obtain a better numerical representation of the desired contour, you can repeat the above approach for chosen y values. So, your line will better fill the whole graph.

As an alternative, one may use contour to calculate the points on the contour as follows:

figure
[c, h] = contour(X1, X2, X3, [0.95 0.95]);
c(3, :) = mvncdf(c',mu,Sigma);

figure(1)
plot3(c(1, :)', c(2, :)', c(3, :)', 'LineWidth', 5);
xlim([-5 5])
ylim([-5 5])

A disadvantage of this approach is that you do not have control over the coarseness of the sampled contour. Secondly, this method uses (interpolation of) the 3D cdf, which is less accurate than the values calculated with fsolve.


问:
Getting Events per Month using BigQuery within resource limitations
I've got Google Analytics exporting it's data to Big Query. It's now got ca. 14 months of data, containing ca. 430m Events. I want to run a query to get the total number of Events per month (e.g. 201701, 201702, etc.).

I wrote a query, but it will only run on a interval of ca. 4 - 6 days. If I make it larger I get the 'Resources exceeded during query execution.' message. Below is my query. Where did I go wrong in formulating this query? Or should I approach this completely differently (just a beginner...)

The query:

```<code>SELECT
  MonthYear,
  EXACT_COUNT_DISTINCT(combinedVisitorId) AS EventCount,
FROM (
  SELECT
    CONCAT(fullVisitorId,"-",STRING(visitId),"-",STRING(hits.hitNumber)) AS combinedVisitorId,
    hits.eventInfo.eventCategory AS EventCategory,
    CONCAT(CAST(YEAR(SEC_TO_TIMESTAMP(visitStartTime)) AS STRING), LPAD(CAST(MONTH(SEC_TO_TIMESTAMP(visitStartTime)) AS STRING), 2, '0')) AS MonthYear,
  FROM
    TABLE_DATE_RANGE([XXX:79296192.ga_sessions_], TIMESTAMP("2016-04-01"), TIMESTAMP("2017-05-30"))
  WHERE
    hits.type="EVENT" )
GROUP BY
  MonthYear
ORDER BY
  EventCount DESC
</code>```

答:
Try something like below - it is for BigQuery Standard SQL

#standardSQL
SELECT
  YearMonth,
  COUNT(DISTINCT combinedVisitorId) AS EventCount
FROM (
  SELECT
    SUBSTR(_TABLE_SUFFIX, 1, 6) AS YearMonth,
    CONCAT(fullVisitorId,"-",STRING(visitId),"-",STRING(hits.hitNumber)) AS combinedVisitorId
  FROM `XXX.79296192.ga_sessions_*`
  WHERE _TABLE_SUFFIX BETWEEN "20160401" AND "20170530"
  AND hits.type="EVENT"
)
GROUP BY YearMonth
-- ORDER BY EventCount DESC
```

Note: I left logic for combinedVisitorId as it is assuming this is exactly the way you want to treat visitors

Also, you can combine above into one select statement (without subquery) - but I wrote it this way intentionally to emphasize approach with wildcard usage

Body:
I've got Google Analytics exporting it's data to Big Query. It's now got ca. 14 months of data, containing ca. 430m Events. I want to run a query to get the total number of Events per month (e.g. 201701, 201702, etc.).

I wrote a query, but it will only run on a interval of ca. 4 - 6 days. If I make it larger I get the 'Resources exceeded during query execution.' message. Below is my query. Where did I go wrong in formulating this query? Or should I approach this completely differently (just a beginner...)

The query:

SELECT
  MonthYear,
  EXACT_COUNT_DISTINCT(combinedVisitorId) AS EventCount,
FROM (
  SELECT
    CONCAT(fullVisitorId,"-",STRING(visitId),"-",STRING(hits.hitNumber)) AS combinedVisitorId,
    hits.eventInfo.eventCategory AS EventCategory,
    CONCAT(CAST(YEAR(SEC_TO_TIMESTAMP(visitStartTime)) AS STRING), LPAD(CAST(MONTH(SEC_TO_TIMESTAMP(visitStartTime)) AS STRING), 2, '0')) AS MonthYear,
  FROM
    TABLE_DATE_RANGE([XXX:79296192.ga_sessions_], TIMESTAMP("2016-04-01"), TIMESTAMP("2017-05-30"))
  WHERE
    hits.type="EVENT" )
GROUP BY
  MonthYear
ORDER BY
  EventCount DESC

Body:
Try something like below - it is for BigQuery Standard SQL

#standardSQL
SELECT
  YearMonth,
  COUNT(DISTINCT combinedVisitorId) AS EventCount
FROM (
  SELECT
    SUBSTR(_TABLE_SUFFIX, 1, 6) AS YearMonth,
    CONCAT(fullVisitorId,"-",STRING(visitId),"-",STRING(hits.hitNumber)) AS combinedVisitorId
  FROM `XXX.79296192.ga_sessions_*`
  WHERE _TABLE_SUFFIX BETWEEN "20160401" AND "20170530"
  AND hits.type="EVENT"
)
GROUP BY YearMonth
-- ORDER BY EventCount DESC

Note: I left logic for combinedVisitorId as it is assuming this is exactly the way you want to treat visitors

Also, you can combine above into one select statement (without subquery) - but I wrote it this way intentionally to emphasize approach with wildcard usage


问:
How to achieve ImageAlign.MiddleCenter in the overriden OnPaint method
As the subject line explains it.

I want to achieve the behaviour ImageAlign.MiddleCenter in the Image property of a Button
control in .NET

i am overriding the Button's OnPaint event.
I use e.Graphics.DrawImage(Image,oDrawRectagle);
to paint the image inside the Button control.
However this always appears on the Lefthand side of the Button.
Since the oDrawRectagle always returns the 0,0 co-ordinates for the ClientRectangle.

I want the image to be always aligned ImageAlign.MiddleCenter. How do i achieve it ?

Thanks

```<code>  protected override void  OnPaint(PaintEventArgs e)
            {
                 Graphics g = e.Graphics;

                 int iHeight;
                 int iWidth;

                 if (Image != null)
                 {
                     //newSize = MaintainAspectRatio(Image, ClientRectangle.Width, ClientRectangle.Height);
                     //iHeight = newSize.Height;
                     //iWidth = newSize.Width;
                     Rectangle ResizedRectangle = MaintainAspectRatio(Image,ClientRectangle);
                     iHeight = ResizedRectangle.Height;
                     iWidth = ResizedRectangle.Width;

                 }
                 else
                 {
                     iWidth = ClientRectangle.Width;
                     iHeight = ClientRectangle.Height;
                 }

                 g.FillRectangle(new SolidBrush(Color.FromArgb(213, 221, 224)), ClientRectangle);

                 // Draw border
                 Color oLeftTopColor = SystemColors.ControlLightLight;
                 Color oRightBottomColor = SystemColors.ActiveCaption;
                 Pen oLeftTopPen = new Pen(oLeftTopColor);
                 Pen oRightBottomPen = new Pen(oRightBottomColor);
                 // top line
                 g.DrawLine(oLeftTopPen, 0, 0, iWidth - 1, 0);
                 //g.DrawLine(new Pen(SystemColors.ControlLight), 1, 1, iWidth-2, 1);
                 // bottom line
                 g.DrawLine(oRightBottomPen, 0, iHeight, iWidth - 1, iHeight);
                 //g.DrawLine(new Pen(SystemColors.ControlDark), 1, iHeight-2, iWidth-2, iHeight-2);
                 // right line
                 g.DrawLine(oRightBottomPen, iWidth, 0, iWidth, iHeight - 1);
                 //g.DrawLine(new Pen(SystemColors.ControlDark), iWidth-2, 1, iWidth-2, iHeight-2);
                 // left line
                 g.DrawLine(oLeftTopPen, 0, 0, 0, iHeight - 1);
                 //g.DrawLine(new Pen(SystemColors.ControlLightLight), 1, 1, 1, iHeight-2);

                 // Draw image
                 if (Image != null)
                 {
                     //Rectangle oDrawRectagle = new Rectangle(
                     //   8, 5, iWidth - 20, iHeight - 10);
                     Rectangle oDrawRectagle = new Rectangle(
                        0, 0, iWidth, iHeight);
                     if (Enabled == false)
                     {
                         e.Graphics.DrawImage(Image, oDrawRectagle,
                            0, 0, Image.Width, Image.Height,
                            GraphicsUnit.Pixel);
                     }
                     else
                     {
                         e.Graphics.DrawImage(Image,oDrawRectagle);

                     }
                 }

                 // Draw text
                 if (Text != null)
                 {
                     int iTextTop = 5;
                     int iTextLeft = 5;
                     int iMaxTextWidth = iWidth - 10;
                     int iMaxTextHeight = iHeight - 10;
                 }
            }
</code>```

答:
You can just manually change the position to the center using the button size and the image size.</p>

```<code>oDrawRectangle = new Rectangle(this.Width / 2 - iWidth / 2, this.Height / 2 - iHeight / 2, iWidth, iHeight);
</code>```

Body:
As the subject line explains it.

I want to achieve the behaviour ImageAlign.MiddleCenter in the Image property of a Button
control in .NET

i am overriding the Button's OnPaint event.
I use e.Graphics.DrawImage(Image,oDrawRectagle);
to paint the image inside the Button control.
However this always appears on the Lefthand side of the Button.
Since the oDrawRectagle always returns the 0,0 co-ordinates for the ClientRectangle.

I want the image to be always aligned ImageAlign.MiddleCenter. How do i achieve it ?

Thanks

  protected override void  OnPaint(PaintEventArgs e)
            {
                 Graphics g = e.Graphics;

                 int iHeight;
                 int iWidth;

                 if (Image != null)
                 {
                     //newSize = MaintainAspectRatio(Image, ClientRectangle.Width, ClientRectangle.Height);
                     //iHeight = newSize.Height;
                     //iWidth = newSize.Width;
                     Rectangle ResizedRectangle = MaintainAspectRatio(Image,ClientRectangle);
                     iHeight = ResizedRectangle.Height;
                     iWidth = ResizedRectangle.Width;

                 }
                 else
                 {
                     iWidth = ClientRectangle.Width;
                     iHeight = ClientRectangle.Height;
                 }

                 g.FillRectangle(new SolidBrush(Color.FromArgb(213, 221, 224)), ClientRectangle);

                 // Draw border
                 Color oLeftTopColor = SystemColors.ControlLightLight;
                 Color oRightBottomColor = SystemColors.ActiveCaption;
                 Pen oLeftTopPen = new Pen(oLeftTopColor);
                 Pen oRightBottomPen = new Pen(oRightBottomColor);
                 // top line
                 g.DrawLine(oLeftTopPen, 0, 0, iWidth - 1, 0);
                 //g.DrawLine(new Pen(SystemColors.ControlLight), 1, 1, iWidth-2, 1);
                 // bottom line
                 g.DrawLine(oRightBottomPen, 0, iHeight, iWidth - 1, iHeight);
                 //g.DrawLine(new Pen(SystemColors.ControlDark), 1, iHeight-2, iWidth-2, iHeight-2);
                 // right line
                 g.DrawLine(oRightBottomPen, iWidth, 0, iWidth, iHeight - 1);
                 //g.DrawLine(new Pen(SystemColors.ControlDark), iWidth-2, 1, iWidth-2, iHeight-2);
                 // left line
                 g.DrawLine(oLeftTopPen, 0, 0, 0, iHeight - 1);
                 //g.DrawLine(new Pen(SystemColors.ControlLightLight), 1, 1, 1, iHeight-2);

                 // Draw image
                 if (Image != null)
                 {
                     //Rectangle oDrawRectagle = new Rectangle(
                     //   8, 5, iWidth - 20, iHeight - 10);
                     Rectangle oDrawRectagle = new Rectangle(
                        0, 0, iWidth, iHeight);
                     if (Enabled == false)
                     {
                         e.Graphics.DrawImage(Image, oDrawRectagle,
                            0, 0, Image.Width, Image.Height,
                            GraphicsUnit.Pixel);
                     }
                     else
                     {
                         e.Graphics.DrawImage(Image,oDrawRectagle);

                     }
                 }

                 // Draw text
                 if (Text != null)
                 {
                     int iTextTop = 5;
                     int iTextLeft = 5;
                     int iMaxTextWidth = iWidth - 10;
                     int iMaxTextHeight = iHeight - 10;
                 }
            }

Body:
You can just manually change the position to the center using the button size and the image size.

oDrawRectangle = new Rectangle(this.Width / 2 - iWidth / 2, this.Height / 2 - iHeight / 2, iWidth, iHeight);


问:
VSCode code autocomplete behavior
I noticed that VSCode uses only the files that are opened in editors (tabs) for looking up names for code auto complete. It is strange for me. To my mind the more usual behavior is to look up all files in opened folder, but not use only the opened files. Is this behavior by design ?</p>

答:
Try creating a jsconfig.json file at the root of your workspace:

```<code>{
   "exclude": [
     "node_modules"
   ]
}
</code>```

This tells VSCode to treat all JS files in your workspace as part of a single project, even if the files have not been opened yet. You can find more information about jsconfig.json files in our documentation

Title: VSCode code autocomplete behavior

Body:
Try creating a jsconfig.json file at the root of your workspace:

{
   "exclude": [
     "node_modules"
   ]
}

This tells VSCode to treat all JS files in your workspace as part of a single project, even if the files have not been opened yet. You can find more information about jsconfig.json files in our documentation


问:
Encapsulating controller logic in rails
I have 2 controllers in rails with different authentications schemes,
but they do almost the same.

What is the best way in rails to encapsulate
the logic of a controller in another class or helper?

Sample:

```<code>def ControllerA < BasicAuthController
  def create
    blablacode
  end
end

def ControllerB < TokenAuthController
  def create
    blablacode
  end
end
</code>```

Whats the proper way to do this? create a model with the code?
Create a helper? other?

答:
I do it something like this:

```<code>#app/services/my_app/services/authentication.rb
class MyApp::Services::Authentication

  class < self

    def call(params={})
      new(params).call
    end

  end # Class Methods

  #==============================================================================================
  # Instance Methods
  #==============================================================================================

    def initialize(params)
      @params = params
    end

    def call
      ... do a lot of clever stuff
      ... end by returning true or false
    end

  private

    def params() @params end

end
</code>```

Then:

```<code>class FooController < ApplicationController
  before_action :authenticate

  def authenticate
    redirect_to 'some_path' unless MyApp::Services::Authenticate.call(with: 'some_params')
  end

end
</code>```

Title: Encapsulating controller logic in rails

Body:
I have 2 controllers in rails with different authentications schemes,
but they do almost the same.

What is the best way in rails to encapsulate
the logic of a controller in another class or helper?

Sample:

def ControllerA < BasicAuthController
  def create
    blablacode
  end
end

def ControllerB < TokenAuthController
  def create
    blablacode
  end
end

Whats the proper way to do this? create a model with the code?
Create a helper? other?

Body:
I do it something like this:

#app/services/my_app/services/authentication.rb
class MyApp::Services::Authentication

  class < self

    def call(params={})
      new(params).call
    end

  end # Class Methods

  #==============================================================================================
  # Instance Methods
  #==============================================================================================

    def initialize(params)
      @params = params
    end

    def call
      ... do a lot of clever stuff
      ... end by returning true or false
    end

  private

    def params() @params end

end

Then:

class FooController < ApplicationController
  before_action :authenticate

  def authenticate
    redirect_to 'some_path' unless MyApp::Services::Authenticate.call(with: 'some_params')
  end

end


问:
R stm - Number of provided texts and number of documents modeled do not match
I'm working with textual data from abstracts and I am trying to use stm (structural topic modeling) to have a look on unsupervised extracted topics, before constructing my own dictionary (for supervised analysis).
I'm dealing with a problem and I wonder whether anyone had encountered the same issue before.
When running findThoughts() I get the following error:

Error in findThoughts(out.stm, topics = 27, texts = corpus$documents$texts,  :
    Number of provided texts and number of documents modeled do not match

I'm not sure what's wrong with my data. I thought it could have to do with NA values in those empty rows of the corpus wherein I had no abstract, but the same happens after removing NA rows (with the following:

```<code>df[!is.na(df$abstract),]
</code>```

If you have any idea on the matter, please let me know.

答:
The findThoughts function returns the error "Number of provided texts and number of documents modeled do not match" when length(texts) != number of rows of out.stm.

This is an error that orginates from the textProcessor function that is used to process the documents before calling the 'stm' function.

Here is why this happens:
The temp output has an attribute temp$docs.removed which lists the rows that were removed. So the length of 'temp$documents' will be lesser than 'comments' by length of temp$docs.removed.

So the stm object 'a' and a$theta (the matrix with topic probabilities of documents) which is modeled using temp$documents will have the same length as temp$documents.

```<code>temp<-textProcessor(comments, metadata=NULL,  lowercase=TRUE, removestopwords=TRUE, removenumbers=TRUE,  removepunctuation=TRUE, stem=TRUE, wordLengths=c(3,Inf),  sparselevel=1, language="en",  verbose=TRUE, onlycharacter= FALSE, striphtml=FALSE, customstopwords=NULL, onlytxtfiles=TRUE)

meta<-temp$meta
vocab<-temp$vocab
docs<-temp$documents
a<-stm(documents=docs, vocab=vocab, K=7,data=meta, max.em.its=800)
</code>```

Solution: Remove the documents that were removed in the 'temp' object from your 'texts' objects. The code below does that by creating a new vector z that removes the indices referenced in temp$docs.removed.

```<code>z<-comments[-temp$docs.removed,]
length(z)

thoughts3 <- findThoughts(a,texts=z,topics=3, n=10,thresh=0.0)
</code>```

Body:
I'm working with textual data from abstracts and I am trying to use stm (structural topic modeling) to have a look on unsupervised extracted topics, before constructing my own dictionary (for supervised analysis).
I'm dealing with a problem and I wonder whether anyone had encountered the same issue before.
When running findThoughts() I get the following error:

Error in findThoughts(out.stm, topics = 27, texts = corpus$documents$texts,  :
    Number of provided texts and number of documents modeled do not match

I'm not sure what's wrong with my data. I thought it could have to do with NA values in those empty rows of the corpus wherein I had no abstract, but the same happens after removing NA rows (with the following:

df[!is.na(df$abstract),]

If you have any idea on the matter, please let me know.

Body:
The findThoughts function returns the error "Number of provided texts and number of documents modeled do not match" when length(texts) != number of rows of out.stm.

This is an error that orginates from the textProcessor function that is used to process the documents before calling the 'stm' function.

Here is why this happens:
The temp output has an attribute temp$docs.removed which lists the rows that were removed. So the length of 'temp$documents' will be lesser than 'comments' by length of temp$docs.removed.

So the stm object 'a' and a$theta (the matrix with topic probabilities of documents) which is modeled using temp$documents will have the same length as temp$documents.

temp<-textProcessor(comments, metadata=NULL,  lowercase=TRUE, removestopwords=TRUE, removenumbers=TRUE,  removepunctuation=TRUE, stem=TRUE, wordLengths=c(3,Inf),  sparselevel=1, language="en",  verbose=TRUE, onlycharacter= FALSE, striphtml=FALSE, customstopwords=NULL, onlytxtfiles=TRUE)

meta<-temp$meta
vocab<-temp$vocab
docs<-temp$documents
a<-stm(documents=docs, vocab=vocab, K=7,data=meta, max.em.its=800)

Solution: Remove the documents that were removed in the 'temp' object from your 'texts' objects. The code below does that by creating a new vector z that removes the indices referenced in temp$docs.removed.

z<-comments[-temp$docs.removed,]
length(z)

thoughts3 <- findThoughts(a,texts=z,topics=3, n=10,thresh=0.0)


问:
How do I prevent replay attacks?
This is related to another question I asked. In summary, I have a special case of a URL where, when a form is POSTed to it, I can't rely on cookies for authentication or to maintain the user's session, but I somehow need to know who they are, and I need to know they're logged in!

I think I came up with a solution to my problem, but it needs fleshing out. Here's what I'm thinking. I create a hidden form field called "username", and place within it the user's username, encrypted. Then, when the form POSTs, even though I don't receive any cookies from the browser, I know they're logged in because I can decrypt the hidden form  field and get the username.

The major security flaw I can see is replay attacks. How do I prevent someone from getting ahold of that encrypted string, and POSTing as that user? I know I can use SSL to make it harder to steal that string, and maybe I can rotate the encryption key on a regular basis to limit the amount of time that the string is good for, but I'd really like to find a bulletproof solution. Anybody have any ideas? Does the ASP.Net ViewState prevent replay? If so, how do they do it?

Edit: I'm hoping for a solution that doesn't require anything stored in a database. Application state would be okay, except that it won't survive an IIS restart or work at all in a web farm or garden scenario. I'm accepting Chris's answer, for now, because I'm not convinced it's even possible to secure this without a database. But if someone comes up with an answer that does not involve the database, I'll accept it!

答: You could use some kind of random challenge string that's used along with the username to create the hash.  If you store the challenge string on the server in a database you can then ensure that it's only used once, and only for one particular user.</p>

OwnerDisplayName: Josh Hinman

Title: How do I prevent replay attacks?

LastEditorDisplayName: Josh Hinman

OwnerDisplayName: catlee


问:
Why can't enum's constructor access static fields?
Why can't enum's constructor access static fields and methods? This is perfectly valid with a class, but is not allowed with an enum.

What I'm trying to do is store my enum instances in a static Map. Consider this example code which allows lookup by abbreivation:

```<code>public enum Day {
    Sunday("Sun"), Monday("Mon"), Tuesday("Tue"), Wednesday("Wed"), Thursday("Thu"), Friday("Fri"), Saturday("Sat");

    private final String abbreviation;

    private static final Map<String, Day> ABBREV_MAP = new HashMap<String, Day>();

    private Day(String abbreviation) {
        this.abbreviation = abbreviation;
        ABBREV_MAP.put(abbreviation, this);  // Not valid
    }

    public String getAbbreviation() {
        return abbreviation;
    }

    public static Day getByAbbreviation(String abbreviation) {
        return ABBREV_MAP.get(abbreviation);
    }
}
</code>```

This will not work as enum doesn't allow static references in its constructor. It however works just find if implemented as a class:

```<code>public static final Day SUNDAY = new Day("Sunday", "Sun");
private Day(String name, String abbreviation) {
    this.name = name;
    this.abbreviation = abbreviation;
    ABBREV_MAP.put(abbreviation, this);  // Valid
}
</code>```

答:
The constructor is called before the static fields have all been initialized, because the static fields (including those representing the enum values) are initialized in textual order, and the enum values always come before the other fields. Note that in your class example you haven't shown where ABBREV_MAP is initialized - if it's after SUNDAY, you'll get an exception when the class is initialized.

Yes, it's a bit of a pain and could probably have been designed better.

However, the usual answer in my experience is to have a static {} block at the end of all the static initializers, and do all static initialization there, using EnumSet.allOf  to get at all the values.

OwnerDisplayName: Steve Kuo

Body:
Why can't enum's constructor access static fields and methods? This is perfectly valid with a class, but is not allowed with an enum.

What I'm trying to do is store my enum instances in a static Map. Consider this example code which allows lookup by abbreivation:

public enum Day {
    Sunday("Sun"), Monday("Mon"), Tuesday("Tue"), Wednesday("Wed"), Thursday("Thu"), Friday("Fri"), Saturday("Sat");

    private final String abbreviation;

    private static final Map<String, Day> ABBREV_MAP = new HashMap<String, Day>();

    private Day(String abbreviation) {
        this.abbreviation = abbreviation;
        ABBREV_MAP.put(abbreviation, this);  // Not valid
    }

    public String getAbbreviation() {
        return abbreviation;
    }

    public static Day getByAbbreviation(String abbreviation) {
        return ABBREV_MAP.get(abbreviation);
    }
}

This will not work as enum doesn't allow static references in its constructor. It however works just find if implemented as a class:

public static final Day SUNDAY = new Day("Sunday", "Sun");
private Day(String name, String abbreviation) {
    this.name = name;
    this.abbreviation = abbreviation;
    ABBREV_MAP.put(abbreviation, this);  // Valid
}

OwnerDisplayName: Jon Skeet


答:
Why don't you enable both schemes for a single controller? Especially if the only difference is Authentication. You could have two app/controllers/concerns to encapsulate both authentication methods and include Auth1 and include Auth2 for a single controller who is only responsible for whatever resource it manages.

Otherwise, services are the best approach to encapsulate controller logic.

Create a folder called services in your app folder and write PORO classes here. Say you have a few places in your app where you want to pay for stuff via make Stripe.

```<code># app/services/stripe_service.rb
module StripeService
  def customer(args)
    ...
  end

  def pay(amount, customer)
    ...
  end

  def reverse(stripe_txn_id)
    ...
  end
end
# controller
StripeService.customer(data)
=> <#Stripe::Customer>
</code>```

Or if you only need to do one thing.

```<code># app/services/some_thing.rb
module SomeThing
  def call
    # do stuff
  end
end
# controller
SomeThing.call
=> # w/e
</code>```

If you need an object with multiple reponsibilities you could create a class instead.

```<code>class ReportingService
  def initialize(args)
    ...
  end

  def query
    ...
  end

  def data
    ...
  end

  def to_json
    ...
  end
end
</code>```

https://blog.engineyard.com/2014/keeping-your-rails-controllers-dry-with-services

Title: Encapsulating controller logic in rails

Body:
Why don't you enable both schemes for a single controller? Especially if the only difference is Authentication. You could have two app/controllers/concerns to encapsulate both authentication methods and include Auth1 and include Auth2 for a single controller who is only responsible for whatever resource it manages.

Otherwise, services are the best approach to encapsulate controller logic.

Create a folder called services in your app folder and write PORO classes here. Say you have a few places in your app where you want to pay for stuff via make Stripe.

# app/services/stripe_service.rb
module StripeService
  def customer(args)
    ...
  end

  def pay(amount, customer)
    ...
  end

  def reverse(stripe_txn_id)
    ...
  end
end
# controller
StripeService.customer(data)
=> <#Stripe::Customer>

Or if you only need to do one thing.

# app/services/some_thing.rb
module SomeThing
  def call
    # do stuff
  end
end
# controller
SomeThing.call
=> # w/e

If you need an object with multiple reponsibilities you could create a class instead.

class ReportingService
  def initialize(args)
    ...
  end

  def query
    ...
  end

  def data
    ...
  end

  def to_json
    ...
  end
end

https://blog.engineyard.com/2014/keeping-your-rails-controllers-dry-with-services


问:
LNK2019 error in VS6.0 -> VS2013 migrated MFC DLL project
I get the following link error when attempting to build/port a LARGE VS6.0 DLL project to VS2013 where DLL modules are dependent on other DLL modules. The unique thing about the undefined function is that it takes CString arguments, but perhaps the problem is more obvious than that:

```<code>error LNK2019: unresolved external symbol "__declspec(dllimport) public: void __thiscall CTokenEx::Split(class ATL::CStringT<char,class StrTraitMFC_DLL<char,class ATL::ChTraitsCRT<char> > >,class ATL::CStringT<char,class StrTraitMFC_DLL<char,class ATL::ChTraitsCRT<char> > >,class CStringArray &,int)" (__imp_?Split@CTokenEx@@QAEXV?$CStringT@DV?$StrTraitMFC_DLL@DV?$ChTraitsCRT@D@ATL@@@@@ATL@@0AAVCStringArray@@H@Z) referenced in function "public: bool __thiscall OptionFlag::isTestEnableByFlag(class ATL::CStringT<char,class StrTraitMFC_DLL<char,class ATL::ChTraitsCRT<char> > >)" (?isTestEnableByFlag@OptionFlag@@QAE_NV?$CStringT@DV?$StrTraitMFC_DLL@DV?$ChTraitsCRT@D@ATL@@@@@ATL@@@Z)
</code>```

Here is the dumpbin.exe for this module where the symbol is exported (from the *.exp file):

```<code> 00000148  DIR32NB                    00000000        20  $N00027
 00000094  DIR32NB                    00000000        4F  ?Split@CTokenEx@@QAEXV?$CStringT@DV?$StrTraitMFC_DLL@DV?$ChTraitsCRT@D@ATL@@@@@ATL@@0AAVCStringArray@@H@Z (public: void __thiscall CTokenEx::Split(class ATL::CStringT<char,class StrTraitMFC_DLL<char,class ATL::ChTraitsCRT<char> > >,class ATL::CStringT<char,class StrTraitMFC_DLL<char,class ATL::ChTraitsCRT<char> > >,class CStringArray &,int))
 0000014C  DIR32NB                    00000000        21  $N00028
</code>```

Here is the dump from the *.lib file and I see __imp_ in the *.lib file.

```<code>     3E30 ?Split@CTokenEx@@QAEXV?$CStringT@DV?$StrTraitMFC_DLL@DV?$ChTraitsCRT@D@ATL@@@@@ATL@@0AAVCStringArray@@H@Z
     3E30 __imp_?Split@CTokenEx@@QAEXV?$CStringT@DV?$StrTraitMFC_DLL@DV?$ChTraitsCRT@D@ATL@@@@@ATL@@0AAVCStringArray@@H@Z
</code>```

Of course I need to triple check again that I'm reading this exact .exp/.lib which is what /Verbose tells me.

In this particular case, all the issue(s) I have are cases where DLL "x" references a function in DLL "y" which has a CTokenEx::Split() function which has CString arguments.  I thought that the problem was the CSTring MFC vs ATL declaration (see links below), now I'm not so sure, so am going back to square one after posting this here. (i.e. is it a typo I missed? DOH?)

I've done the following to isolate the problem
Build properties:

Verified all modules are using MBCS (Multi Byte Char Set) not Unicode

Verified all modules are building with "Using MFC in a DLL"

Run the linker with /Verbose and Verbose:lib to verify the linker was referencing the linked file I expected.

Used dumpbin.exe to examine the exported symbol decorations to see if they are getting exported. (I think they are, but I'm not a dumpbin expert).

Found these possibly related links:

MSDN LNK2019 error and attempted to hardcode the dllimport of the CString type.

link with respect to MFC and CRT CSTring definitions. Not 100% sure this is the issue. (could be something I'm missing in the arguments.)

included "afxstr.h", and forced -D"_MFC_DLL_BLD"

The CTokenEx portion of the DLL module I'm working with appears to be from here but I haven't confirmed it.   At the moment, I'm not sure that is relevant.

I'm just looking for confirmation that my analysis of dumpbin.exe which tells me the symbols are exported correct is accurate.  I thought it could be a link-order issue, and referenced the DLL a second time to the linker, but that didn't help.  In a past life that worked in similar linker issues in SunOs (back in ancient times).

If I figure this one out, I will post an answer to this problem.

答:
!DOH!
After you have eliminated all other options. .
Although using /Verbose and /Verbose:lib show you where the *.lib files are, and confirms they are found, you must pay attention!
In my case, there were some VS6.0 STALE *.lib files in "." relative to the solution workspace and the linker found those first, and of course they likely didn't have the symbols properly decorated.
If the linker tells you that it linked in:

mylib.lib
instead of

path\to\Mylib.lib
it's a major clue :).

Sooo... what I thought was a complex & strange linker problem.  Was a !DOH! easy linker problem.

Problem solved, just that simple.

Body:
I get the following link error when attempting to build/port a LARGE VS6.0 DLL project to VS2013 where DLL modules are dependent on other DLL modules. The unique thing about the undefined function is that it takes CString arguments, but perhaps the problem is more obvious than that:

error LNK2019: unresolved external symbol "__declspec(dllimport) public: void __thiscall CTokenEx::Split(class ATL::CStringT<char,class StrTraitMFC_DLL<char,class ATL::ChTraitsCRT<char> > >,class ATL::CStringT<char,class StrTraitMFC_DLL<char,class ATL::ChTraitsCRT<char> > >,class CStringArray &,int)" (__imp_?Split@CTokenEx@@QAEXV?$CStringT@DV?$StrTraitMFC_DLL@DV?$ChTraitsCRT@D@ATL@@@@@ATL@@0AAVCStringArray@@H@Z) referenced in function "public: bool __thiscall OptionFlag::isTestEnableByFlag(class ATL::CStringT<char,class StrTraitMFC_DLL<char,class ATL::ChTraitsCRT<char> > >)" (?isTestEnableByFlag@OptionFlag@@QAE_NV?$CStringT@DV?$StrTraitMFC_DLL@DV?$ChTraitsCRT@D@ATL@@@@@ATL@@@Z)

Here is the dumpbin.exe for this module where the symbol is exported (from the *.exp file):

 00000148  DIR32NB                    00000000        20  $N00027
 00000094  DIR32NB                    00000000        4F  ?Split@CTokenEx@@QAEXV?$CStringT@DV?$StrTraitMFC_DLL@DV?$ChTraitsCRT@D@ATL@@@@@ATL@@0AAVCStringArray@@H@Z (public: void __thiscall CTokenEx::Split(class ATL::CStringT<char,class StrTraitMFC_DLL<char,class ATL::ChTraitsCRT<char> > >,class ATL::CStringT<char,class StrTraitMFC_DLL<char,class ATL::ChTraitsCRT<char> > >,class CStringArray &,int))
 0000014C  DIR32NB                    00000000        21  $N00028

Here is the dump from the *.lib file and I see __imp_ in the *.lib file.

     3E30 ?Split@CTokenEx@@QAEXV?$CStringT@DV?$StrTraitMFC_DLL@DV?$ChTraitsCRT@D@ATL@@@@@ATL@@0AAVCStringArray@@H@Z
     3E30 __imp_?Split@CTokenEx@@QAEXV?$CStringT@DV?$StrTraitMFC_DLL@DV?$ChTraitsCRT@D@ATL@@@@@ATL@@0AAVCStringArray@@H@Z

Of course I need to triple check again that I'm reading this exact .exp/.lib which is what /Verbose tells me.

In this particular case, all the issue(s) I have are cases where DLL "x" references a function in DLL "y" which has a CTokenEx::Split() function which has CString arguments.  I thought that the problem was the CSTring MFC vs ATL declaration (see links below), now I'm not so sure, so am going back to square one after posting this here. (i.e. is it a typo I missed? DOH?)

I've done the following to isolate the problem
Build properties:

Verified all modules are using MBCS (Multi Byte Char Set) not Unicode

Verified all modules are building with "Using MFC in a DLL"

Run the linker with /Verbose and Verbose:lib to verify the linker was referencing the linked file I expected.

Used dumpbin.exe to examine the exported symbol decorations to see if they are getting exported. (I think they are, but I'm not a dumpbin expert).

Found these possibly related links:

MSDN LNK2019 error and attempted to hardcode the dllimport of the CString type.

link with respect to MFC and CRT CSTring definitions. Not 100% sure this is the issue. (could be something I'm missing in the arguments.)

included "afxstr.h", and forced -D"_MFC_DLL_BLD"

The CTokenEx portion of the DLL module I'm working with appears to be from here but I haven't confirmed it.   At the moment, I'm not sure that is relevant.

I'm just looking for confirmation that my analysis of dumpbin.exe which tells me the symbols are exported correct is accurate.  I thought it could be a link-order issue, and referenced the DLL a second time to the linker, but that didn't help.  In a past life that worked in similar linker issues in SunOs (back in ancient times).

If I figure this one out, I will post an answer to this problem.