问:
Webview doesn't work?
I want to pass URL string from main activity to second activity and load the URL in second activity.... but when I click the go button at mainactivity it goes to second activity but it shows nothing but blank.

here is my code ..

MainActivity:-

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

EditText editText;
Button go;

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

    editText=findViewById(R.id.urltext);
    go=findViewById(R.id.button6);

    final String link=go.getText().toString();

    go.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getApplicationContext(),Webview.class);
            intent.putExtra(link,1);
            startActivity(intent);

        }
    });

}

}
</code>```

Second activity:

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

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

    String one = getIntent().getExtras().getString("1");
    String http="https://";
    String url=http+one;

    WebView webView = (WebView)findViewById(R.id.webview);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.loadUrl(url);
}
}
</code>```

答:
No offence but you must have read the documentation first .

intent.putExtra(key,value);

Key should be constant in case of getting value from the same key in other component.So the answer is your OnClick shold be like below.

```<code>final String link=go.getText().toString();

go.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Intent intent = new Intent(YourActivity.this,Webview.class);
        intent.putExtra("link",link);
        startActivity(intent);

    }
});
</code>```

Getting url from intent in other activity.

```<code> String one = getIntent().getExtras().getString("link");
String http="https://";
String url=http+one;// Use this url to open in web view
</code>```

Title: Webview doesn't work?

Body:
I want to pass URL string from main activity to second activity and load the URL in second activity.... but when I click the go button at mainactivity it goes to second activity but it shows nothing but blank.

here is my code ..

MainActivity:-

public class MainActivity extends AppCompatActivity {

EditText editText;
Button go;

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

    editText=findViewById(R.id.urltext);
    go=findViewById(R.id.button6);

    final String link=go.getText().toString();

    go.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getApplicationContext(),Webview.class);
            intent.putExtra(link,1);
            startActivity(intent);

        }
    });

}

}

Second activity:

public class Webview extends AppCompatActivity {

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

    String one = getIntent().getExtras().getString("1");
    String http="https://";
    String url=http+one;

    WebView webView = (WebView)findViewById(R.id.webview);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.loadUrl(url);
}
}

Body:
No offence but you must have read the documentation first .

intent.putExtra(key,value);

Key should be constant in case of getting value from the same key in other component.So the answer is your OnClick shold be like below.

final String link=go.getText().toString();

go.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Intent intent = new Intent(YourActivity.this,Webview.class);
        intent.putExtra("link",link);
        startActivity(intent);

    }
});

Getting url from intent in other activity.

 String one = getIntent().getExtras().getString("link");
String http="https://";
String url=http+one;// Use this url to open in web view


来源: stackexchange

问:
preg replace everything BUT digits over 5 in length
I have a string:

3 pk. Ready-Dough White Loaves Included $3.99 - 47500 - 00892, 48101

I want to keep only groups of digits longer than 5 characters, and if possible, any dashes or commas between them.

e.g.

47500-00892,48101

My first step was to strip out groups of digits < 4:

preg_replace('/\d{1,4}/', '', $string);

My thinking was "replace any block of digits from 1 to 4 with nothing", but that doesn't do exactly what I thought. Maybe I'm just missing an operator?

Then I was going to strip out all letters and all punctuation except , and -. In my example I would've been left with a starting - because of it being in a string, but a trim() would've been fine to clean that up.

Any help is appreciated!

答:
Had I been patient for 5 more minutes, I would've found the answer: \b

For some reason, working with digits didn't trigger that I needed to use 'word boundaries'.

```<code>$string = preg_replace('/\b\d{1,4}\b/', '', $string);
$string = preg_replace('/[^0-9-,]/', '', $string);
$string = trim($string, ',-');
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Had I been patient for 5 more minutes, I would've found the answer: \b

For some reason, working with digits didn't trigger that I needed to use 'word boundaries'.

$string = preg_replace('/\b\d{1,4}\b/', '', $string);
$string = preg_replace('/[^0-9-,]/', '', $string);
$string = trim($string, ',-');


问:
Reduce run time for DTW distance function
I want to compute DTW distance between columns of a data matrix. But current implementation takes terribly long time. Is there any other implementation of dtw which takes less time?

Here is the dummy data:

```<code>df <- data.frame(d1= rnorm(1500,10,5),d2= rnorm(1500,130,10),d3= rnorm(1500,200,10),d4= rnorm(1500,120,15),d5= rnorm(1500,700,25),d6= rnorm(1500,6,2),d7= rnorm(1500,760,15),d8= rnorm(1500,3000,08),d9= rnorm(1500,490,15),d10= rnorm(1500,321,21))
</code>```

This function returns distance matrix using DTWDistance() function:

```<code>compute_dtw_distance_matrix  <- function(data_mat){
  library(TSdist) # for DTWDistance function
  cols = dim(data_mat)[2] # no. of columns or features
  dis_mat = matrix(0,nrow=cols,ncol=cols) # create result matrix
  # Here, I will compute only lower triangular matrix, later I will copy values to full matrix.
  # compute only lower traingular matrix
  for(row in 1:cols){
    ref_col = data_mat[,row]
    for(col in 1:row){
      comp_col = data_mat[,col]
      dis_mat[row,col] = DTWDistance(ref_col, comp_col)
    }
  }
  # convert lower_triangular to full_symmetric matrix
  for(i in 1:NROW(dis_mat)){
    for(j in 1:NCOL(dis_mat)){
      dis_mat[i,j] = dis_mat[j,i]
    }
  }
  colnames(dis_mat) <- colnames(data_mat)
  row.names(dis_mat) <- colnames(data_mat)
  return(dis_mat)
}
</code>```

Here are the running time statistic of this function on my machine:

```<code> system.time(compute_dtw_distance_matrix(df))
       user  system elapsed
     21.500   3.049  24.723
</code>```

Is it possible to reduce the running time of this function?

答:
You could use the parallelDist package which supports the parallel calculation of multi-dimensional Dynamic Time Warping distances.

The parDist function currently takes a list of matrices as an input argument for processing multi-dimensional data sets.

```<code>matrices.list <- lapply(as.list(df), function(x) t(as.matrix(x)))
</code>```

parDist produces the same output in ~ 0.5s with 8 threads compared to 18.44s with the compute_dtw_distance_matrix function, using the following arguments:

```<code>res1 <- compute_dtw_distance_matrix(df)
res2 <- parDist(matrices.list, method = "dtw", step.pattern="symmetric2", window.type="none", upper = T, diag = T, threads = 8)
all.equal(as.matrix(res1), as.matrix(res2))
</code>```

Here is a microbenchmark which includes different number of threads.

```<code>    expr        min         lq
                                                                                compute_dtw_distance_matrix(df) 17.9424328 18.1571842
 parDist(matrices.list, method = "dtw", step.pattern = "symmetric2",      window.type = "none", upper = T, diag = T, threads = 8)  0.5280135  0.5434037
 parDist(matrices.list, method = "dtw", step.pattern = "symmetric2",      window.type = "none", upper = T, diag = T, threads = 4)  0.6869948  0.6999783
 parDist(matrices.list, method = "dtw", step.pattern = "symmetric2",      window.type = "none", upper = T, diag = T, threads = 2)  1.0311007  1.0646326
 parDist(matrices.list, method = "dtw", step.pattern = "symmetric2",      window.type = "none", upper = T, diag = T, threads = 1)  1.6967269  1.7057925
       mean     median         uq        max neval
 18.4489183 18.4901471 18.6747947 18.9852819    10
  0.5547146  0.5568046  0.5657859  0.5727592    10
  0.7266116  0.7276621  0.7446920  0.7597008    10
  1.0796176  1.0742217  1.0812031  1.1792582    10
  1.7358018  1.7148310  1.7695766  1.8238875    10
</code>```

Body:
I want to compute DTW distance between columns of a data matrix. But current implementation takes terribly long time. Is there any other implementation of dtw which takes less time?

Here is the dummy data:

df <- data.frame(d1= rnorm(1500,10,5),d2= rnorm(1500,130,10),d3= rnorm(1500,200,10),d4= rnorm(1500,120,15),d5= rnorm(1500,700,25),d6= rnorm(1500,6,2),d7= rnorm(1500,760,15),d8= rnorm(1500,3000,08),d9= rnorm(1500,490,15),d10= rnorm(1500,321,21))

This function returns distance matrix using DTWDistance() function:

compute_dtw_distance_matrix  <- function(data_mat){
  library(TSdist) # for DTWDistance function
  cols = dim(data_mat)[2] # no. of columns or features
  dis_mat = matrix(0,nrow=cols,ncol=cols) # create result matrix
  # Here, I will compute only lower triangular matrix, later I will copy values to full matrix.
  # compute only lower traingular matrix
  for(row in 1:cols){
    ref_col = data_mat[,row]
    for(col in 1:row){
      comp_col = data_mat[,col]
      dis_mat[row,col] = DTWDistance(ref_col, comp_col)
    }
  }
  # convert lower_triangular to full_symmetric matrix
  for(i in 1:NROW(dis_mat)){
    for(j in 1:NCOL(dis_mat)){
      dis_mat[i,j] = dis_mat[j,i]
    }
  }
  colnames(dis_mat) <- colnames(data_mat)
  row.names(dis_mat) <- colnames(data_mat)
  return(dis_mat)
}

Here are the running time statistic of this function on my machine:

 system.time(compute_dtw_distance_matrix(df))
       user  system elapsed
     21.500   3.049  24.723

Is it possible to reduce the running time of this function?

Body:
You could use the parallelDist package which supports the parallel calculation of multi-dimensional Dynamic Time Warping distances.

The parDist function currently takes a list of matrices as an input argument for processing multi-dimensional data sets.

matrices.list <- lapply(as.list(df), function(x) t(as.matrix(x)))

parDist produces the same output in ~ 0.5s with 8 threads compared to 18.44s with the compute_dtw_distance_matrix function, using the following arguments:

res1 <- compute_dtw_distance_matrix(df)
res2 <- parDist(matrices.list, method = "dtw", step.pattern="symmetric2", window.type="none", upper = T, diag = T, threads = 8)
all.equal(as.matrix(res1), as.matrix(res2))

Here is a microbenchmark which includes different number of threads.

    expr        min         lq
                                                                                compute_dtw_distance_matrix(df) 17.9424328 18.1571842
 parDist(matrices.list, method = "dtw", step.pattern = "symmetric2",      window.type = "none", upper = T, diag = T, threads = 8)  0.5280135  0.5434037
 parDist(matrices.list, method = "dtw", step.pattern = "symmetric2",      window.type = "none", upper = T, diag = T, threads = 4)  0.6869948  0.6999783
 parDist(matrices.list, method = "dtw", step.pattern = "symmetric2",      window.type = "none", upper = T, diag = T, threads = 2)  1.0311007  1.0646326
 parDist(matrices.list, method = "dtw", step.pattern = "symmetric2",      window.type = "none", upper = T, diag = T, threads = 1)  1.6967269  1.7057925
       mean     median         uq        max neval
 18.4489183 18.4901471 18.6747947 18.9852819    10
  0.5547146  0.5568046  0.5657859  0.5727592    10
  0.7266116  0.7276621  0.7446920  0.7597008    10
  1.0796176  1.0742217  1.0812031  1.1792582    10
  1.7358018  1.7148310  1.7695766  1.8238875    10


问:
Filter by sender Outlook OData web service api
I am trying to filter my Outlook 365 inbox by sender address. Looking at the OData spec I would have throught it would involve querying a complex type as such

https://outlook.office365.com/ews/odata/Me/Folders('Inbox')/Messages?$filter=From/Address eq 'some@address.com'.

Unfortunately this returns The property 'Address' is invalid.

I can confirm I can access the data

Looking a the JSON if I just query the inbox I see an e-mail

...

```<code>"From": {

    "Name": "Some One",
    "Address": "some@address.com"

},
</code>```

...

any help with the query string would be greatly appreciated

(p.s. I have dummied the address)

答:
Try this:</p>

```<code>https://outlook.office365.com/ews/odata/Me/Folders('Inbox')/Messages?$filter=From/EmailAddress/Address eq 'some@address.com'.
</code>```

Body:
I am trying to filter my Outlook 365 inbox by sender address. Looking at the OData spec I would have throught it would involve querying a complex type as such

https://outlook.office365.com/ews/odata/Me/Folders('Inbox')/Messages?$filter=From/Address eq 'some@address.com'.

Unfortunately this returns The property 'Address' is invalid.

I can confirm I can access the data

Looking a the JSON if I just query the inbox I see an e-mail

...

"From": {

    "Name": "Some One",
    "Address": "some@address.com"

},

...

any help with the query string would be greatly appreciated

(p.s. I have dummied the address)

Body:
Try this:

https://outlook.office365.com/ews/odata/Me/Folders('Inbox')/Messages?$filter=From/EmailAddress/Address eq 'some@address.com'.


问:
.net core 2 entity framework migrations not working
I'm having a problem with adding a database migration in .net core 2.0.
I'm getting the following error:

```<code>An error occurred while calling method 'BuildWebHost' on class 'Program'. Continuing without the application service provider. Error: One or more errors occurred. (Webpack dev middleware failed because of an error while loading 'aspnet-webpack'. Error was: Error: Cannot find module 'aspnet-webpack'
    at Function.Module._resolveFilename (module.js:469:15)
    at Function.Module._load (module.js:417:25)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (C:\Users\Dries\AppData\Local\Temp\quzf2u2y.rt0:83:19)
    at __webpack_require__ (C:\Users\Dries\AppData\Local\Temp\quzf2u2y.rt0:20:30)
    at createWebpackDevServer (C:\Users\Dries\AppData\Local\Temp\quzf2u2y.rt0:62:26)
    at C:\Users\Dries\AppData\Local\Temp\00o3h05d.izo:114:19
    at IncomingMessage.<anonymous> (C:\Users\Dries\AppData\Local\Temp\00o3h05d.izo:133:38)
    at emitNone (events.js:86:13)
Current directory is: D:\Projects\Jeroen Fiers\Projecten\Fiers\bin\MCD\Debug\netcoreapp2.0
)
Unable to create an object of type 'ApplicationDbContext'. Add an implementation of 'IDesignTimeDbContextFactory<ApplicationDbContext>' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time.
</code>```

My Program.cs is adjusted to the following:

```<code>public class Program{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }
    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();
}
</code>```

The strange part is that the migrations have worked before (one time).

答:
Check if you have some DB initialization code (such as a data-seeding method) in the Startup.cs file's Configure() method: in case you do, you could fix your issue by removing that code from there and move it into the Program.cs file's Main() method in the following way:

```<code>public static void Main(string[] args)
{
    // REPLACE THIS:
    // BuildWebHost(args).Run();

    // WITH THIS:
    var host = BuildWebHost(args);
    using (var scope = host.Services.CreateScope())
    {
        // Retrieve your DbContext isntance here
        var dbContext = scope.ServiceProvider.GetService<ApplicationDbContext>();

        // place your DB seeding code here
        DbSeeder.Seed(dbContext);
    }
    host.Run();

    // ref.: https://learn.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/
}

public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .Build();
</code>```

Such kind of issues are due to the fact that in EF Core 2.x they changed the behaviour of how the BuildWebHost method works: now it invokes the Configure method in the Startup.cs file, which could lead to unexpected problems if that method contains some database initialization code.

The major issue there is that such problems will most likely raise misleading exceptions whenever the seeding code runs before the first dotnet ef migrations add /  dotnet ef database update command execution – when the database doesn’t yet exist: after that, they found a valid Database and do their job without raising any exception.

For additional info, check the MS official EF Core 1.x to 2.x migration guide and also this blog post that I wrote on this topic.

Body:
I'm having a problem with adding a database migration in .net core 2.0.
I'm getting the following error:

An error occurred while calling method 'BuildWebHost' on class 'Program'. Continuing without the application service provider. Error: One or more errors occurred. (Webpack dev middleware failed because of an error while loading 'aspnet-webpack'. Error was: Error: Cannot find module 'aspnet-webpack'
    at Function.Module._resolveFilename (module.js:469:15)
    at Function.Module._load (module.js:417:25)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (C:\Users\Dries\AppData\Local\Temp\quzf2u2y.rt0:83:19)
    at __webpack_require__ (C:\Users\Dries\AppData\Local\Temp\quzf2u2y.rt0:20:30)
    at createWebpackDevServer (C:\Users\Dries\AppData\Local\Temp\quzf2u2y.rt0:62:26)
    at C:\Users\Dries\AppData\Local\Temp\00o3h05d.izo:114:19
    at IncomingMessage.<anonymous> (C:\Users\Dries\AppData\Local\Temp\00o3h05d.izo:133:38)
    at emitNone (events.js:86:13)
Current directory is: D:\Projects\Jeroen Fiers\Projecten\Fiers\bin\MCD\Debug\netcoreapp2.0
)
Unable to create an object of type 'ApplicationDbContext'. Add an implementation of 'IDesignTimeDbContextFactory<ApplicationDbContext>' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time.

My Program.cs is adjusted to the following:

public class Program{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }
    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();
}

The strange part is that the migrations have worked before (one time).

Body:
Check if you have some DB initialization code (such as a data-seeding method) in the Startup.cs file's Configure() method: in case you do, you could fix your issue by removing that code from there and move it into the Program.cs file's Main() method in the following way:

public static void Main(string[] args)
{
    // REPLACE THIS:
    // BuildWebHost(args).Run();

    // WITH THIS:
    var host = BuildWebHost(args);
    using (var scope = host.Services.CreateScope())
    {
        // Retrieve your DbContext isntance here
        var dbContext = scope.ServiceProvider.GetService<ApplicationDbContext>();

        // place your DB seeding code here
        DbSeeder.Seed(dbContext);
    }
    host.Run();

    // ref.: https://learn.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/
}

public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .Build();

Such kind of issues are due to the fact that in EF Core 2.x they changed the behaviour of how the BuildWebHost method works: now it invokes the Configure method in the Startup.cs file, which could lead to unexpected problems if that method contains some database initialization code.

The major issue there is that such problems will most likely raise misleading exceptions whenever the seeding code runs before the first dotnet ef migrations add /  dotnet ef database update command execution – when the database doesn’t yet exist: after that, they found a valid Database and do their job without raising any exception.

For additional info, check the MS official EF Core 1.x to 2.x migration guide and also this blog post that I wrote on this topic.

ContentLicense: CC BY-SA 4.0


问:
HTTP Headers w/ NSURLRequest in swift
Anybody have an idea how to configure HTTP Headers with NSURLRequest in Swift? I have authentication set up on my server and it only needs a token passed to it but I'm having trouble setting the header

my code:

```<code>func getLatestData() {
        var loggedInUsersNumber:String = SharingManager.sharedInstance.userID
        var usersDataPoint:String = StormDataPoint + loggedInUsersNumber
        activityIND.hidden = false
        activityIND.startAnimating()
        let request = NSURLRequest(URL: NSURL(string: usersDataPoint)!)
        let tokenString = SharingManager.sharedInstance.authToken
        //request.setValue("Token " + tokenString, forKey: "Authorization")
        let urlSession = NSURLSession.sharedSession()
        let task = urlSession.dataTaskWithRequest(request, completionHandler: {
            (data, response, error) -> Void in
            if let error = error {
                print(error)
                return }
</code>```

I created a property "tokenString" to be the token to pass into the header and on the next line where i commented it out. request.setvalue - I popped it in and get an error to the tune of "cannot override data type". All my searches show Objective C help. Is there a better way to try to pass a header in?

答:
Swift3 bigger example

```<code>var req: URLRequest = /* create requets */
req.setValue("Bearer Y3GzLG2x6wSXihmUGhwGFw", forHTTPHeaderField: "Authorization")
req.timeoutInterval = 10
let task = URLSession.shared.dataTask(with: req, completionHandler: { (data, response, error) in
    print("completionHandler invoked")
})
task.resume()
</code>```

Title: HTTP Headers w/ NSURLRequest in swift

Body:
Anybody have an idea how to configure HTTP Headers with NSURLRequest in Swift? I have authentication set up on my server and it only needs a token passed to it but I'm having trouble setting the header

my code:

func getLatestData() {
        var loggedInUsersNumber:String = SharingManager.sharedInstance.userID
        var usersDataPoint:String = StormDataPoint + loggedInUsersNumber
        activityIND.hidden = false
        activityIND.startAnimating()
        let request = NSURLRequest(URL: NSURL(string: usersDataPoint)!)
        let tokenString = SharingManager.sharedInstance.authToken
        //request.setValue("Token " + tokenString, forKey: "Authorization")
        let urlSession = NSURLSession.sharedSession()
        let task = urlSession.dataTaskWithRequest(request, completionHandler: {
            (data, response, error) -> Void in
            if let error = error {
                print(error)
                return }

I created a property "tokenString" to be the token to pass into the header and on the next line where i commented it out. request.setvalue - I popped it in and get an error to the tune of "cannot override data type". All my searches show Objective C help. Is there a better way to try to pass a header in?

Body:
Swift3 bigger example

var req: URLRequest = /* create requets */
req.setValue("Bearer Y3GzLG2x6wSXihmUGhwGFw", forHTTPHeaderField: "Authorization")
req.timeoutInterval = 10
let task = URLSession.shared.dataTask(with: req, completionHandler: { (data, response, error) in
    print("completionHandler invoked")
})
task.resume()


问:
Send an entire web app as 1 HTTP response (html, js, css, images, ...)
Traditionally a browser will parse HTML and then send further requests to the server for all related data. This seems like inefficient to me, since it might require a large number of requests, even though my server already knows that a browser that wants to use this web application will need all of it's resources.

I know that js and css could be inlined, but that complicates server side code and img data as base64 bloats the size of the data... I'm aware as well that rendering can start before all assets are downloaded, which would potentially no longer work (depending on the implementation). I still feel that streaming an entire application in one go should be faster on slow connections than making tens of requests separately.

Ideally I would like the server to stream an entire directory into one HTTP response.

Does any model for this exist?

Does the reasoning make sense?

ps: If browser support for this is completely lacking, I'm wondering about a 2 step approach. Download a small JavaScript which downloads a compressed web app file, extracts it and plugs the resources into the page. Is anyone already doing something like this?

Update
I found one: http://blog.another-d-mention.ro/programming/read-load-files-from-zip-in-javascript/

答:
I started to research related issues in order to find the way to get best results with what seems possible without changing web standards, and I wondered about caching. If I could send the last modified date of every subresource of a page along with the initial HTML page, a browser could avoid asking if modified headers once it has loaded every resource at least once. This would in effect be better than to send all resources with the initial request, since that would be beneficial only on the first load, and detrimental on subsequent loads, since it would be better for browsers to use their cache (as Barmar pointed out).

Now it turns out that even with a web extension you can not get hold of the if-modified-since header and so you surely can't tell the browser to use the cached version instead of contacting the server.

I then found this post from Facebook on how they tried to reduce traffic by hashing their static files and giving them a 1 year expiry date. This would mean that the url garantuees the content of the file. They still saw plenty of unnecessary if-modified-since requests and they managed to convince Firefox and Chrome to change the behaviour of their reload buttons to no longer reload static resources. For Firefox this requires a new cache-control: immutable header, for Chrome it doesn't.

I then remembered that I had seen something like that before and it turns out there is a solution for this problem which is more convenient than hashing the contents of resources and serving them from a database for at least ten years. It is to just a new version number in the filename. The even more convenient solution would be to just add a version query string, but it turns out that that doesn't always work.

Admittedly, changing your filenames all the time is a nuisance, because files referencing these files also need to change. However the files don't actually need to change. If you control the server it might be as simple as writing a redirect rule to make sure that logo.vXXXX.png will be redirected to logo.png (where XXXX is the last modified timestamp in seconds since epoch)[1]. Now let your template system automatically generate the timestamp, like in wordpress' wp_enqueue_script. WordPress actually satisfies itself with the query string technique. Now you can set the expiration date to a far future and use the immutable cache header. If browsers respect the cache control, you can now safely ignore etags and if-modified-since headers, since they are now completely redundant.

This solution guarantees the browser shall never ask for cache validation and yet you shall never see a stale resource, without having to decide on the expiry date in advance.

It doesn't answer the original question here about how to avoid having to do multiple requests to fetch the resources on the same page on a clean cache, but ever after (as long as the browser cache doesn't get cleared), you're good! I suppose that's good enough for me.

[1] You can even avoid the server overhead of checking the timestamp on every resource every time a page references it by using the version number of your application. In debug mode, for development, one can use the timestamp to avoid having to bump the version on every modification of the file.


问:
Is there a way to change the root URL in python's Tornado web framework?
I have a Tornado web server with an application running on it such that when I go to:

localhost:8888/

I see my application's homepage. When I go to, for example,

localhost:8888/static/image/logo.png

localhost:8888/about

localhost:8888/contact

etc..

I get those relavant items as well.

My question is, is there a way to change the root location such that all of those URL's would replace the first part of the URL with:

localhost:8888/myApplication/

localhost:8888/myApplication/static/image/logo.png

etc...

Sorry if this is a simple question! Can't seem to find the answer.

Note that I would like a solution other than to manually change all the page routing regex's to include that prefix.

答:
If you're on Tornado 4.5+, I think you also have two options in monkeypatching tornado.routing.PathMatches.

tornado.routing.PathMatches.__init__():

Here you can prepend the original pattern with something like r/\w*. This may additionally beneficial if you also want to modify the original regex pattern to be open-ended on the right hand side (since the original version always ensures $ is at end of the regex pattern). This will ensure routing by path matching will follow Apache RewriteRule or Django router-style semantics (where you'll need to explicitly match on ^ and $ if you need more specific path matching control)

```<code>import re
import tornado.routing
from tornado.util import basestring_type

def pathmatches_init(self, path_pattern):

    if isinstance(path_pattern, basestring_type):

        # restore path regex behavior to RewriteRule semantics

        # if not path_pattern.endswith('$'):
        #    path_pattern += '$'
        # self.regex = re.compile(path_pattern)

        if not path_pattern.startswith('^'):
            path_pattern = r'/\w*' + path_pattern

        self.regex = re.compile(path_pattern)
    else:
        self.regex = path_pattern

    assert len(self.regex.groupindex) in (0, self.regex.groups), \
        ("groups in url regexes must either be all named or all "
         "positional: %r" % self.regex.pattern)

    self._path, self._group_count = self._find_groups()

tornado.routing.PathMatches.__init__ = pathmatches_init
</code>```

tornado.routing.PathMatches.match()

Instead of calling re.match() which only matches at beginning of the path, re.search() is called instead, since it will search the entire request.path for a match, and therefore match any URI prefix:

```<code>import tornado.routing

def pathmatches_match(self, request):
    # change match to search
    match = self.regex.search(request.path)
    if match is None:
        return None
    if not self.regex.groups:
        return {}

    path_args, path_kwargs = [], {}

    # Pass matched groups to the handler.  Since
    # match.groups() includes both named and
    # unnamed groups, we want to use either groups
    # or groupdict but not both.
    if self.regex.groupindex:
        path_kwargs = dict(
            (str(k), _unquote_or_none(v))
            for (k, v) in match.groupdict().items())
    else:
        path_args = [_unquote_or_none(s) for s in match.groups()]

    return dict(path_args=path_args, path_kwargs=path_kwargs)

tornado.routing.PathMatches.match = pathmatches_match
</code>```

Body:
If you're on Tornado 4.5+, I think you also have two options in monkeypatching tornado.routing.PathMatches.

tornado.routing.PathMatches.__init__():

Here you can prepend the original pattern with something like r/\w*. This may additionally beneficial if you also want to modify the original regex pattern to be open-ended on the right hand side (since the original version always ensures $ is at end of the regex pattern). This will ensure routing by path matching will follow Apache RewriteRule or Django router-style semantics (where you'll need to explicitly match on ^ and $ if you need more specific path matching control)

import re
import tornado.routing
from tornado.util import basestring_type

def pathmatches_init(self, path_pattern):

    if isinstance(path_pattern, basestring_type):

        # restore path regex behavior to RewriteRule semantics

        # if not path_pattern.endswith('$'):
        #    path_pattern += '$'
        # self.regex = re.compile(path_pattern)

        if not path_pattern.startswith('^'):
            path_pattern = r'/\w*' + path_pattern

        self.regex = re.compile(path_pattern)
    else:
        self.regex = path_pattern

    assert len(self.regex.groupindex) in (0, self.regex.groups), \
        ("groups in url regexes must either be all named or all "
         "positional: %r" % self.regex.pattern)

    self._path, self._group_count = self._find_groups()

tornado.routing.PathMatches.__init__ = pathmatches_init

tornado.routing.PathMatches.match()

Instead of calling re.match() which only matches at beginning of the path, re.search() is called instead, since it will search the entire request.path for a match, and therefore match any URI prefix:

import tornado.routing

def pathmatches_match(self, request):
    # change match to search
    match = self.regex.search(request.path)
    if match is None:
        return None
    if not self.regex.groups:
        return {}

    path_args, path_kwargs = [], {}

    # Pass matched groups to the handler.  Since
    # match.groups() includes both named and
    # unnamed groups, we want to use either groups
    # or groupdict but not both.
    if self.regex.groupindex:
        path_kwargs = dict(
            (str(k), _unquote_or_none(v))
            for (k, v) in match.groupdict().items())
    else:
        path_args = [_unquote_or_none(s) for s in match.groups()]

    return dict(path_args=path_args, path_kwargs=path_kwargs)

tornado.routing.PathMatches.match = pathmatches_match


问:
Adding static content in web config transform
I have a Web.Config file for local testing and i have a web.Release.Deploy.config transform that i want to include static content into.
I am not very familiar with web config transforms. I have added this to the web.release.deploy.config.

```<code> <system.webServer xdt:Transform="Insert">
    <staticContent>
      <mimeMap fileExtension=".nupkg" mimeType="application/zip" />
      <remove fileExtension=".woff" />
      <mimeMap fileExtension=".woff" mimeType="application/x-font-woff" />
      <mimeMap fileExtension=".woff2" mimeType="application/x-font-woff2" />
    </staticContent>
  </system.webServer>
</code>```

Should i be adding a rule to this or does the syntax look correct?

or should it look like this since the system.webserver element is not being inserted only the static content?

```<code> <staticContent xdt:Transform="Insert">
      <mimeMap fileExtension=".nupkg" mimeType="application/zip" />
      <remove fileExtension=".woff" />
      <mimeMap fileExtension=".woff" mimeType="application/x-font-woff" />
      <mimeMap fileExtension=".woff2" mimeType="application/x-font-woff2" />
    </staticContent>
</code>```

答:
I know this is old but this is how I add additional fileExtensions in my transforms:

```<code><staticContent xdt:Transform="InsertIfMissing">
  <remove fileExtension=".css"  xdt:Transform="InsertIfMissing" xdt:Locator="Match(fileExtension)" />
  <mimeMap fileExtension=".css" mimeType="text/css"  xdt:Transform="InsertIfMissing" xdt:Locator="Match(fileExtension)" />
  <remove fileExtension=".js"  xdt:Transform="InsertIfMissing" xdt:Locator="Match(fileExtension)" />
  <mimeMap fileExtension=".js" mimeType="text/javascript"  xdt:Transform="InsertIfMissing" xdt:Locator="Match(fileExtension)" />
  <remove fileExtension=".jpg"  xdt:Transform="InsertIfMissing" xdt:Locator="Match(fileExtension)" />
  <mimeMap fileExtension=".jpg" mimeType="image/jpeg"  xdt:Transform="InsertIfMissing"  xdt:Locator="Match(fileExtension)" />
  <remove fileExtension=".png"  xdt:Transform="InsertIfMissing"  xdt:Locator="Match(fileExtension)" />
  <mimeMap fileExtension=".png" mimeType="image/png"  xdt:Transform="InsertIfMissing" xdt:Locator="Match(fileExtension)" />
</staticContent>
</code>```

This works for me because my initial web.config already contained some existing values:

```<code><staticContent>
  <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="31.00:00:00" />
  <remove fileExtension=".woff" />
  <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
  <remove fileExtension=".woff2" />
  <mimeMap fileExtension=".woff2" mimeType="application/font-woff2" />
</staticContent>
</code>```

Example for @AsierVillanueva since I couldn't format in a comment:

```<code><mimeMap fileExtension=".css" mimeType="text/css"  xdt:Transform="Remove" xdt:Locator="Match(fileExtension)" />
<remove fileExtension=".css"  xdt:Transform="InsertIfMissing" xdt:Locator="Match(fileExtension)" />
<mimeMap fileExtension=".css" mimeType="text/css"  xdt:Transform="InsertIfMissing" xdt:Locator="Match(fileExtension)" />
</code>```

Body:
I have a Web.Config file for local testing and i have a web.Release.Deploy.config transform that i want to include static content into.
I am not very familiar with web config transforms. I have added this to the web.release.deploy.config.

 <system.webServer xdt:Transform="Insert">
    <staticContent>
      <mimeMap fileExtension=".nupkg" mimeType="application/zip" />
      <remove fileExtension=".woff" />
      <mimeMap fileExtension=".woff" mimeType="application/x-font-woff" />
      <mimeMap fileExtension=".woff2" mimeType="application/x-font-woff2" />
    </staticContent>
  </system.webServer>

Should i be adding a rule to this or does the syntax look correct?

or should it look like this since the system.webserver element is not being inserted only the static content?

 <staticContent xdt:Transform="Insert">
      <mimeMap fileExtension=".nupkg" mimeType="application/zip" />
      <remove fileExtension=".woff" />
      <mimeMap fileExtension=".woff" mimeType="application/x-font-woff" />
      <mimeMap fileExtension=".woff2" mimeType="application/x-font-woff2" />
    </staticContent>

Body:
I know this is old but this is how I add additional fileExtensions in my transforms:

<staticContent xdt:Transform="InsertIfMissing">
  <remove fileExtension=".css"  xdt:Transform="InsertIfMissing" xdt:Locator="Match(fileExtension)" />
  <mimeMap fileExtension=".css" mimeType="text/css"  xdt:Transform="InsertIfMissing" xdt:Locator="Match(fileExtension)" />
  <remove fileExtension=".js"  xdt:Transform="InsertIfMissing" xdt:Locator="Match(fileExtension)" />
  <mimeMap fileExtension=".js" mimeType="text/javascript"  xdt:Transform="InsertIfMissing" xdt:Locator="Match(fileExtension)" />
  <remove fileExtension=".jpg"  xdt:Transform="InsertIfMissing" xdt:Locator="Match(fileExtension)" />
  <mimeMap fileExtension=".jpg" mimeType="image/jpeg"  xdt:Transform="InsertIfMissing"  xdt:Locator="Match(fileExtension)" />
  <remove fileExtension=".png"  xdt:Transform="InsertIfMissing"  xdt:Locator="Match(fileExtension)" />
  <mimeMap fileExtension=".png" mimeType="image/png"  xdt:Transform="InsertIfMissing" xdt:Locator="Match(fileExtension)" />
</staticContent>

This works for me because my initial web.config already contained some existing values:

<staticContent>
  <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="31.00:00:00" />
  <remove fileExtension=".woff" />
  <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
  <remove fileExtension=".woff2" />
  <mimeMap fileExtension=".woff2" mimeType="application/font-woff2" />
</staticContent>

Example for @AsierVillanueva since I couldn't format in a comment:

<mimeMap fileExtension=".css" mimeType="text/css"  xdt:Transform="Remove" xdt:Locator="Match(fileExtension)" />
<remove fileExtension=".css"  xdt:Transform="InsertIfMissing" xdt:Locator="Match(fileExtension)" />
<mimeMap fileExtension=".css" mimeType="text/css"  xdt:Transform="InsertIfMissing" xdt:Locator="Match(fileExtension)" />


问:
First, Second and Third largest number from user provided integer array
In this program, size of array and array elements are taken from user.

This code passes all the cases I have tried but not able to pass, where size of array is 4 and elements are {5,5,5,2}

Here output should be 5 5 5

But I am getting 2 2 5

I am able to figure out the problem is in this part.

```<code>else if((max1 == max2 && max2 == max3 && max1 == max3) && x[i] < max2)
                {
                    max2 = x[i];
                    if(max2 < max3)
                    {
                        max3 = max2;
                    }
                }
</code>```

How can I solve this problem using array only. Don't need solution in collections.

```<code>import java.util.*;
    class ThirdLargest
    {
        public static void main(String[] args)
        {
            Scanner sc = new Scanner(System.in);
            System.out.println("Enter size for array: ");
            int size = sc.nextInt();
            int[] x = new int[size];
            for(int i = 0; i < x.length; i++)
            {
                System.out.println("Enter elements for array: ");
                x[i] = sc.nextInt();
            }
            System.out.println("Array is: ");
            for(int i = 0; i < x.length; i++)
            {
                System.out.print(x[i] +"    ");
            }
            System.out.println();
            if (x.length >= 3)
            {
                int max1 = x[0], max2 = x[0], max3 = x[0];
            for (int i = 1; i < x.length; i++)
            {
                    if(x[i] > max1)
                    {
                        max3 = max2;
                        max2 = max1;
                        max1 = x[i];
                    }
                    else if(x[i] > max2)
                    {
                        max3 = max2;
                        max2 = x[i];
                    }
                    else if (x[i] > max3)
                    {
                        max3 = x[i];
                    }
                    else if((max1 == max2 && max2 == max3 && max1 == max3) && x[i] < max2)
                    {
                        max2 = x[i];
                        if(max2 < max3)
                        {
                            max3 = max2;
                        }
                    }
                    else if(max2 == max3 && x[i] < max3)
                        {
                            max3 = x[i];
                        }
                }
            System.out.println("3rd, 2nd and 1st maximum: " + max3 +"   "+max2+"    "+max1);
            }
            else
            {
                System.out.println("Array size is short");
            }
        }
    }
</code>```

答:
The problem is that repeated integers in the array are not kept track of as unique elements.

When you look at the array x  = [5, 5, 5, 2] on paper you can see that there are three unique int elements of value 5 so the three largest should be 5, 5, 5 but the way the tests are now, when it reaches the value 2 at the end of the array, it doesn't know that max3, max2, and max1 each represent three distinct ints of value 5 for x[0], x[1], and x[2].

The problem can be seen here in this code section:

```<code>...

else if ((max1 == max2 && max2 == max3 && max1 == max3) && x[i] < max2) {
    max2 = x[i];
    if (max2 < max3) {
        max3 = max2;
    }
} else if (max2 == max3 && x[i] < max3) {
    max3 = x[i];
}

...
</code>```

It doesn't work for two reasons:

In the first if/else block, both max2 and max3 are changed so the other if/else blocks will work during future loop iterations, but the problem is that this assumes there will be a next iteration. It does not work when  the code block above is the last thing executed in the loop, e.g. [5, 5, 5, 2].

(side note) if max1, max2, and max3 are all equal, and x[i] < max2, then after the line:

```<code>max2 = x[i];
</code>```

max2 will always be less than max3 so the test if (max2 < max3) { is not needed.

The tests max1 == max2 && max2 == max3 && max1 == max3 and max2 == max3 do not handle the cases where:

max1, max2, and max3 are all equal, but each represents a different element in the array, e.g. [5, 5, 5, 2], when i = 3 in the for loop then max1 could represent x[0], max2 could represent x[1], and max3 could represent x[2] but because uniques are not kept track of, max2 and max3 are reassigned to 2 and because this is the last thing the for loop executes, the output is 2, 2, 5.

max2 and max3 are equal but each represents a different element in the array, e.g. for [7, 7, 8, 2], when i = 3 in the for loop, max2 represents x[0] and max3 represents x[1] but again, because uniques are not kept track of, max3 is reassigned to 2 and the output is 2, 7, 8 instead of 7, 7, 8.

To be clear:

If you tested the array [5, 5, 5, 5, 2] where the 2 occurs at index 4, the program would output 2, 2, 5 because of the reasons mentioned above.

If you tested the array [5, 5, 5, 2, 5] where the 2 occurs at index 3, the program would output 2, 5, 5 because there is only one 5 that appears after the 2.

If you tested the array [5, 5, 2, 5, 5] where the 2 occurs at index 2, the program would output 5, 5, 5 because there are two 5s that occur after the 2. In the end: max1, max2, and max3 all equal each other, 5.

If you tested the array [5, 5, 2, 5, 5, 3] which is just the previous array but with 3 added at the end, then the program would output 3, 3, 5 because when i = 5 in the for loop, max1, max2, and max3 all equal each other, 5, and the program assumes this is because they were all initially set to x[0].

Now that you understand why the program does not work, I believe a better way to solve this problem would be to first initialize max1, max2, and max3 to the lowest possible value using the Integer wrapper class, read about it here:

Replace

```<code>int max1 = x[0], max2 = x[0], max3 = x[0];
</code>```

with

```<code>int max1, max2, max3;
max1 = max2 = max3 = Integer.MIN_VALUE;
</code>```

then change the last for loop to begin at index 0 now instead of 1

```<code>for (int i = 0; i < x.length; i++) {
</code>```

and delete the last two if/else blocks:

```<code>else if ((max1 == max2 && max2 == max3 && max1 == max3) && x[i] < max2) {
    max2 = x[i];
    if (max2 < max3) {
        max3 = max2;
    }
} else if (max2 == max3 && x[i] < max3) {
    max3 = x[i];
}
</code>```

You were very close to solving it and only a few small changes are needed to fix the bugs.

Hope this was helpful, and cheers!

Body:
In this program, size of array and array elements are taken from user.

This code passes all the cases I have tried but not able to pass, where size of array is 4 and elements are {5,5,5,2}

Here output should be 5 5 5

But I am getting 2 2 5

I am able to figure out the problem is in this part.

else if((max1 == max2 && max2 == max3 && max1 == max3) && x[i] < max2)
                {
                    max2 = x[i];
                    if(max2 < max3)
                    {
                        max3 = max2;
                    }
                }

How can I solve this problem using array only. Don't need solution in collections.

import java.util.*;
    class ThirdLargest
    {
        public static void main(String[] args)
        {
            Scanner sc = new Scanner(System.in);
            System.out.println("Enter size for array: ");
            int size = sc.nextInt();
            int[] x = new int[size];
            for(int i = 0; i < x.length; i++)
            {
                System.out.println("Enter elements for array: ");
                x[i] = sc.nextInt();
            }
            System.out.println("Array is: ");
            for(int i = 0; i < x.length; i++)
            {
                System.out.print(x[i] +"    ");
            }
            System.out.println();
            if (x.length >= 3)
            {
                int max1 = x[0], max2 = x[0], max3 = x[0];
            for (int i = 1; i < x.length; i++)
            {
                    if(x[i] > max1)
                    {
                        max3 = max2;
                        max2 = max1;
                        max1 = x[i];
                    }
                    else if(x[i] > max2)
                    {
                        max3 = max2;
                        max2 = x[i];
                    }
                    else if (x[i] > max3)
                    {
                        max3 = x[i];
                    }
                    else if((max1 == max2 && max2 == max3 && max1 == max3) && x[i] < max2)
                    {
                        max2 = x[i];
                        if(max2 < max3)
                        {
                            max3 = max2;
                        }
                    }
                    else if(max2 == max3 && x[i] < max3)
                        {
                            max3 = x[i];
                        }
                }
            System.out.println("3rd, 2nd and 1st maximum: " + max3 +"   "+max2+"    "+max1);
            }
            else
            {
                System.out.println("Array size is short");
            }
        }
    }

Body:
The problem is that repeated integers in the array are not kept track of as unique elements.

When you look at the array x  = [5, 5, 5, 2] on paper you can see that there are three unique int elements of value 5 so the three largest should be 5, 5, 5 but the way the tests are now, when it reaches the value 2 at the end of the array, it doesn't know that max3, max2, and max1 each represent three distinct ints of value 5 for x[0], x[1], and x[2].

The problem can be seen here in this code section:

...

else if ((max1 == max2 && max2 == max3 && max1 == max3) && x[i] < max2) {
    max2 = x[i];
    if (max2 < max3) {
        max3 = max2;
    }
} else if (max2 == max3 && x[i] < max3) {
    max3 = x[i];
}

...

It doesn't work for two reasons:

In the first if/else block, both max2 and max3 are changed so the other if/else blocks will work during future loop iterations, but the problem is that this assumes there will be a next iteration. It does not work when  the code block above is the last thing executed in the loop, e.g. [5, 5, 5, 2].

(side note) if max1, max2, and max3 are all equal, and x[i] < max2, then after the line:

max2 = x[i];

max2 will always be less than max3 so the test if (max2 < max3) { is not needed.

The tests max1 == max2 && max2 == max3 && max1 == max3 and max2 == max3 do not handle the cases where:

max1, max2, and max3 are all equal, but each represents a different element in the array, e.g. [5, 5, 5, 2], when i = 3 in the for loop then max1 could represent x[0], max2 could represent x[1], and max3 could represent x[2] but because uniques are not kept track of, max2 and max3 are reassigned to 2 and because this is the last thing the for loop executes, the output is 2, 2, 5.

max2 and max3 are equal but each represents a different element in the array, e.g. for [7, 7, 8, 2], when i = 3 in the for loop, max2 represents x[0] and max3 represents x[1] but again, because uniques are not kept track of, max3 is reassigned to 2 and the output is 2, 7, 8 instead of 7, 7, 8.

To be clear:

If you tested the array [5, 5, 5, 5, 2] where the 2 occurs at index 4, the program would output 2, 2, 5 because of the reasons mentioned above.

If you tested the array [5, 5, 5, 2, 5] where the 2 occurs at index 3, the program would output 2, 5, 5 because there is only one 5 that appears after the 2.

If you tested the array [5, 5, 2, 5, 5] where the 2 occurs at index 2, the program would output 5, 5, 5 because there are two 5s that occur after the 2. In the end: max1, max2, and max3 all equal each other, 5.

If you tested the array [5, 5, 2, 5, 5, 3] which is just the previous array but with 3 added at the end, then the program would output 3, 3, 5 because when i = 5 in the for loop, max1, max2, and max3 all equal each other, 5, and the program assumes this is because they were all initially set to x[0].

Now that you understand why the program does not work, I believe a better way to solve this problem would be to first initialize max1, max2, and max3 to the lowest possible value using the Integer wrapper class, read about it here:

Replace

int max1 = x[0], max2 = x[0], max3 = x[0];

with

int max1, max2, max3;
max1 = max2 = max3 = Integer.MIN_VALUE;

then change the last for loop to begin at index 0 now instead of 1

for (int i = 0; i < x.length; i++) {

and delete the last two if/else blocks:

else if ((max1 == max2 && max2 == max3 && max1 == max3) && x[i] < max2) {
    max2 = x[i];
    if (max2 < max3) {
        max3 = max2;
    }
} else if (max2 == max3 && x[i] < max3) {
    max3 = x[i];
}

You were very close to solving it and only a few small changes are needed to fix the bugs.

Hope this was helpful, and cheers!


问:
asp.net mvc vs javascript build whole site
i am building a site. There are two choices for me.

asp.net mvc 3.0 + ajax.

build whole site with ajax(javascript). Firstly, use ajax to get data with json format, and   then fill the whole page with the data. In this way, the page will be produced only via javascript.

Could anyone tell me the advantages and disadvantages of these two ways?

Thanks in advance.

答:
Javascript is not for building entire markup and rendering it. Don't shoot yourself in the foot.

Use ASP.Net MVC to build your site. Along side of ASP.Net MVC use jQuery/javascript to build ajax functionality.

ContentLicense: CC BY-SA 2.5


问:
Site Map for Customization Projects in 2017 R2
I have a problem with the site map in Acumatica 2017 R2

On version 17.200.0401, I created a sitemap and added workspaces and tiles. When the customization project is created it doesn't seem to include this information in the XML. As a result, if I publish this project on a new Acumatica instance, these Workspaces are not visible (although the menu looks correctly in the classic UI).

On versions 17.201.0043 and above, the situation is reversed. Workspaces are added in the customization project, but when I go to add the site map nodes to the customization project, those that are parents node (i.e. "Work Area", "Manage", "Enter", etc) are not selectable.

Version showing the Parent nodes (17.200.0401)

Version not showing the parent nodes (17.203.0029)

Development instance where the new menu was created (version 17.200.0401)

Target instance where it was published. Menu not showing the information

答:
To include custom workspaces into a customization project, you should proceed as follows:

add your new screen(s) on the Site Map screen (SM200520) - same approach as used with ver. 6.1 and before

add your new screen(s) into the new UI

open the customization manager and re-create all site map records for your custom screen(s)

Please be aware, with build # 17.200.0401 the Reload from Database button found in the Site Map section of the Customization Manager didn't add New UI elements into project.xml for previously added site map records. This issue had already been addressed in 17.201.0043.

When a node from the old site map is added in a customization, the following entities of the new UI should be also included into customization:

Node in the new site map

Workspace which contains the node

Subcategory for the node

Area for the workspace

Pinned / unpinned status for the node (if it shared setting)

Favorite / unfavorite status for the workspace

Tile for the screen

Workspace for the tile


问:
How to change color of string being drawn on JPanel

Hi, I am trying to change the font color for a string that is being drawn on my JPanel. How do I make my font color be black instead of white?

Here is how I am drawing:

```<code>g.setFont(font);
g.drawString("Rating: " + Integer.toString(rating), 150, 150);
</code>```

Here is the font:

```<code> private static final java.awt.Font verdana_12 = new java.awt.Font("Verdana", java.awt.Font.BOLD, 14);
</code>```

Thanks!

答:
To set the color in a JPanel or most things in Java Swing, there is a function available called .setColor(Color c). For your code, you would do:

g.setColor(Color.BLACK)

Here is a helpful link with more explanation:
http://www.java2s.com/Tutorials/Java/java.awt/Graphics/0940__Graphics.setColor_Color_c_.htm

This website also has other links so answer more Java Swing questions.

Body:
Hi, I am trying to change the font color for a string that is being drawn on my JPanel. How do I make my font color be black instead of white?

Here is how I am drawing:

g.setFont(font);
g.drawString("Rating: " + Integer.toString(rating), 150, 150);

Here is the font:

 private static final java.awt.Font verdana_12 = new java.awt.Font("Verdana", java.awt.Font.BOLD, 14);

Thanks!


问:
js or-equal operator equivalent as in ruby
In Ruby, I can do the following:

```<code>very_long_dictionary_name = {}
very_long_key_name = "a"

# this code usually will run inside a function invoked twice,
# first with parameter "b" and after with parameter "c", so
# I don't know if very_long_dictionary_name[very_long_key_name]
# was initialized, inside the function
(very_long_dictionary_name[very_long_key_name] ||= []).push("b")
(very_long_dictionary_name[very_long_key_name] ||= []).push("c")

very_long_dictionary_name    #=> {"a" => ["b", "c"]}
</code>```

I tried it in Javascript and I got syntax error at ||=. Is there a way to set the very_long_dictionary_name[very_long_key_name] as an empty array in javascript only if it is undefined, without repeating that long name?

答:
Is there a way to set the
  very_long_dictionary_name[very_long_key_name] as an empty array in
  javascript only if it is undefined, without repeating that long name?

Not in JavaScript. There are a few shorthand if statements you could use to set the object key as an empty array, but all require you to write the object + key at least twice for what you are attempting to do.

In JavaScript, objects are passed by reference, so you may use an 'alias' for your object key to neaten your code a little without having to worry about efficiency in this case.

```<code>let myRef = very_long_dictionary_name // Reference variable,
                                         changes with the object.
</code>```

Body:
In Ruby, I can do the following:

very_long_dictionary_name = {}
very_long_key_name = "a"

# this code usually will run inside a function invoked twice,
# first with parameter "b" and after with parameter "c", so
# I don't know if very_long_dictionary_name[very_long_key_name]
# was initialized, inside the function
(very_long_dictionary_name[very_long_key_name] ||= []).push("b")
(very_long_dictionary_name[very_long_key_name] ||= []).push("c")

very_long_dictionary_name    #=> {"a" => ["b", "c"]}

I tried it in Javascript and I got syntax error at ||=. Is there a way to set the very_long_dictionary_name[very_long_key_name] as an empty array in javascript only if it is undefined, without repeating that long name?

Body:
Is there a way to set the
  very_long_dictionary_name[very_long_key_name] as an empty array in
  javascript only if it is undefined, without repeating that long name?

Not in JavaScript. There are a few shorthand if statements you could use to set the object key as an empty array, but all require you to write the object + key at least twice for what you are attempting to do.

In JavaScript, objects are passed by reference, so you may use an 'alias' for your object key to neaten your code a little without having to worry about efficiency in this case.

let myRef = very_long_dictionary_name // Reference variable,
                                         changes with the object.


问:
Animating circles along multiple paths
I am trying to create an animation where circles are being animated on multiple paths.

I am able to get the animation I want for one of the paths but am not sure why the circles are only animating on that particular path, instead of being distributed according to the path they belong.

The full code can be found on my bl.ocks page: https://bl.ocks.org/JulienAssouline/4a11b54fc68c3255a85b31f34e171649

This is the main part of it

```<code>var path = svg.selectAll("path")
      .data(data.filter(function(d){
        return d.From > 2010
      }))
      .enter()
      .append("path")
      .style("stroke", "#832129")
      .attr("class", "arc")
      .attr("d", function(d){
        var To_scale = xScale(d.experience),
            From_scale = xScale(0),
            y = yScale(0),
            dx = To_scale - From_scale,
            dy = y,
            dr = Math.sqrt(dx * dx + dy * dy);
        return "M" + From_scale + " " + y + " A 43 50 0 0 1 " + To_scale + " " + y;
      })
      .style("fill", "none")
      .style("opacity", 0)
      .call(transition)
      .on("mouseover",  function(d){
        var thisClass = d3.select(this).attr("class")
          d3.selectAll(".path").style("opacity", 0.1)
          d3.select(this).style("stroke", "white").style("opacity", 1).style("stroke-width", 2)

        })
        .on("mouseout",  function(d){
          d3.select(this).style("stroke", "#832129").style("opacity", 1)
        })

      function transition(path){
        path.each(function(PathItem, index){
         d3.select(this).transition()
          // .delay(index + 200)
          .duration(index * 5 + 1000)
          .on("start", function(){
            d3.select(this).style("opacity", 1)
          })
          .attrTween("stroke-dasharray", tweenDash)
        })

      }

      function tweenDash(){
        var l = this.getTotalLength(),
            i = d3.interpolateString("0," + l, l + "," + l)
            return function(t){ return i(t); };
      }

      console.log(data[0])

var circle = svg.selectAll("circle")
    .data(data.filter(function(d){
        return d.From > 2010
      }))
    .enter()
    .append("circle")
    .attr("r", 5)
    .attr("cx", function(d){
      return xScale(d.experience)
    })
    .style("fill", "red")
    .attr("transform", "translate(" + 0 + ")")
    .style("opacity", 0)

transition_circles();

  function transition_circles(){
      circle.each(function(pathItem, index){
      d3.select(this)
      .transition()
      .delay(index * 200)
      .duration(index * 10 + 1000)
      .on("start", function(){
        d3.select(this).style("opacity", 1)
      })
      .on("end",function(){
        d3.select(this).style("opacity", 0)
      })
      .attrTween("transform", translateAlong(path.node(), index))
      })

    }

    function translateAlong(path, index){
     var l = path.getTotalLength();
      return function(d, i , a){
        return function(t){
          var p = path.getPointAtLength(t * l);
          return "translate(" + p.x + "," + p.y + ")";
          }
        }
    }
</code>```

Basically, I followed this https://bl.ocks.org/mbostock/1705868 example to get the point-along-path interpolation, but am having trouble adapting it to get the same effect on multiple lines.

I also tried adding .attr("cx", function(d){ return d.experience} to the circles but that didn't work.

答:
You're always passing the same path (the first one) to the translateAlong function:

```<code>.attrTween("transform", translateAlong(path.node(), index))
//this is always the first path ---------^
</code>```

You have to pass different paths to the translateAlong function. There are different ways for doing that (I don't know which one you want), one of those is:

```<code>.attrTween("transform", translateAlong(path.nodes()[index], index))
</code>```

In this approach, the indices of the circles go from 0 to the data array length minus 1. So, since path.nodes() is an array of elements, it's selecting different ones by their indices.

Here is the updated bl.ocks: https://bl.ocks.org/anonymous/f54345ed04e1a66b7cff3ebeef271428/76fc9fbaeed5dfa867fdd57b24c6451346852568

PS: regarding optimisation, you don't need to draw several paths at the same position! Right now you have dozens of paths which are exactly the same. Just draw the different paths (in your case, only 3).

Title: Animating circles along multiple paths

Body:
I am trying to create an animation where circles are being animated on multiple paths.

I am able to get the animation I want for one of the paths but am not sure why the circles are only animating on that particular path, instead of being distributed according to the path they belong.

The full code can be found on my bl.ocks page: https://bl.ocks.org/JulienAssouline/4a11b54fc68c3255a85b31f34e171649

This is the main part of it

var path = svg.selectAll("path")
      .data(data.filter(function(d){
        return d.From > 2010
      }))
      .enter()
      .append("path")
      .style("stroke", "#832129")
      .attr("class", "arc")
      .attr("d", function(d){
        var To_scale = xScale(d.experience),
            From_scale = xScale(0),
            y = yScale(0),
            dx = To_scale - From_scale,
            dy = y,
            dr = Math.sqrt(dx * dx + dy * dy);
        return "M" + From_scale + " " + y + " A 43 50 0 0 1 " + To_scale + " " + y;
      })
      .style("fill", "none")
      .style("opacity", 0)
      .call(transition)
      .on("mouseover",  function(d){
        var thisClass = d3.select(this).attr("class")
          d3.selectAll(".path").style("opacity", 0.1)
          d3.select(this).style("stroke", "white").style("opacity", 1).style("stroke-width", 2)

        })
        .on("mouseout",  function(d){
          d3.select(this).style("stroke", "#832129").style("opacity", 1)
        })

      function transition(path){
        path.each(function(PathItem, index){
         d3.select(this).transition()
          // .delay(index + 200)
          .duration(index * 5 + 1000)
          .on("start", function(){
            d3.select(this).style("opacity", 1)
          })
          .attrTween("stroke-dasharray", tweenDash)
        })

      }

      function tweenDash(){
        var l = this.getTotalLength(),
            i = d3.interpolateString("0," + l, l + "," + l)
            return function(t){ return i(t); };
      }

      console.log(data[0])

var circle = svg.selectAll("circle")
    .data(data.filter(function(d){
        return d.From > 2010
      }))
    .enter()
    .append("circle")
    .attr("r", 5)
    .attr("cx", function(d){
      return xScale(d.experience)
    })
    .style("fill", "red")
    .attr("transform", "translate(" + 0 + ")")
    .style("opacity", 0)

transition_circles();

  function transition_circles(){
      circle.each(function(pathItem, index){
      d3.select(this)
      .transition()
      .delay(index * 200)
      .duration(index * 10 + 1000)
      .on("start", function(){
        d3.select(this).style("opacity", 1)
      })
      .on("end",function(){
        d3.select(this).style("opacity", 0)
      })
      .attrTween("transform", translateAlong(path.node(), index))
      })

    }

    function translateAlong(path, index){
     var l = path.getTotalLength();
      return function(d, i , a){
        return function(t){
          var p = path.getPointAtLength(t * l);
          return "translate(" + p.x + "," + p.y + ")";
          }
        }
    }

Basically, I followed this https://bl.ocks.org/mbostock/1705868 example to get the point-along-path interpolation, but am having trouble adapting it to get the same effect on multiple lines.

I also tried adding .attr("cx", function(d){ return d.experience} to the circles but that didn't work.

Body:
You're always passing the same path (the first one) to the translateAlong function:

.attrTween("transform", translateAlong(path.node(), index))
//this is always the first path ---------^

You have to pass different paths to the translateAlong function. There are different ways for doing that (I don't know which one you want), one of those is:

.attrTween("transform", translateAlong(path.nodes()[index], index))

In this approach, the indices of the circles go from 0 to the data array length minus 1. So, since path.nodes() is an array of elements, it's selecting different ones by their indices.

Here is the updated bl.ocks: https://bl.ocks.org/anonymous/f54345ed04e1a66b7cff3ebeef271428/76fc9fbaeed5dfa867fdd57b24c6451346852568

PS: regarding optimisation, you don't need to draw several paths at the same position! Right now you have dozens of paths which are exactly the same. Just draw the different paths (in your case, only 3).


问:
A few problems with my javascript sample. Please help
Alright, so I'm trying to get a page to load some js at the end of it's loading. I think I got it, but now it's saying I'm not getting a number with this line:

```<code>parseInt(document.getElementById('canvas').style.width);
</code>```

It should be "480px" but it's NaN.

It also said the line document.getElementById('ss') was null.

Here's the full thing:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <title>Cypri Designs</title>
        <link href="style.css" rel="stylesheet" type="text/css" />
        <link rel="shortcut icon" href="/images/favicon1.ico" type="image/x-icon" />
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
        <script type="text/javascript">
        <!--
            //Variables to handle game parameters
            var gameloopId;
            var screenWidth;
            var screenHeight;
            var gameRunning = false;
            var ctx;

            var playerX = 0;
            var playerY = 0;

            //Create images
            var playerImg = new Image();

            //Wait for DOM to load and init game
            window.onload = function(){
                init();
            };

            function init(){
                initSettings();
                initImages();

                //add event handler to surrounding DIV to monitor mouse move and update mushroom's x position
                /*$("#container").mousemove(function(e){
                    mushroomX = e.pageX;
                });*/

                //add event handler for clicking on start/stop button and toggle the game play
                document.getElementById('ss').onclick = function (){

                    toggleGameplay();
                };
            }

            function initSettings()
            {
                //Get a handle to the 2d context of the canvas
                ctx = document.getElementById('canvas').getContext('2d');

                //Calulate screen height and width
                screenWidth = parseInt(document.getElementById('canvas').style.width);
                screenHeight = parseInt(document.getElementById('canvas').style.height);

                playerX = 100;
                playerY = 100;
            }

            function initImages(){
                playerImg.src = "images/player.png";
            }
            //Main game loop, it all happens here!
            function gameLoop(){

                //Clear the screen (i.e. a draw a clear rectangle the size of the screen)
                ctx.clearRect(0, 0, screenWidth, screenHeight);

                ctx.save();
                ctx.drawImage(playerImg, 0, 0);

                ctx.restore();
            }

            //Start/stop the game loop (and more importantly that annoying boinging!)
            function toggleGameplay()
            {
                gameRunning = !gameRunning;

                if(gameRunning)
                {
                    clearInterval(gameloopId);
                    gameloopId = setInterval(gameLoop, 10);
                }
                else
                {
                    clearInterval(gameloopId);
                }
            }
        //-->
        </script>

    </head>

    <body>
        <input id="ss" type="button" value="start/stop" />
        <div id="container" style="border:1px solid; cursor:none; width:480px; height:320px;">
            <canvas id="canvas" width="480px" height="320px" >
            Canvas not displaying.
            </canvas>
        </div>
    </body>
</html>
</code>```

答:
Your code has a few problems. First, these lines where you are getting the width are the cause of your NaN result.

```<code>            screenWidth = parseInt(document.getElementById('canvas').style.width);
            screenHeight = parseInt(document.getElementById('canvas').style.height);
</code>```

The width and height properties return a string value, 480px and 320px respectively. Since those are string values, the parseInt call will return NaN because 480px is not a number. I'd recommend switching to offsetWidth as mVCr and user85461 recommended.

And I don't see any problem with the document.getElementById('ss') line. When I ran it, the click event was setup and fired correctly.

Body:
Alright, so I'm trying to get a page to load some js at the end of it's loading. I think I got it, but now it's saying I'm not getting a number with this line:

parseInt(document.getElementById('canvas').style.width);

It should be "480px" but it's NaN.

It also said the line document.getElementById('ss') was null.

Here's the full thing:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

        <title>Cypri Designs</title>
        <link href="style.css" rel="stylesheet" type="text/css" />
        <link rel="shortcut icon" href="/images/favicon1.ico" type="image/x-icon" />
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />

        <input id="ss" type="button" value="start/stop" />

            <canvas id="canvas" width="480px" height="320px" >
            Canvas not displaying.
            </canvas>

Body:
Your code has a few problems. First, these lines where you are getting the width are the cause of your NaN result.

            screenWidth = parseInt(document.getElementById('canvas').style.width);
            screenHeight = parseInt(document.getElementById('canvas').style.height);

The width and height properties return a string value, 480px and 320px respectively. Since those are string values, the parseInt call will return NaN because 480px is not a number. I'd recommend switching to offsetWidth as mVCr and user85461 recommended.

And I don't see any problem with the document.getElementById('ss') line. When I ran it, the click event was setup and fired correctly.


问:
Laravel relationship between multiple models
I have the folowing models User, Test, Attempts.

User has access to tests (many-to-many)

```<code>public function tests(){
    return $this->belongsToMany('App\Test');
}
</code>```

I have table attempts with folowing columns:

```<code>- user_id
- test_id
</code>```

I need to obtain all user tests with related attempts.

How can I acquire that by using eager loading?

Thanks.

答:
Ensure firstly that the reverse side of the relationship is setup so your Tests Model will require a belongsToMany relationship with Users like so:

```<code>public function Users(){
   return $this->belongsToMany('App\User');
}
</code>```

You can specify the table name for the pivot table by passing an additonal argument to the belongsToMany like so :

```<code>public function Users(){
   return $this->belongsToMany('App\User', 'attempts');
}
</code>```

To eager load columns from a pivot you can make use of the withPivot method

Body:
I have the folowing models User, Test, Attempts.

User has access to tests (many-to-many)

public function tests(){
    return $this->belongsToMany('App\Test');
}

I have table attempts with folowing columns:

- user_id
- test_id

I need to obtain all user tests with related attempts.

How can I acquire that by using eager loading?

Thanks.

Body:
Ensure firstly that the reverse side of the relationship is setup so your Tests Model will require a belongsToMany relationship with Users like so:

public function Users(){
   return $this->belongsToMany('App\User');
}

You can specify the table name for the pivot table by passing an additonal argument to the belongsToMany like so :

public function Users(){
   return $this->belongsToMany('App\User', 'attempts');
}

To eager load columns from a pivot you can make use of the withPivot method


问:
The service "fos_user.mailer" has a dependency on a non-existent service "templating"
So, the above error has suddenly started happening, after I've been using FOSUserBundle for several Symfony projects.

I've tried including the templating service (twice now) and it seems like it's installed fine. Here is my list of requires in my composer.json:

```<code>"require": {
    "php": ">=5.5.9",
    "doctrine/doctrine-bundle": "^1.6",
    "doctrine/orm": "^2.5",
    "friendsofsymfony/user-bundle": "^2.0",
    "incenteev/composer-parameter-handler": "^2.0",
    "sensio/distribution-bundle": "^5.0.19",
    "sensio/framework-extra-bundle": "^5.0.0",
    "symfony/monolog-bundle": "^3.1.0",
    "symfony/polyfill-apcu": "^1.0",
    "symfony/swiftmailer-bundle": "^2.6.4",
    "symfony/symfony": "3.4.*",
    "symfony/templating": "^3.4",
    "twig/twig": "^1.0||^2.0"
},
</code>```

I've set up the config.yml, security.yml and the routing.yml files as per usual, and included the bundle in the AppKernel.php file. I've also created the User.php Entity but every time I try to clear the cache or update the database, I get this error.

The service "fos_user.mailer" has a dependency on a non-existent
  service "templating"

And after much searching I cannot see where to fix this problem. Any help with this is much appreciated as it's something that's never happened before, and I've always used FOSUserBundle for my security needs.

答:
I just experienced the exact same problem. The funny thing is that I created a Symfony 3.3 project just before creating a Symfony 3.4 project and the Symfony 3.3 project didn't have this problem. So they must have removed the templating component for the 3.4 release.

To solve your problem, you will have to install the templating component using composer:

composer require symfony/templating
```

<p>Then, add the following configuration under the <code>framework</code> key in your config.yml:</p>

<pre class="lang-none prettyprint-override"><code>templating:
    engines: ['twig']
</code>```

Update: I recently had to start a new Symfony 3.4 project with FOSUserBundle and discovered that I only had to add the above configuration to my config.yml file (as was mentioned in a comment below).

Body:
So, the above error has suddenly started happening, after I've been using FOSUserBundle for several Symfony projects.

I've tried including the templating service (twice now) and it seems like it's installed fine. Here is my list of requires in my composer.json:

"require": {
    "php": ">=5.5.9",
    "doctrine/doctrine-bundle": "^1.6",
    "doctrine/orm": "^2.5",
    "friendsofsymfony/user-bundle": "^2.0",
    "incenteev/composer-parameter-handler": "^2.0",
    "sensio/distribution-bundle": "^5.0.19",
    "sensio/framework-extra-bundle": "^5.0.0",
    "symfony/monolog-bundle": "^3.1.0",
    "symfony/polyfill-apcu": "^1.0",
    "symfony/swiftmailer-bundle": "^2.6.4",
    "symfony/symfony": "3.4.*",
    "symfony/templating": "^3.4",
    "twig/twig": "^1.0||^2.0"
},

I've set up the config.yml, security.yml and the routing.yml files as per usual, and included the bundle in the AppKernel.php file. I've also created the User.php Entity but every time I try to clear the cache or update the database, I get this error.

The service "fos_user.mailer" has a dependency on a non-existent
  service "templating"

And after much searching I cannot see where to fix this problem. Any help with this is much appreciated as it's something that's never happened before, and I've always used FOSUserBundle for my security needs.

Body:
I just experienced the exact same problem. The funny thing is that I created a Symfony 3.3 project just before creating a Symfony 3.4 project and the Symfony 3.3 project didn't have this problem. So they must have removed the templating component for the 3.4 release.

To solve your problem, you will have to install the templating component using composer:

composer require symfony/templating

Then, add the following configuration under the framework key in your config.yml:

templating:
    engines: ['twig']

Update: I recently had to start a new Symfony 3.4 project with FOSUserBundle and discovered that I only had to add the above configuration to my config.yml file (as was mentioned in a comment below).


问:
How to install a compiled by Gradle jar into the local Gradle Repository files-2.1 instead of the Maven repository?
In my build.gradle, I added the plugin:

```<code>apply plugin: 'maven'
</code>```

Then using gradle install I can copy the resulted jar into the maven repository : ~/.m2/repository

However, my Gradle repository resides in ~/.gradle/caches/modules-2/files-2.1. How can I install the jar into this repository?

答:
A build.gradle sample to create a Jar file along with its logback dependencies. using mavenlocale()

```<code>apply plugin: 'java'

apply plugin: 'eclipse'

version = '1.0'

sourceCompatibility = 1.7

target Compatibility = 1.7

//create a single Jar with all dependencies

 task fatJar(type: Jar) {

     manifest {

        attributes 'Implementation-Title': 'Gradle Jar File Example',

            'Implementation-Version': version,

            'Main-Class': 'com.mkyong.DateUtils'
    }
    baseName = project.name + '-all'

    from { configurations.compile.collect { it.isDirectory() ? it :
zipTree(it)

 }

}
    with jar
}

//Get dependencies from Maven central repository

repositories {

    mavenCentral()
}

//Project dependencies

dependencies {

    compile 'ch.qos.logback:logback-classic:1.1.2'

}
</code>```

Reference  create a Jar file along with its logback dependencies.

Body:
In my build.gradle, I added the plugin:

apply plugin: 'maven'

Then using gradle install I can copy the resulted jar into the maven repository : ~/.m2/repository

However, my Gradle repository resides in ~/.gradle/caches/modules-2/files-2.1. How can I install the jar into this repository?

Body:
A build.gradle sample to create a Jar file along with its logback dependencies. using mavenlocale()

apply plugin: 'java'

apply plugin: 'eclipse'

version = '1.0'

sourceCompatibility = 1.7

target Compatibility = 1.7

//create a single Jar with all dependencies

 task fatJar(type: Jar) {

     manifest {

        attributes 'Implementation-Title': 'Gradle Jar File Example',

            'Implementation-Version': version,

            'Main-Class': 'com.mkyong.DateUtils'
    }
    baseName = project.name + '-all'

    from { configurations.compile.collect { it.isDirectory() ? it :
zipTree(it)

 }

}
    with jar
}

//Get dependencies from Maven central repository

repositories {

    mavenCentral()
}

//Project dependencies

dependencies {

    compile 'ch.qos.logback:logback-classic:1.1.2'

}

Reference  create a Jar file along with its logback dependencies.


问:
How to capture old value and new value in INotifyPropertyChanged implementation of PropertyChanged event in C#
I need to capture old value, new value and property name in PropertyChanged event handler. The default implementation of INotifyPropertyChanged provides only name of the property. So after searching on internet, I found similar question here with Extended implementation of property changed.

Below is the link to that Q and interface declaration:

NotifyPropertyChanged event where event args contain the old value

```<code>public interface INotifyPropertyChangedExtended<T>
{
    event PropertyChangedExtendedEventHandler<T> PropertyChanged;
}
</code>```

public delegate void PropertyChangedExtendedEventHandler(object sender, PropertyChangedExtendedEventArgs e);

Above interface will solve my problem, however I am not understanding how to implement generic interface on my Entity class because T will change depending on data type of property.

Can anyone help me in understanding, will it be possible to implement this interface with T parameter. Sample implementation of this will be really helpful.

Thanks in advance for help.

Umesh

EDIT #1:
Based on the reply from Peter, posting updated code that may be useful for someone who wants to capture old and new values in PropertyChanged event.

```<code>    public class PropertyChangedExtendedEventArgs : PropertyChangedEventArgs
{
    public string OldValue { get; set; }

    public string NewValue { get; set; }

    public PropertyChangedExtendedEventArgs(string propertyName, string oldValue, string newValue) : base(propertyName)
    {
        OldValue = oldValue;
        NewValue = newValue;
    }
}

    //
// Summary:
//     Notifies clients that a property value has changed.
public interface INotifyPropertyChangedEnhanced
{
    //
    // Summary:
    //     Occurs when a property value changes.
    event PropertyChangedEventHandlerEnhanced PropertyChanged;
}

public delegate void PropertyChangedEventHandlerEnhanced(object sender, PropertyChangedExtendedEventArgs e);

public abstract class BindableBase : INotifyPropertyChangedEnhanced
{
    public event PropertyChangedEventHandlerEnhanced PropertyChanged;

    protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName]
    string propertyName = null)
    {
        if (Equals(storage, value))
        {
            return false;
        }

        var oldValue = storage;
        storage = value;
        this.OnPropertyChanged(oldValue, value, propertyName);
        return true;
    }
    protected void OnPropertyChanged<T>(T oldValue, T newValue, [CallerMemberName] string propertyName = null)
    {
        this.PropertyChanged?.Invoke(this, new PropertyChangedExtendedEventArgs(propertyName, oldValue?.ToString(), newValue?.ToString()));
    }
}
</code>```

答: You can't.  Implement INotifyPropetyChanging as well. That will provide access to the old value. You can find example implementations for both interfaces in the documentation. </p>

Body:
I need to capture old value, new value and property name in PropertyChanged event handler. The default implementation of INotifyPropertyChanged provides only name of the property. So after searching on internet, I found similar question here with Extended implementation of property changed.

Below is the link to that Q and interface declaration:

NotifyPropertyChanged event where event args contain the old value

public interface INotifyPropertyChangedExtended<T>
{
    event PropertyChangedExtendedEventHandler<T> PropertyChanged;
}

public delegate void PropertyChangedExtendedEventHandler(object sender, PropertyChangedExtendedEventArgs e);

Above interface will solve my problem, however I am not understanding how to implement generic interface on my Entity class because T will change depending on data type of property.

Can anyone help me in understanding, will it be possible to implement this interface with T parameter. Sample implementation of this will be really helpful.

Thanks in advance for help.

Umesh

EDIT #1:
Based on the reply from Peter, posting updated code that may be useful for someone who wants to capture old and new values in PropertyChanged event.

    public class PropertyChangedExtendedEventArgs : PropertyChangedEventArgs
{
    public string OldValue { get; set; }

    public string NewValue { get; set; }

    public PropertyChangedExtendedEventArgs(string propertyName, string oldValue, string newValue) : base(propertyName)
    {
        OldValue = oldValue;
        NewValue = newValue;
    }
}

    //
// Summary:
//     Notifies clients that a property value has changed.
public interface INotifyPropertyChangedEnhanced
{
    //
    // Summary:
    //     Occurs when a property value changes.
    event PropertyChangedEventHandlerEnhanced PropertyChanged;
}

public delegate void PropertyChangedEventHandlerEnhanced(object sender, PropertyChangedExtendedEventArgs e);

public abstract class BindableBase : INotifyPropertyChangedEnhanced
{
    public event PropertyChangedEventHandlerEnhanced PropertyChanged;

    protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName]
    string propertyName = null)
    {
        if (Equals(storage, value))
        {
            return false;
        }

        var oldValue = storage;
        storage = value;
        this.OnPropertyChanged(oldValue, value, propertyName);
        return true;
    }
    protected void OnPropertyChanged<T>(T oldValue, T newValue, [CallerMemberName] string propertyName = null)
    {
        this.PropertyChanged?.Invoke(this, new PropertyChangedExtendedEventArgs(propertyName, oldValue?.ToString(), newValue?.ToString()));
    }
}


问:
Efficient construction of cosine similarity matrix from corpus in Chapel
I have a corpus V of TF/IDF vectors, so they are pretty sparse.

It's an array about 2,500 by 150,000.

I want to calculate the cosine similarity between each document in the corpus.

This is almost the most naive way I can think of to do it.  I know of three or four optimizations already, but I don't want to assume the answer.  I'd like know the most computationally efficient way to use Chapel in this calculation.  The goal is to get X as a symmetric matrix with diag(X) = 0

```<code>use Norm,
    LinearAlgebra;

var ndocs = 2500,
    nftrs = 150000,
    docs = 1..ndocs,
    ftrs = 1..nftrs,
    V: [docs, ftrs] real,
    X: [docs, docs] real;

for i in docs {
  var n1 = norm(V[i,..]);
  for j in (i+1)..ndocs {
    var n2 = norm(V[j,..]);
    var c = dot(V[i,..], V[j,..]) / (n1*n2);
    X[i,j] = c;
    X[j,i] = c;
  }
}
</code>```

Compiled using

```<code>chpl -I/usr/local/Cellar/openblas/0.2.20/include -L/usr/local/Cellar/openblas/0.2.20/lib -lblas cosim.chpl
</code>```

== UPDATED ==

This could should actually compile and run. Original code had errors as suggested by @bradcray below

答:
[Meta: This question has been weighing on me due to its being unanswered for so long.  I've personally shied away from it due to its use of the phrase "most computationally efficient."  In practice, its hard to guarantee that any solution meets that description given variations that may occur from one target machine or dataset to the next.  But since nobody else has stepped up, I'll make some comments in hopes that they might be of use.]

A few things that stand out for me in your code:

1) Unless I'm missing something, you are computing norm(V[r, ..]) redundantly many, many times during the computation.  Asymptotically speaking, this suggests that you're doing quadratic work where only linear work is required.  I'd suggest computing the norm for each row once and storing it in an array to avoid this redundant computation:

```<code>var normVrow: [docs] real = [r in docs] norm(V[r,..]);
</code>```

Then, within the inner loop, you can just refer to normVrow[i] or normVrow[j].

2) Since this is Chapel and your loop seems to have no cross-loop dependencies, rather than using serial for loops, you should probably use a parallel forall loop for this computation.  There's a question about whether to:

(a) change your outer loop to a forall (which would result in a load imbalance since the overall iteration space is triangular),

(b) change both loops to forall loops (which would help the load imbalance problem by over-decomposing, but likely also increase overhead), or

(c) make the outer loop into a dynamically scheduled loop to address the load imbalance.

My instinct would be to do option c using Chapel's dynamic iterator:

```<code>use DynamicIters;

forall i in dynamic(ndocs) {
  ...
}
</code>```

3) A final thing to consider would be to avoid the triangular iteration space and just redundantly compute X[i,j] and X[j,i] even though they'll have the same value.  This may not make sense on a shared-memory run, but if you were computing on a distributed array X, you'd likely reduce communication since those matrix values will be stored by different processors.  In this approach, you could iterate with a single forall loop over X.domain, and the result would be well-load-balanced by default without the need for the dynamic iterator.

Body:
I have a corpus V of TF/IDF vectors, so they are pretty sparse.

It's an array about 2,500 by 150,000.

I want to calculate the cosine similarity between each document in the corpus.

This is almost the most naive way I can think of to do it.  I know of three or four optimizations already, but I don't want to assume the answer.  I'd like know the most computationally efficient way to use Chapel in this calculation.  The goal is to get X as a symmetric matrix with diag(X) = 0

use Norm,
    LinearAlgebra;

var ndocs = 2500,
    nftrs = 150000,
    docs = 1..ndocs,
    ftrs = 1..nftrs,
    V: [docs, ftrs] real,
    X: [docs, docs] real;

for i in docs {
  var n1 = norm(V[i,..]);
  for j in (i+1)..ndocs {
    var n2 = norm(V[j,..]);
    var c = dot(V[i,..], V[j,..]) / (n1*n2);
    X[i,j] = c;
    X[j,i] = c;
  }
}

Compiled using

chpl -I/usr/local/Cellar/openblas/0.2.20/include -L/usr/local/Cellar/openblas/0.2.20/lib -lblas cosim.chpl

== UPDATED ==

This could should actually compile and run. Original code had errors as suggested by @bradcray below

Body:
[Meta: This question has been weighing on me due to its being unanswered for so long.  I've personally shied away from it due to its use of the phrase "most computationally efficient."  In practice, its hard to guarantee that any solution meets that description given variations that may occur from one target machine or dataset to the next.  But since nobody else has stepped up, I'll make some comments in hopes that they might be of use.]

A few things that stand out for me in your code:

1) Unless I'm missing something, you are computing norm(V[r, ..]) redundantly many, many times during the computation.  Asymptotically speaking, this suggests that you're doing quadratic work where only linear work is required.  I'd suggest computing the norm for each row once and storing it in an array to avoid this redundant computation:

var normVrow: [docs] real = [r in docs] norm(V[r,..]);

Then, within the inner loop, you can just refer to normVrow[i] or normVrow[j].

2) Since this is Chapel and your loop seems to have no cross-loop dependencies, rather than using serial for loops, you should probably use a parallel forall loop for this computation.  There's a question about whether to:

(a) change your outer loop to a forall (which would result in a load imbalance since the overall iteration space is triangular),

(b) change both loops to forall loops (which would help the load imbalance problem by over-decomposing, but likely also increase overhead), or

(c) make the outer loop into a dynamically scheduled loop to address the load imbalance.

My instinct would be to do option c using Chapel's dynamic iterator:

use DynamicIters;

forall i in dynamic(ndocs) {
  ...
}

3) A final thing to consider would be to avoid the triangular iteration space and just redundantly compute X[i,j] and X[j,i] even though they'll have the same value.  This may not make sense on a shared-memory run, but if you were computing on a distributed array X, you'd likely reduce communication since those matrix values will be stored by different processors.  In this approach, you could iterate with a single forall loop over X.domain, and the result would be well-load-balanced by default without the need for the dynamic iterator.


问:
custom mozilla addon: how to install?
I created a simple mozilla addon. Debugging is fine - all works. Now I want to install it and have problems. I know Im supposed to create install.rdf, but cant do this. I need it as minimum as possible - addon will work only on 4 PC's at the office.

My files:
/icons
- background.js
- manifest.json

Can You help?

答:
The publishing process for firefox addons varies depending on whether you want the extension to be public, unlisted, etc.

It sounds to me like you want a private extension with no web store distribution.  To do this, you will need to create a web store account and get the extension signed.

Read this about getting the extension signed:
https://developer.mozilla.org/en-US/Add-ons/Distribution

That process will result in a signed extension that you can then privately distribute however you choose.

Packaging is detailed at
https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Publishing_your_WebExtension#2._Create_an_account_on_addons.mozilla.org

Title: custom mozilla addon: how to install?