问:
Equality inference in F# + records with mutable fields
The common equality/comparison members design guideline is to not implement structural equality on mutable reference types, but take a look at F# record types with mutable fields:

```<code>type Value = { mutable value: int }

let mutableRecord = { value = 1 }
let xs = Map.ofList [ mutableRecord, "abc"
                      { value = 2 }, "def" ]

let abc = Map.find { value=1 } xs
mutableRecord.value <- 3
let abc = Map.find { value=3 } xs // KeyNotFoundException!
</code>```

The Map is sorted internally, but mutable record fields allows me to change ordering while record instance is already inside map and this is very bad.

I think F# should infer [<NoEquality>] and [<NoComparison>] modes for F# record types that declares mutable fields, isn't it?

答:
That's not an unreasonable stance.

There might be some clever ways to leverage this feature usefully, though I haven't thought about it deeply enough.  This is basically the same thing as when you put a mutable type in a Dictionary, and you get what you deserve.  (Languages can't prevent every misuse, which is why we have design guidelines and programmer judgment to fill in the gaps :) )

Anyway, there's no changing it now.

Body:
The common equality/comparison members design guideline is to not implement structural equality on mutable reference types, but take a look at F# record types with mutable fields:

type Value = { mutable value: int }

let mutableRecord = { value = 1 }
let xs = Map.ofList [ mutableRecord, "abc"
                      { value = 2 }, "def" ]

let abc = Map.find { value=1 } xs
mutableRecord.value <- 3
let abc = Map.find { value=3 } xs // KeyNotFoundException!

The Map is sorted internally, but mutable record fields allows me to change ordering while record instance is already inside map and this is very bad.

I think F# should infer [<NoEquality>] and [<NoComparison>] modes for F# record types that declares mutable fields, isn't it?


来源: stackexchange

问:
UIImageView missing images in Launch Screen on device
I have an app that supports iOS8 and later, built in Xcode 7 and I am using a XIB for a Launch Screen (I do not have launch images). The view contains a single UILabel with the app version, and 2 UIImageViews with images that are both present in Images.xcassets: A logo and a splash image.

The UILabel and the logo image appear correctly when I launch the application, but the splash image does not if I run the app on an iPad Air 2 with iOS9. I have tested on an Air and a Mini running iOS8, and iOS9 simulators for iPad 2, iPad Air, and iPad Air 2 and the image appears correctly in all of those.

I ran some basic troubleshooting to see if I could figure out what is going on but I haven't been able to solve it and the only difference I can see between the image that's working and the one that's failing is when I added it to the assets...

Here's a rundown of what I know:

The UIImageView for the splash image is in the correct place, at the correct size. I can tell this because I set its background color to green just to make sure. The view is there, but the image does not appear. So I'm assuming that the view is not to blame.

Setting the UIImageView for the splash image to also use the logo image makes the logo image appear in the correct place for the view. This also leads me to assume that the view is not to blame.

The UIImage that I am using in the splash image view is used elsewhere in the app and appears fine in those other views (the logo image is also used elsewhere in the app and appears fine). So I'm assuming that the image is valid and having it appear in other views is not a problem.

I've confirmed that the settings of the UIImages for the logo and splash in the xcassets file are the same. They are set to Universal, Any width and height, multiple scale factors, rendered as default. There is one difference - the logo has 1x, 2x and 3x scales while the splash image only has 1x and 2x, but I have also tried using UIImages with only 1x, and 1x and 2x values in the UIView and they work (if they were added to the project some time ago).

Adding another image of a different size or format (PNG and JPG) to my xcassets and using that UIImage in the UIImageView for the splash image also fails to display.

Adding another UIImageView to the XIB file and allocating it a UIImage that was already in the xcassets works, the image appears in the loading screen.

Copying and renaming the image files used for the logo and adding them to the project then using that UIImage in the splash view also fails to display.

I have tried cleaning the project, restarting the development machine, and deleting the app from the Air 2 and reinstalling it just in case that was a problem.

These last three steps lead me to believe that there's some issue with images added after a certain point in the project file's lifetime. While I updated to Xcode 7 yesterday, the splash image was originally added in Xcode 6, but the logo image (also added in Xcode 6) was added some months before.

I've looked over the json files for the logo image and splash image and they appear to have the same format. I've also trawled through the pbxproj file looking for differences and I can't see any.

So I was wondering if anyone had any idea why the launch screen might not display these new images I'm adding on the Air 2 specifically? Other questions I've been reading through relating to images not appearing all seem to relate either to Launch Images, or to images in XIB files that have associated classes, neither of which seems relevant here.

答:
In my case I it was the image name.

I added an image named Default-568h@2x.png to LaunchScreen.xib - one of my old launch screens just for testing purposes. I was building on the iPhone X Simulator, the image didn't show up.

Changing the name to something neutral (MyImage.png) solved the issue.

It seems that the @2x was part of the problem as well as the -568h.
Which makes some sense on a -812h@3x device.

ContentLicense: CC BY-SA 3.0


问:
Count in Eloquent with distinct?
the following query:

```<code>Sheep::whereIn('foobar_id', [1, 2, 3, 4, 5])->groupBy('foobar_id')->count();
</code>```

Also instead of using groupBy I tried distinct('foobar_id') with no effect.
How can I get a result of the counts where doubles of the foobar_id are skipped?
Using Postgres

答:
```<code>Sheep::query()
   ->whereIn('foobar_id', [1, 2, 3, 4, 5])
   ->distinct()
   ->count('foobar_id');
</code>```

Title: Count in Eloquent with distinct?

Body:
the following query:

Sheep::whereIn('foobar_id', [1, 2, 3, 4, 5])->groupBy('foobar_id')->count();

Also instead of using groupBy I tried distinct('foobar_id') with no effect.
How can I get a result of the counts where doubles of the foobar_id are skipped?
Using Postgres


问:
None vs nil in Elixir
What is the difference between None and nil in Elixir?

From Elixir's documentation if I understand correctly nil is a literal representing absence of value.

But even None seems to represent the same, though I could not find any documentation over it.

答:
None is a module name, an atom, that doesn't evaluate to false in control flow.

nil is an atom that evaluates to false in control flow.

```<code>iex(1)> if None, do: :ok, else: :ko
:ok
iex(2)> if nil, do: :ok, else: :ko
:ko
</code>```

ContentLicense: CC BY-SA 4.0

Title: None vs nil in Elixir

Body:
None is a module name, an atom, that doesn't evaluate to false in control flow.

nil is an atom that evaluates to false in control flow.

iex(1)> if None, do: :ok, else: :ko
:ok
iex(2)> if nil, do: :ok, else: :ko
:ko


问:
HTTP GET search form with Phoenix
I'm trying to make a simple search form to filter my list of resources. I've made a form like this, but it's not placing q in the url as a query param like I would expect with method: :get

```<code><%= form_for @conn, post_path(@conn, :index), [as: :search, method: :get], fn f -> %>
  <%= text_input f, :q, placeholder: "Search by title, content, etc." %>
<% end %>
</code>```

When I submit this form with "term" as the search term, it results in search%5Bq%5D=term being placed in the url (the url encoded version of the name of the q field.) I expected just q=term. Am I incorrect in expecting that? What's the proper way to do a simple search form?

答:
All fields in the form are wrapped by the argument as, e.g. q with as: :search becomes search[q]. You can either keep doing this and extract this variable in the controller like this:

```<code>def index(conn, %{"search" => %{"q" => q}}) do
  ...
end
</code>```

Or, if you want the field to be just q, you can upgrade to v2.10.5 of phoenix_html and remove the as argument. This argument was made optional just 5 days ago.

Title: HTTP GET search form with Phoenix

Body:
I'm trying to make a simple search form to filter my list of resources. I've made a form like this, but it's not placing q in the url as a query param like I would expect with method: :get

<%= form_for @conn, post_path(@conn, :index), [as: :search, method: :get], fn f -> %>
  <%= text_input f, :q, placeholder: "Search by title, content, etc." %>
<% end %>

When I submit this form with "term" as the search term, it results in search%5Bq%5D=term being placed in the url (the url encoded version of the name of the q field.) I expected just q=term. Am I incorrect in expecting that? What's the proper way to do a simple search form?

Body:
All fields in the form are wrapped by the argument as, e.g. q with as: :search becomes search[q]. You can either keep doing this and extract this variable in the controller like this:

def index(conn, %{"search" => %{"q" => q}}) do
  ...
end

Or, if you want the field to be just q, you can upgrade to v2.10.5 of phoenix_html and remove the as argument. This argument was made optional just 5 days ago.


问:
Property 'getReadableSchedule' is missing in type
How do I populate a typed array where the type being populated has a function (getReadableSchedule)? If I remove the function this works. Is this failing because of the way i'm assigning the the array elements?

ERROR in src/app/mock-extracts.ts(3,14): error TS2322: Property 'getReadableSchedule' is missing in type '{ id: number; name: string; description: string; client: string; vendor: string; extractType: str...'.

export class Extract {
  id: number;
  name: string;
  description: string;
  client: string;
  vendor: string;
  extractType: string;
  path: string;
  sentDate: string;
  sentTo: string;
  lastRun: string;
  nextRun: string;
  schedule: string;

  getReadableSchedule(): string {
    return "<return readable cronjob schedule>";
  }
}
```

<pre class="lang-js prettyprint-override"><code>import { Extract } from "./extract";

export const EXTRACTS: Extract[] = [
  {
    id: 1,
    name: "Find Barb",
    description: "Find Barb in the unspide down.",
    client: "Tower, Inc",
    vendor: "Vendy",
    extractType: "Normal",
    sentDate: "Today",
    path: "//outside",
    sentTo: "",
    lastRun: "",
    nextRun: "",
    schedule: ""
  },
  {
    id: 2,
    name: "Rescue Will",
    description: "Give Will a hair cut.",
    client: "Tower, Inc",
    vendor: "Vendy",
    extractType: "Normal",
    sentDate: "Today",
    path: "//outside",
    sentTo: "",
    lastRun: "",
    nextRun: "",
    schedule: ""
  },
  {
    id: 3,
    name: "Sooth Harry's Scar",
    description: "Put Robitussin on Harry's scar.",
    client: "Tower, Inc",
    vendor: "Turkish Barn, LLC",
    extractType: "Normal",
    sentDate: "Today",
    path: "//outside",
    sentTo: "",
    lastRun: "",
    nextRun: "",
    schedule: ""
  }
];
</code>```

答:
The error happens because the object literals that are included in the array don't match the exact type structure of the Extract class.

First option:

To make it work with just a few changes, add as last property in each object the key getReadableSchedule and point it to method in the class prototype:

```<code>{
    id: 1,
    name: "Find Barb",
    description: "Find Barb in the unspide down.",
    client: "Tower, Inc",
    vendor: "Vendy",
    extractType: "Normal",
    sentDate: "Today",
    path: "//outside",
    sentTo: "",
    lastRun: "",
    nextRun: "",
    schedule: "",
    getReadableSchedule: Extract.prototype.getReadableSchedule// < -this will point to the same method in the class.
},
</code>```

Second option:

Just create an instance for each object, assign it to a variable, assign values to it's properties and then add that variable to the array, all objects created this way already have access to the method so no other change will be needed:

```<code>const EXTRACTS: Extract[] = [];

let a = new Extract();
a.propA = ...;
a.propB = ...;
.
.
.

EXTRACTS.push(a);

let b = new Extract();
b.propA = ...;
.
.
.
EXTRACTS.push(b);
</code>```

Third option:

If there is no intention to use the class as constructor, problably makes more sense to use an interface. So , outside of the class, declare a simple function equivalent to the class method...

```<code>export function getReadableSchedule(): string {

    return "<return readable cronjob schedule>";
}
</code>```

Inside the class, remove the body of the method leaving only the signature

```<code>getReadableSchedule(): string;
</code>```

and change from class to interface in the type declaration and then export it.

```<code>export interface Extract {
    .
    .
    .
}
</code>```

Now add object literals to EXTRACT array as done previously and the only thing that still is necessary to change is importing getReadableSchedule and adding it to each object:

```<code>import { Extract, getReadableSchedule } from "./extract";

const EXTRACTS: Extract[] = [
    {
        id: "whatever",
        ...,
        ...,
        ...,
        getReadableSchedule // <- this will point to the imported function
    } //<- and now all the properties are compatible with the type interface
];
</code>```

The TypeScript type system checks only the structure of types. So the class...

```<code>class Extract {
    name: string;
    getReadableSchedule() {
        return "Some message";
    }
}
</code>```

has the following type structure ...

```<code>{
    name: string;
    getReadableSchedule(): string;
}
</code>```

To assign an object literal for some variable of the type above,
that literal must have every property existent in the type and no other.

```<code>var fail1: Extract = { name: "1st failure" }; // does not type check - Missing property "getReadableSchedule"
var fail2: Extract = { getReadableSchedule() { return this.name; } }; // does not type check - Missing property "name";
var fail3: Extract = { // does not type check also!
    name: "3rd failure", // Ok!
    getReadableSchedule() { return this.name } //Ok!
    id: 1 // Error - property "id" does not exist in type Extract
};

var success: Extract = {
    name: "Success",
    getReadableSchedule() { return "Ok!"}
}; // <- No errors;

// But it is ok to assign a Variable that has all properties existent
// in the type and additional ones

var notNamedType = {
    name: "Also works",
    getReadableSchedule() { return this.name },
    id: 1 // property does not exist in the Extract type but...
}

let alsoWorks: Extract = notNamedType; // no casting needed and works as well;
</code>```

Body:
How do I populate a typed array where the type being populated has a function (getReadableSchedule)? If I remove the function this works. Is this failing because of the way i'm assigning the the array elements?

ERROR in src/app/mock-extracts.ts(3,14): error TS2322: Property 'getReadableSchedule' is missing in type '{ id: number; name: string; description: string; client: string; vendor: string; extractType: str...'.

export class Extract {
  id: number;
  name: string;
  description: string;
  client: string;
  vendor: string;
  extractType: string;
  path: string;
  sentDate: string;
  sentTo: string;
  lastRun: string;
  nextRun: string;
  schedule: string;

  getReadableSchedule(): string {
    return "<return readable cronjob schedule>";
  }
}

import { Extract } from "./extract";

export const EXTRACTS: Extract[] = [
  {
    id: 1,
    name: "Find Barb",
    description: "Find Barb in the unspide down.",
    client: "Tower, Inc",
    vendor: "Vendy",
    extractType: "Normal",
    sentDate: "Today",
    path: "//outside",
    sentTo: "",
    lastRun: "",
    nextRun: "",
    schedule: ""
  },
  {
    id: 2,
    name: "Rescue Will",
    description: "Give Will a hair cut.",
    client: "Tower, Inc",
    vendor: "Vendy",
    extractType: "Normal",
    sentDate: "Today",
    path: "//outside",
    sentTo: "",
    lastRun: "",
    nextRun: "",
    schedule: ""
  },
  {
    id: 3,
    name: "Sooth Harry's Scar",
    description: "Put Robitussin on Harry's scar.",
    client: "Tower, Inc",
    vendor: "Turkish Barn, LLC",
    extractType: "Normal",
    sentDate: "Today",
    path: "//outside",
    sentTo: "",
    lastRun: "",
    nextRun: "",
    schedule: ""
  }
];

Body:
The error happens because the object literals that are included in the array don't match the exact type structure of the Extract class.

First option:

To make it work with just a few changes, add as last property in each object the key getReadableSchedule and point it to method in the class prototype:

{
    id: 1,
    name: "Find Barb",
    description: "Find Barb in the unspide down.",
    client: "Tower, Inc",
    vendor: "Vendy",
    extractType: "Normal",
    sentDate: "Today",
    path: "//outside",
    sentTo: "",
    lastRun: "",
    nextRun: "",
    schedule: "",
    getReadableSchedule: Extract.prototype.getReadableSchedule// < -this will point to the same method in the class.
},

Second option:

Just create an instance for each object, assign it to a variable, assign values to it's properties and then add that variable to the array, all objects created this way already have access to the method so no other change will be needed:

const EXTRACTS: Extract[] = [];

let a = new Extract();
a.propA = ...;
a.propB = ...;
.
.
.

EXTRACTS.push(a);

let b = new Extract();
b.propA = ...;
.
.
.
EXTRACTS.push(b);

Third option:

If there is no intention to use the class as constructor, problably makes more sense to use an interface. So , outside of the class, declare a simple function equivalent to the class method...

export function getReadableSchedule(): string {

    return "<return readable cronjob schedule>";
}

Inside the class, remove the body of the method leaving only the signature

getReadableSchedule(): string;

and change from class to interface in the type declaration and then export it.

export interface Extract {
    .
    .
    .
}

Now add object literals to EXTRACT array as done previously and the only thing that still is necessary to change is importing getReadableSchedule and adding it to each object:

import { Extract, getReadableSchedule } from "./extract";

const EXTRACTS: Extract[] = [
    {
        id: "whatever",
        ...,
        ...,
        ...,
        getReadableSchedule // <- this will point to the imported function
    } //<- and now all the properties are compatible with the type interface
];

The TypeScript type system checks only the structure of types. So the class...

class Extract {
    name: string;
    getReadableSchedule() {
        return "Some message";
    }
}

has the following type structure ...

{
    name: string;
    getReadableSchedule(): string;
}

To assign an object literal for some variable of the type above,
that literal must have every property existent in the type and no other.

var fail1: Extract = { name: "1st failure" }; // does not type check - Missing property "getReadableSchedule"
var fail2: Extract = { getReadableSchedule() { return this.name; } }; // does not type check - Missing property "name";
var fail3: Extract = { // does not type check also!
    name: "3rd failure", // Ok!
    getReadableSchedule() { return this.name } //Ok!
    id: 1 // Error - property "id" does not exist in type Extract
};

var success: Extract = {
    name: "Success",
    getReadableSchedule() { return "Ok!"}
}; // <- No errors;

// But it is ok to assign a Variable that has all properties existent
// in the type and additional ones

var notNamedType = {
    name: "Also works",
    getReadableSchedule() { return this.name },
    id: 1 // property does not exist in the Extract type but...
}

let alsoWorks: Extract = notNamedType; // no casting needed and works as well;


问:
Matlab integer strings decoding ... speed optimization
I have the following problem:

I need decode integer sequences "c" to char string messages "m" by following association:

```<code>  numpos = 10 % ( = size(c,2)/2)
  c = [3 4 1 1 4 2 5 2 3 3,1 1 1 1 2 2 2 3 3 3]
</code>```

Each row of "c" represents 2*numpos integers, where first numpos parameters encoded position of

```<code>types = {'a' 'b@2' 'c@6' 'd@10' 'e@11'}
</code>```

and second numpos parameters are applied only if type contains character '@' like this:

```<code>  m = ' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'
</code>```

My current solution is as follows:

```<code>  function m = c2m(c,types)

  numpos = size(c,2)/2;

  F = cellfun(@(f) [' ' f], strrep(types,'@',':%d@'),'unif',0);
  m = arrayfun(@(f,k) sprintf(f{1},k),F(c(:,1:numpos)),c(:,numpos+(1:numpos)),'unif', 0);
  m = arrayfun(@(i) horzcat(m{i,:}), (1:numlines)', 'unif', 0)

  end
</code>```

and the testing code is as follows:

```<code>  numlines = 10;
  c = repmat([3 4 1 1 4 2 5 2 3 3,1 1 1 1 2 2 2 3 3 3],numlines,1);
  types = {'a' 'b@2' 'c@6' 'd@10' 'e@11'};

  m = c2m(c,types);

  m =

    10×1 cell array

      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
</code>```

The code is still too slow for me, I am looking for any speed up. In this case the most significant fraction of CPU time is spent at built-in function "sprintf".

Typical realistic sizes of problem are:

```<code>   numpos ~ 30 ... 60
   numlines ~ 1e4 ... 1e5
</code>```

Any idea?

Body:
I have the following problem:

I need decode integer sequences "c" to char string messages "m" by following association:

  numpos = 10 % ( = size(c,2)/2)
  c = [3 4 1 1 4 2 5 2 3 3,1 1 1 1 2 2 2 3 3 3]

Each row of "c" represents 2*numpos integers, where first numpos parameters encoded position of

types = {'a' 'b@2' 'c@6' 'd@10' 'e@11'}

and second numpos parameters are applied only if type contains character '@' like this:

  m = ' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'

My current solution is as follows:

  function m = c2m(c,types)

  numpos = size(c,2)/2;

  F = cellfun(@(f) [' ' f], strrep(types,'@',':%d@'),'unif',0);
  m = arrayfun(@(f,k) sprintf(f{1},k),F(c(:,1:numpos)),c(:,numpos+(1:numpos)),'unif', 0);
  m = arrayfun(@(i) horzcat(m{i,:}), (1:numlines)', 'unif', 0)

  end

and the testing code is as follows:

  numlines = 10;
  c = repmat([3 4 1 1 4 2 5 2 3 3,1 1 1 1 2 2 2 3 3 3],numlines,1);
  types = {'a' 'b@2' 'c@6' 'd@10' 'e@11'};

  m = c2m(c,types);

  m =

    10×1 cell array

      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}

The code is still too slow for me, I am looking for any speed up. In this case the most significant fraction of CPU time is spent at built-in function "sprintf".

Typical realistic sizes of problem are:

   numpos ~ 30 ... 60
   numlines ~ 1e4 ... 1e5

Any idea?

Body:
Here is an idea to start experimenting with.

numpos = 10 % ( = size(c,2)/2)
c = [3 4 1 1 4 2 5 2 3 3,1 1 1 1 2 2 2 3 3 3];
types = {'a' 'b@2' 'c@6' 'd@10' 'e@11'}

Then

types_mod = {'a@0' 'b@2' 'c@6' 'd@10' 'e@11'}'; % so that each item got a @
types_mod_split = split(types_mod,'@');
m = strcat(types_mod_split(c(1:10),1), repmat({':'},10,1), num2str(c(11:20)'), repmat({'@'},10,1), types_mod_split(c(1:10),2))'

which gives

m =
    1×10 cell array
    Columns 1 through 10

{'c:1@6'} {'d:1@10'} {'a:1@0'} {'a:1@0'} {'d:2@10'} {'b:2@2'} {'e:2@11'}    {'b:3@2'} {'c:3@6'} {'c:3@6'}


问:
Unable to get Dynatrace Authentication Token via API
I am unable to get access token of dynatrace via REST api. I have used the sample REST call provided in the dynatrace documentation but still cannot get the token, but I can log into the account on the portal using these credentials. I have signed up for a free trial account on dynatrace synthetic. Are there any permissions need to be given in order to use APIs.

```<code>    GET https://datafeed-api.dynatrace.com/publicapi/rest/v1.0/login?
    user=sampleuser&password=samplepw HTTP/1.1
    Accept-Encoding: gzip,deflate
    Accept: application/json
    User-Agent: Jakarta Commons-HttpClient/3.1
    Host: datafeed-api.dynatrace.com`enter code here`
</code>```

I get "Invalid username or password"

答: This means either the account has expired or your username + password are incorrect.</p>

Body:
I am unable to get access token of dynatrace via REST api. I have used the sample REST call provided in the dynatrace documentation but still cannot get the token, but I can log into the account on the portal using these credentials. I have signed up for a free trial account on dynatrace synthetic. Are there any permissions need to be given in order to use APIs.

    GET https://datafeed-api.dynatrace.com/publicapi/rest/v1.0/login?
    user=sampleuser&password=samplepw HTTP/1.1
    Accept-Encoding: gzip,deflate
    Accept: application/json
    User-Agent: Jakarta Commons-HttpClient/3.1
    Host: datafeed-api.dynatrace.com`enter code here`

I get "Invalid username or password"


问:
How can I make an unchecked exception thrown from a thread to be propagated to main thread?
I can't find a way (neither through SO nor debugging my code) to allow an exception thrown from a tread to be propagated to the main thread. I have already tried using Thread.setUncaughtExceptionHandler() and using CompletableFuture: .exceptionally(), .handle(),...

The point is that with these mechanisms (as I debug), the actual handling is performed on the worker thread, not main thread -and I cannot manage to get it to to the main thread.

The overall point is that I'm writing a test and that if the exception raises in the worker thread, it never gets to the main thread where the test is running, making the test to pass even when something went wrong.

I would need that exception would raise asynchronous; I cannot wait for the future to complete as I need to immediately return a Stream (a PipedStream) without blocking, from the main tread.

The only tip I get is a console error (and only when I use the traditional Thread + uncaughtExceptionHandler approach, no log at all when I try with CompletableFuture):

```<code>Exception: com.example.exception.MyException thrown from the UncaughtExceptionHandler in thread "Thread-5"
</code>```

or this if I don't define the exception handler:

```<code>Exception in thread "Thread-5" com.example.MyException: Exception message
</code>```

I provide some code:

```<code>try {
    @SuppressWarnings("squid:S2095") final PipedOutputStream pos = new PipedOutputStream();
    final PipedInputStream pis = new PipedInputStream(pos);

    CompletableFuture.runAsync(pipeDecryptorRunnable(inputStream, pos));

    return pis;

} catch (IOException e) {
    throw new CryptographyException(e.getMessage(), e);
}
</code>```

Inside pipeDecryptorRunnable is a CipherStream that decrypts data. The exception is thrown there. But I cannot catch it in the main thread and becomes invisible. The pisstream returning from this method is used to read and worker thread decrypts data on-the-fly as its being read prom pis.

EDIT:
UncaughtExceptionHandler as the answers in similar questions suggests does not work for my scenario as the handler code is invoked by worker thread, not the main one.

答:
Thanks to the tip of @RalfKleberhoff I came with the solution I was looking for. The fact is that to achieve the desired behavior an inter thread communication mechanism is required. And given that I were already working with a PipedStreams, I can leverage it to accomplish the goal –I also thought in some kind of solution involving an event bus to signal or communicate from one thread to another (main thread/worker thread) and I think some event bus libraries can achieve it as well.

So back to piped streams I had a pis to read in the main thread and its connected pos to write in the worker thread. So that, when an exception was raised in the worker, I need the main thread to notice that.

To achieve that you can extend the PipedOutputStream class, adding a method to signal the connected pipe when an exception occurs. The same way, you need to extend the connected PipedInputStream to be signaled on exception, store the exception and override the read methods in order to check if an exception occurred first and, in that case, throw the exception wrapped in the IOException of the read method.

Here the code:

```<code>/**
 * This piped stream class allows to signal Exception between threads, allowing an exception produced in the writing
 * thread to reach the reading thread.
 *
 * @author Gerard on 10/11/2017.
 */
public class ExceptionAwarePipedOutputStream extends PipedOutputStream {

    private final ExceptionAwarePipedInputStream sink;

    public ExceptionAwarePipedOutputStream(ExceptionAwarePipedInputStream sink) throws IOException {
        super(sink);
        this.sink = sink;
    }

    /**
     * Signals connected {@link ExceptionAwarePipedInputStream} that an exception ocurred allowing to propagate it
     * across respective threads. This works as inter thread communication mechanism. So it allows to the reading thread
     * notice that an exception was thrown in the writing thread.
     *
     * @param exception The exception to propagate.
     */
    public void signalException(Throwable exception) {
        sink.signalException(exception);
    }
}
</code>```

·

```<code>/**
 * This piped stream class allows to signal Exception between threads, allowing an exception produced in the writing
 * thread to reach the reading thread.
 *
 * @author Gerard on 10/11/2017.
 */
public class ExceptionAwarePipedInputStream extends PipedInputStream {

    private volatile Throwable exception;

    void signalException(Throwable exception) {
        this.exception = exception;
    }

    @Override
    public int read(byte[] b) throws IOException {
        final int read = super.read(b);
        checkException();
        return read;
    }

    @Override
    public synchronized int read() throws IOException {
        final int read = super.read();
        checkException();
        return read;
    }

    @Override
    public synchronized int read(byte[] b, int off, int len) throws IOException {
        final int read = super.read(b, off, len);
        checkException();
        return read;
    }

    private void checkException() throws IOException {
        if (exception != null) {
            throw new IOException(exception.getMessage(), exception);
        }
    }
}
</code>```

The client code:

```<code>public InputStream decrypt(InputStream inputStream) {

    assert supportedStreamModes.contains(mode) : "Unsupported cipher mode for stream decryption " + mode;

    @SuppressWarnings("squid:S2095") final ExceptionAwarePipedInputStream pis = new ExceptionAwarePipedInputStream();
    final ExceptionAwarePipedOutputStream pos = newConnectedPipedOutputStream(pis);
    final Cipher decryptor = newDecryptorInitialized(inputStream);

    CompletableFuture.runAsync(
        pipeDecryptorRunnable(inputStream, pos, decryptor));

    return pis;
}

private ExceptionAwarePipedOutputStream newConnectedPipedOutputStream(ExceptionAwarePipedInputStream pis) {
    try {
        return new ExceptionAwarePipedOutputStream(pis);
    } catch (IOException e) {
        throw new CryptographyException(e.getMessage(), e);
    }
}
</code>```

And the exception handling part (notice the thread signaling):

```<code>private Runnable pipeDecryptorRunnable(InputStream inputStream, ExceptionAwarePipedOutputStream pos, Cipher decryptor) {
    return () -> {
        try {

            // do stuff... and write to pos

        } catch (Exception e) {
            // Signaling any (checked or unchecked) exception
            pos.signalException(new CryptographyException(e.getMessage(), e));
        } finally {
            closePipedStream(pos);
        }
    };
}
</code>```

Body:
I can't find a way (neither through SO nor debugging my code) to allow an exception thrown from a tread to be propagated to the main thread. I have already tried using Thread.setUncaughtExceptionHandler() and using CompletableFuture: .exceptionally(), .handle(),...

The point is that with these mechanisms (as I debug), the actual handling is performed on the worker thread, not main thread -and I cannot manage to get it to to the main thread.

The overall point is that I'm writing a test and that if the exception raises in the worker thread, it never gets to the main thread where the test is running, making the test to pass even when something went wrong.

I would need that exception would raise asynchronous; I cannot wait for the future to complete as I need to immediately return a Stream (a PipedStream) without blocking, from the main tread.

The only tip I get is a console error (and only when I use the traditional Thread + uncaughtExceptionHandler approach, no log at all when I try with CompletableFuture):

Exception: com.example.exception.MyException thrown from the UncaughtExceptionHandler in thread "Thread-5"

or this if I don't define the exception handler:

Exception in thread "Thread-5" com.example.MyException: Exception message

I provide some code:

try {
    @SuppressWarnings("squid:S2095") final PipedOutputStream pos = new PipedOutputStream();
    final PipedInputStream pis = new PipedInputStream(pos);

    CompletableFuture.runAsync(pipeDecryptorRunnable(inputStream, pos));

    return pis;

} catch (IOException e) {
    throw new CryptographyException(e.getMessage(), e);
}

Inside pipeDecryptorRunnable is a CipherStream that decrypts data. The exception is thrown there. But I cannot catch it in the main thread and becomes invisible. The pisstream returning from this method is used to read and worker thread decrypts data on-the-fly as its being read prom pis.

EDIT:
UncaughtExceptionHandler as the answers in similar questions suggests does not work for my scenario as the handler code is invoked by worker thread, not the main one.

Body:
Thanks to the tip of @RalfKleberhoff I came with the solution I was looking for. The fact is that to achieve the desired behavior an inter thread communication mechanism is required. And given that I were already working with a PipedStreams, I can leverage it to accomplish the goal –I also thought in some kind of solution involving an event bus to signal or communicate from one thread to another (main thread/worker thread) and I think some event bus libraries can achieve it as well.

So back to piped streams I had a pis to read in the main thread and its connected pos to write in the worker thread. So that, when an exception was raised in the worker, I need the main thread to notice that.

To achieve that you can extend the PipedOutputStream class, adding a method to signal the connected pipe when an exception occurs. The same way, you need to extend the connected PipedInputStream to be signaled on exception, store the exception and override the read methods in order to check if an exception occurred first and, in that case, throw the exception wrapped in the IOException of the read method.

Here the code:

/**
 * This piped stream class allows to signal Exception between threads, allowing an exception produced in the writing
 * thread to reach the reading thread.
 *
 * @author Gerard on 10/11/2017.
 */
public class ExceptionAwarePipedOutputStream extends PipedOutputStream {

    private final ExceptionAwarePipedInputStream sink;

    public ExceptionAwarePipedOutputStream(ExceptionAwarePipedInputStream sink) throws IOException {
        super(sink);
        this.sink = sink;
    }

    /**
     * Signals connected {@link ExceptionAwarePipedInputStream} that an exception ocurred allowing to propagate it
     * across respective threads. This works as inter thread communication mechanism. So it allows to the reading thread
     * notice that an exception was thrown in the writing thread.
     *
     * @param exception The exception to propagate.
     */
    public void signalException(Throwable exception) {
        sink.signalException(exception);
    }
}

·

/**
 * This piped stream class allows to signal Exception between threads, allowing an exception produced in the writing
 * thread to reach the reading thread.
 *
 * @author Gerard on 10/11/2017.
 */
public class ExceptionAwarePipedInputStream extends PipedInputStream {

    private volatile Throwable exception;

    void signalException(Throwable exception) {
        this.exception = exception;
    }

    @Override
    public int read(byte[] b) throws IOException {
        final int read = super.read(b);
        checkException();
        return read;
    }

    @Override
    public synchronized int read() throws IOException {
        final int read = super.read();
        checkException();
        return read;
    }

    @Override
    public synchronized int read(byte[] b, int off, int len) throws IOException {
        final int read = super.read(b, off, len);
        checkException();
        return read;
    }

    private void checkException() throws IOException {
        if (exception != null) {
            throw new IOException(exception.getMessage(), exception);
        }
    }
}

The client code:

public InputStream decrypt(InputStream inputStream) {

    assert supportedStreamModes.contains(mode) : "Unsupported cipher mode for stream decryption " + mode;

    @SuppressWarnings("squid:S2095") final ExceptionAwarePipedInputStream pis = new ExceptionAwarePipedInputStream();
    final ExceptionAwarePipedOutputStream pos = newConnectedPipedOutputStream(pis);
    final Cipher decryptor = newDecryptorInitialized(inputStream);

    CompletableFuture.runAsync(
        pipeDecryptorRunnable(inputStream, pos, decryptor));

    return pis;
}

private ExceptionAwarePipedOutputStream newConnectedPipedOutputStream(ExceptionAwarePipedInputStream pis) {
    try {
        return new ExceptionAwarePipedOutputStream(pis);
    } catch (IOException e) {
        throw new CryptographyException(e.getMessage(), e);
    }
}

And the exception handling part (notice the thread signaling):

private Runnable pipeDecryptorRunnable(InputStream inputStream, ExceptionAwarePipedOutputStream pos, Cipher decryptor) {
    return () -> {
        try {

            // do stuff... and write to pos

        } catch (Exception e) {
            // Signaling any (checked or unchecked) exception
            pos.signalException(new CryptographyException(e.getMessage(), e));
        } finally {
            closePipedStream(pos);
        }
    };
}


问:
variable === undefined vs. typeof variable === "undefined"
The jQuery Core Style Guidelines suggest two different ways to check whether a variable is defined.

Global Variables: typeof variable === "undefined"

Local Variables: variable === undefined

Properties: object.prop === undefined

Why does jQuery use one approach for global variables and another for locals and properties?

答:
Yet another reason for using the typeof-variant: undefined can be redefined.

```<code>undefined = "foo";
var variable = "foo";
if (variable === undefined)
  console.log("eh, what?!");
</code>```

The result of typeof variable  cannot.

Update: note that this is not the case in ES5 there the global undefined is a non-configurable, non-writable property:

15.1.1 Value Properties of the Global Object

  [...]

  15.1.1.3 undefined

  The value of undefined is undefined (see 8.1). This property has the attributes

  { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.

But it still can be shadowed by a local variable:

(function() {
  var undefined = "foo";
  var variable = "foo";
  if (variable === undefined)
    console.log("eh, what?!");
})()
```

<p>or parameter:</p>

<pre class="lang-js prettyprint-override"><code>(function(undefined) {
  var variable = "foo";
  if (variable === undefined)
    console.log("eh, what?!");
})("foo")
</code>```

Body:
Yet another reason for using the typeof-variant: undefined can be redefined.

undefined = "foo";
var variable = "foo";
if (variable === undefined)
  console.log("eh, what?!");

The result of typeof variable  cannot.

Update: note that this is not the case in ES5 there the global undefined is a non-configurable, non-writable property:

15.1.1 Value Properties of the Global Object

  [...]

  15.1.1.3 undefined

  The value of undefined is undefined (see 8.1). This property has the attributes

  { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.

But it still can be shadowed by a local variable:

(function() {
  var undefined = "foo";
  var variable = "foo";
  if (variable === undefined)
    console.log("eh, what?!");
})()

or parameter:

(function(undefined) {
  var variable = "foo";
  if (variable === undefined)
    console.log("eh, what?!");
})("foo")


问:
Typescript and IDB library for using indexedDB. Guidance needed
Question from a newbie.
I'm trying to follow the walk through Working with IndexedDB tutorial which uses Jake Archibald's IDB library but using Typescript instead of plain Javascript. I'm not having much of a success so far.

My code looks like this.

```<code>import * as idb from "./idb";

const dbPromise: Promise<idb.DB> = idb.default.open('test-db2', 1, (upgradeDb: idb.UpgradeDB) => {
    console.log('making a new object store');
    if (!upgradeDb.objectStoreNames.contains('firstOS')) {
        upgradeDb.createObjectStore('firstOS');
    }
});
</code>```

The definition file loads well since the compiler doesn't throw any errors and intellisense works fine in VS Code.

I manage to load my module using require.js on my html page, but the console shows the following error:

```<code>Uncaught TypeError: Cannot read property 'default' of undefined
at Object.<anonymous> (main.ts:8)
at Object.execCb (require.min.js:5)
at b.check (require.min.js:5)
at b.<anonymous> (require.min.js:5)
at require.min.js:5
at require.min.js:5
at each (require.min.js:5)
at b.emit (require.min.js:5)
at b.check (require.min.js:5)
at b.enable (require.min.js:5)
</code>```

Now, if I remove defaultfrom the call to idb.default.open(...), the compiler tells me that 'open' does not exist on type '.../idb'.
The library exports idb as its default.

I'm missing some sort of initialization but I cannot really see what or where.

Can anyone help?

WORK AROUND

This is how I finally made this work.

```<code>import * as idxdb from "./idb";
import "./js/idb.js";

let dbPromise: Promise<idxdb.DB> = idb.open('test-db2', 1, (upgradeDb: idxdb.UpgradeDB) => {
    console.log('making a new object store');
    if (!upgradeDb.objectStoreNames.contains('firstOS')) {
        upgradeDb.createObjectStore('firstOS');
    }
});
</code>```

The first import statement brings the types in so it compiles and it provides hinting. The second statement brings the idb object to the mix.

Thanks very much to @Josh for pointing me in the right direction.

答:
When importing a default export, the syntax is:

```<code>import idb from "./idb";
</code>```

This only works with default exports.

You should then be able to use:

```<code>idb.open(/* ... */)
</code>```

Body:
Question from a newbie.
I'm trying to follow the walk through Working with IndexedDB tutorial which uses Jake Archibald's IDB library but using Typescript instead of plain Javascript. I'm not having much of a success so far.

My code looks like this.

import * as idb from "./idb";

const dbPromise: Promise<idb.DB> = idb.default.open('test-db2', 1, (upgradeDb: idb.UpgradeDB) => {
    console.log('making a new object store');
    if (!upgradeDb.objectStoreNames.contains('firstOS')) {
        upgradeDb.createObjectStore('firstOS');
    }
});

The definition file loads well since the compiler doesn't throw any errors and intellisense works fine in VS Code.

I manage to load my module using require.js on my html page, but the console shows the following error:

Uncaught TypeError: Cannot read property 'default' of undefined
at Object.<anonymous> (main.ts:8)
at Object.execCb (require.min.js:5)
at b.check (require.min.js:5)
at b.<anonymous> (require.min.js:5)
at require.min.js:5
at require.min.js:5
at each (require.min.js:5)
at b.emit (require.min.js:5)
at b.check (require.min.js:5)
at b.enable (require.min.js:5)

Now, if I remove defaultfrom the call to idb.default.open(...), the compiler tells me that 'open' does not exist on type '.../idb'.
The library exports idb as its default.

I'm missing some sort of initialization but I cannot really see what or where.

Can anyone help?

WORK AROUND

This is how I finally made this work.

import * as idxdb from "./idb";
import "./js/idb.js";

let dbPromise: Promise<idxdb.DB> = idb.open('test-db2', 1, (upgradeDb: idxdb.UpgradeDB) => {
    console.log('making a new object store');
    if (!upgradeDb.objectStoreNames.contains('firstOS')) {
        upgradeDb.createObjectStore('firstOS');
    }
});

The first import statement brings the types in so it compiles and it provides hinting. The second statement brings the idb object to the mix.

Thanks very much to @Josh for pointing me in the right direction.

Body:
When importing a default export, the syntax is:

import idb from "./idb";

This only works with default exports.

You should then be able to use:

idb.open(/* ... */)


问:
Shoot object to mouse position direction
I want to force my object to my mouse position, I mean force it in direction between my object and mouse position, I use this code:

if(Input.GetKeyDown(KeyCode.Space))
{
    GetComponent<Rigidbody2D>().velocity = Vector2.zero;
    Vector2 direction = (Vector2)(transform.position - Input.mousePosition);
    direction.Normalize();

    this.GetComponent<Rigidbody2D>().AddForce(-direction, ForceMode2D.Impulse);
}
```

But it seems its not works correctly...

答:
You can use iTween also if you want a smother and a more controlled movement:

http://www.pixelplacement.com/itween/index.php

Body:
I want to force my object to my mouse position, I mean force it in direction between my object and mouse position, I use this code:

if(Input.GetKeyDown(KeyCode.Space))
{
    GetComponent<Rigidbody2D>().velocity = Vector2.zero;
    Vector2 direction = (Vector2)(transform.position - Input.mousePosition);
    direction.Normalize();

    this.GetComponent<Rigidbody2D>().AddForce(-direction, ForceMode2D.Impulse);
}

But it seems its not works correctly...


问:
How to access request object inside Item Pipeline Scrapy
I have a item pipeline to process prices. I am having errors while processing item in this pipeline. But scrapy error doesn't tells which url produced error. Is there any way i can access the request object inside the pipeline</p>

```<code>def process_item(self, item, spider):
    """
        :param self:
        :param item:
        :param spider:
    """
    print dir(spider) # No request object here...
    quit()
    if not all(item['price']):
        raise DropItem

    item['price']['new'] = float(re.sub(
        "\D", "", item['price']['new']))
    item['price']['old'] = float(re.sub(
        "\D", "", item['price']['old']))
    try:
        item['price']['discount'] = math.ceil(
            100 - (100 * (item['price']['new'] /
                          item['price']['old'])))
    except ZeroDivisionError as e:
        print "Error in calculating discount {item} {request}".format(item=item, request=spider.request) # here I want to see the culprit url...
        raise DropItem

    return item
</code>```

答:
You can't from an ItemPipeline, you would be able to access the response (and response.url) from an spider middleware but I think the easier solution would be to add a temporary url field assigned when you yield the item, something like:

```<code>yield {...
       'url': response.url,
       ...}
</code>```

The the url can be easily accessed inside the pipeline.

Body:
I have a item pipeline to process prices. I am having errors while processing item in this pipeline. But scrapy error doesn't tells which url produced error. Is there any way i can access the request object inside the pipeline

def process_item(self, item, spider):
    """
        :param self:
        :param item:
        :param spider:
    """
    print dir(spider) # No request object here...
    quit()
    if not all(item['price']):
        raise DropItem

    item['price']['new'] = float(re.sub(
        "\D", "", item['price']['new']))
    item['price']['old'] = float(re.sub(
        "\D", "", item['price']['old']))
    try:
        item['price']['discount'] = math.ceil(
            100 - (100 * (item['price']['new'] /
                          item['price']['old'])))
    except ZeroDivisionError as e:
        print "Error in calculating discount {item} {request}".format(item=item, request=spider.request) # here I want to see the culprit url...
        raise DropItem

    return item

Body:
You can't from an ItemPipeline, you would be able to access the response (and response.url) from an spider middleware but I think the easier solution would be to add a temporary url field assigned when you yield the item, something like:

yield {...
       'url': response.url,
       ...}

The the url can be easily accessed inside the pipeline.


问:
Visual Studio 2013 caching older version of .js file
I am working on a small web api project in Visual Studio 2013 Ultimate.  Windows 2013.  Internet Explorer 9.  When I run (debug) from VS using the internal web server (I guess that is IIS Express, now), I am finding that the changes I am making (and saving) to a javascript page are being ignored.  Placing a breakpoint in the javascript shows the older code without my changes.

CTRL+F5 does not force the application to use the currently updated page.  Checking the page in, then checking it back out often works.  Is there some setting or trick that will help me out here?

答:
So i had the same problem and i could avoid this by canceling the .ASP.NET-Server
.ASP.NET-Server from Visual Studio for debugging
 from Visual Studio and restarting the debugging. Hope this helps someone.</p>


问:
How to force ant javac task to overwrite the class file in the destination directory?
Here is a very simplified version of what I am trying to achieve. I have two directories, Directory1 and Directory2. Both directories contain Java source files. Some of the files in Directory2 can have the same fully qualified class name as the files in Directory1.

Using ant, the files are compiled to a directory called CompileDirectory, first from Directory1 and then from Directory2. I want the files in Directory2 to be compiled and overwrite the compiled class files from Directory1. However, ant seems to ignore the classes that have the same fully qualified class name.

Here's a simple example -

Directory structure

```<code>$ ls -R
.:
build.xml  CompileDirectory  Directory1  Directory2

./CompileDirectory:

./Directory1:
A.java

./Directory2:
A.java
</code>```

build.xml

```<code><project name="TestProject" default="build" basedir=".">

<target name="build" depends="javac1, javac2" />

<target name="javac1">
     <javac srcdir="${basedir}/Directory1" destdir="CompileDirectory" includeantruntime="false"/>
</target>

<target name="javac2">
     <javac srcdir="${basedir}/Directory2" destdir="CompileDirectory" includeantruntime="false"/>
</target>

</project>
</code>```

Ant run

```<code>$ ant -buildfile build.xml

Buildfile: ...(path).../build.xml

javac1:
    [javac] Compiling 1 source file to ...(path).../CompileDirectory

javac2:

build:

BUILD SUCCESSFUL
Total time: 0 seconds
</code>```

As can be seen, the javac2 target above does nothing.

When I run the Java program, I see that the class file is the one from Directory1.

```<code>$ cd CompileDirectory/
$ java A
I am class A from directory 1
</code>```

Is there a way to force the javac task in the javac2 target to compile the source file in Directory2 and overwrite the class file in the CompileDirectory?

答:
Other possible way to avoid this is create a stage directory and compile the classes there and copy back to original directory using overwrite option.

```<code>  <project name="TestProject" default="build" basedir=".">

<target name="build" depends="javac1, javac2, copy1" />

<target name="javac1">
     <javac srcdir="${basedir}/Directory1" destdir="CompileDirectory" includeantruntime="false"/>
</target>

<target name="javac2">
     <javac srcdir="${basedir}/Directory2" destdir="CompileDirectory1" includeantruntime="false"/>
</target>
<target name="copy1">
   <copy overwrite="on" todir="CompileDirectory">
       <fileset dir="CompileDirectory1">
                <include name ="**/*.*"/>
       </fileset>
   </copy>
</target>
</code>```

Body:
Here is a very simplified version of what I am trying to achieve. I have two directories, Directory1 and Directory2. Both directories contain Java source files. Some of the files in Directory2 can have the same fully qualified class name as the files in Directory1.

Using ant, the files are compiled to a directory called CompileDirectory, first from Directory1 and then from Directory2. I want the files in Directory2 to be compiled and overwrite the compiled class files from Directory1. However, ant seems to ignore the classes that have the same fully qualified class name.

Here's a simple example -

Directory structure

$ ls -R
.:
build.xml  CompileDirectory  Directory1  Directory2

./CompileDirectory:

./Directory1:
A.java

./Directory2:
A.java

build.xml

<project name="TestProject" default="build" basedir=".">

<target name="build" depends="javac1, javac2" />

<target name="javac1">
     <javac srcdir="${basedir}/Directory1" destdir="CompileDirectory" includeantruntime="false"/>
</target>

<target name="javac2">
     <javac srcdir="${basedir}/Directory2" destdir="CompileDirectory" includeantruntime="false"/>
</target>

</project>

Ant run

$ ant -buildfile build.xml

Buildfile: ...(path).../build.xml

javac1:
    [javac] Compiling 1 source file to ...(path).../CompileDirectory

javac2:

build:

BUILD SUCCESSFUL
Total time: 0 seconds

As can be seen, the javac2 target above does nothing.

When I run the Java program, I see that the class file is the one from Directory1.

$ cd CompileDirectory/
$ java A
I am class A from directory 1

Is there a way to force the javac task in the javac2 target to compile the source file in Directory2 and overwrite the class file in the CompileDirectory?

Body:
Other possible way to avoid this is create a stage directory and compile the classes there and copy back to original directory using overwrite option.

  <project name="TestProject" default="build" basedir=".">

<target name="build" depends="javac1, javac2, copy1" />

<target name="javac1">
     <javac srcdir="${basedir}/Directory1" destdir="CompileDirectory" includeantruntime="false"/>
</target>

<target name="javac2">
     <javac srcdir="${basedir}/Directory2" destdir="CompileDirectory1" includeantruntime="false"/>
</target>
<target name="copy1">
   <copy overwrite="on" todir="CompileDirectory">
       <fileset dir="CompileDirectory1">
                <include name ="**/*.*"/>
       </fileset>
   </copy>
</target>


问:
Expand environment variable for My Documents
I know I can read environment variables like this:

```<code>Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
</code>```

However, it would be really helpful to me if I could do something like this:

```<code>Environment.ExpandEnvironmentVariables(@"%MyDocuments%\Foo");
</code>```

Is there an environement variable that equals SpecialFolder.MyDocuments?

I also tried to do something like this, but this doesn't lead to the expected result:

```<code>Environment.ExpandEnvironmentVariables(@"%USERPROFILE%\My Documents\Foo");
</code>```

This way I ended up with something like @"C:\Users\<MyUser>\My Documents\Foo" but I what I need is @"\\someservername\users$\<MyUser>\My Documents\Foo".

EDIT: My Goal is NOT to hardcode either environment variable nor the part after that.

Any other suggestions?

答:
I'm not sure if there is a good way to do this but instead of trying to do environment expansion to get the path why not use the Path.Combine API instead?

```<code>Path.Combine(
  Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
  "Foo");
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I know I can read environment variables like this:

Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

However, it would be really helpful to me if I could do something like this:

Environment.ExpandEnvironmentVariables(@"%MyDocuments%\Foo");

Is there an environement variable that equals SpecialFolder.MyDocuments?

I also tried to do something like this, but this doesn't lead to the expected result:

Environment.ExpandEnvironmentVariables(@"%USERPROFILE%\My Documents\Foo");

This way I ended up with something like @"C:\Users\<MyUser>\My Documents\Foo" but I what I need is @"\\someservername\users$\<MyUser>\My Documents\Foo".

EDIT: My Goal is NOT to hardcode either environment variable nor the part after that.

Any other suggestions?

Body:
I'm not sure if there is a good way to do this but instead of trying to do environment expansion to get the path why not use the Path.Combine API instead?

Path.Combine(
  Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
  "Foo");


问:
Angular 4 route.navigate expand collapsed menu
My Angular 4 application has a navigation side menu with 2 collapsed items containing submenu items.  The routing for the menu works find unless I programmatically route to pages.  I can see in the source that the correct menu item is marked active, but it does not expand the menu to show the submenu items.

navigation.componenet.html

```<code><nav class="navbar-default navbar-static-side" role="navigation">
    <div class="sidebar-collapse">
        <ul class="nav metismenu" id="side-menu">

            <li>
                <a [routerLink]="['/home']">
                    <i class="fa fa-home"></i> <span class="nav-label">Home</span>
                    <div class="hidden-lg hidden-md side-menu-phone-text">  home</div>
                </a>
            </li>
            <li [routerLinkActive]="['active']">
                <a href="#">
                    <i class="fa fa-heartbeat"></i> <span class="nav-label">Number Pages</span> <span class="fa arrow"></span>
                    <div class="hidden-lg hidden-md side-menu-phone-text">  numbers</div>
                </a>
                <ul class="nav nav-second-level collapse"  [routerLinkActive]="['in']">
                    <li [routerLinkActive]="['active']"><a [routerLink]="['/pageone']">Page One</a></li>
                    <li [routerLinkActive]="['active']"><a [routerLink]="['/pagetwo']">Page Two</a></li>
                    <li [routerLinkActive]="['active']"><a [routerLink]="['/pagethree']">Page Three</a></li>
                </ul>
            </li>
            <li [routerLinkActive]="['active']">
                <a href="#">
                    <i class="fa fa-gear"></i> <span class="nav-label">Color Pages</span> <span class="fa arrow"></span>
                    <div class="hidden-lg hidden-md side-menu-phone-text">  colors</div>
                </a>
                <ul class="nav nav-second-level collapse"  [routerLinkActive]="['in']">
                    <li [routerLinkActive]="['active']"><a [routerLink]="['/pagered']">Page Red</a></li>
                    <li [routerLinkActive]="['active']"><a [routerLink]="['/pageblue']">Page Blue</a></li>
                    <li [routerLinkActive]="['active']"><a [routerLink]="['/pageblack']">Page Black</a></li>
                </ul>
            </li>
        </ul>
    </div>
</nav>
</code>```

app.routes.ts

```<code>        export const appRoutes: Routes = [
        // Main redirect
        { path: '', redirectTo: 'home', pathMatch: 'full' },
        {
            path: '', component: LayoutComponent,
            children: [
                { path: 'home', component: HomeComponent },

                { path: 'PageOne', component: PageOneComponent },
                { path: 'PageTwo', component: PageTwoComponent },
                { path: 'PageThree', component: PageThreeComponent },

                { path: 'PageRed', component: PageRedComponent },
                { path: 'PageBlue', component: PageBlueComponent },
                { path: 'PageBlack', component: PageBlackComponent },

            ]
        },
        // Handle all other routes
        { path: '**', redirectTo: 'home', pathMatch: 'full' }
    ];
</code>```

edit:  I figured it out.  I needed to ad  [routerLinkActive]="['in']" to the ul.  I updated the code above.

答: I figured it out.  I needed to ad [routerLinkActive]="['in']" to the ul.  I updated the code in the question.</p>

Body:
My Angular 4 application has a navigation side menu with 2 collapsed items containing submenu items.  The routing for the menu works find unless I programmatically route to pages.  I can see in the source that the correct menu item is marked active, but it does not expand the menu to show the submenu items.

navigation.componenet.html

                     Home

  home

                     Number Pages

  numbers

Page One

Page Two

Page Three

                     Color Pages

  colors

Page Red

Page Blue

Page Black

app.routes.ts

        export const appRoutes: Routes = [
        // Main redirect
        { path: '', redirectTo: 'home', pathMatch: 'full' },
        {
            path: '', component: LayoutComponent,
            children: [
                { path: 'home', component: HomeComponent },

                { path: 'PageOne', component: PageOneComponent },
                { path: 'PageTwo', component: PageTwoComponent },
                { path: 'PageThree', component: PageThreeComponent },

                { path: 'PageRed', component: PageRedComponent },
                { path: 'PageBlue', component: PageBlueComponent },
                { path: 'PageBlack', component: PageBlackComponent },

            ]
        },
        // Handle all other routes
        { path: '**', redirectTo: 'home', pathMatch: 'full' }
    ];

edit:  I figured it out.  I needed to ad  [routerLinkActive]="['in']" to the ul.  I updated the code above.


问:
Error reading built in keras datasets - Type Error: 'int' object is not callable
I've just installed the keras and tensorflow packages. I'm looking to get started with building some deep learning models, but I'm immediately stuck trying to read example data into the R environment.

Consider the following code:

```<code>#loading keras library
library(keras)
library(tensorflow)

#loading the keras inbuilt cifar10 dataset
?dataset_cifar10 #to see the help file for details of dataset
cifar <- dataset_cifar10()
</code>```

When I run the code I get the following error:

```<code>Error in py_call_impl(callable, dots$args, dots$keywords) :
  TypeError: 'int' object is not callable

Detailed traceback:
  File "C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\lib\site-packages\keras\datasets\mnist.py", line 17, in load_data
    file_hash='8a61469f7ea1b51cbae51d4f78837e45')
  File "C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\lib\site-packages\keras\utils\data_utils.py", line 220, in get_file
    urlretrieve(origin, fpath, dl_progress)
  File "C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\lib\urllib\request.py", line 274, in urlretrieve
    reporthook(blocknum, bs, size)
  File "C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\lib\site-packages\keras\utils\data_utils.py", line 213, in dl_progress
    ProgressTracker.progbar = Progbar(total_size)
  File "C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\lib\site-packages\keras\utils\generic_utils.py", line 270, in __init__
    self._dynamic_display = (sys.stdout.isatty() or
</code>```

Any ideas on what's going on here? The suggestion of installing the reticulate package from git hub versus CRAN is suggested here , but this doesn't solve my issue. Any ideas?

My session info as it relates to keras and tensorflow is here:

```<code>> reticulate::py_config()
python:         C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\python.exe
libpython:      C:/Users/stc004/AppData/Local/CONTIN~1/ANACON~1/python36.dll
pythonhome:     C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1
version:        3.6.0 |Anaconda 4.3.1 (64-bit)| (default, Dec 23 2016, 11:57:41) [MSC v.1900 64 bit (AMD64)]
Architecture:   64bit
numpy:          C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\lib\site-packages\numpy
numpy_version:  1.11.3
keras:          C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\lib\site-packages\keras

python versions found:
 C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\python.exe
 C:\Users\stc004\AppData\Local\Programs\Python\PYTHON~1\\python.exe
> tf_config()
TensorFlow v1.2.1 (C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\lib\site-packages\keras)
Python v3.6 (C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\python.exe)
</code>```

答:
Changing Keras version to 2.0.0 helped me with similar problem.

```<code>pip install keras==2.0.0
</code>```

I was using 2.0.9 before.

Body:
I've just installed the keras and tensorflow packages. I'm looking to get started with building some deep learning models, but I'm immediately stuck trying to read example data into the R environment.

Consider the following code:

#loading keras library
library(keras)
library(tensorflow)

#loading the keras inbuilt cifar10 dataset
?dataset_cifar10 #to see the help file for details of dataset
cifar <- dataset_cifar10()

When I run the code I get the following error:

Error in py_call_impl(callable, dots$args, dots$keywords) :
  TypeError: 'int' object is not callable

Detailed traceback:
  File "C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\lib\site-packages\keras\datasets\mnist.py", line 17, in load_data
    file_hash='8a61469f7ea1b51cbae51d4f78837e45')
  File "C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\lib\site-packages\keras\utils\data_utils.py", line 220, in get_file
    urlretrieve(origin, fpath, dl_progress)
  File "C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\lib\urllib\request.py", line 274, in urlretrieve
    reporthook(blocknum, bs, size)
  File "C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\lib\site-packages\keras\utils\data_utils.py", line 213, in dl_progress
    ProgressTracker.progbar = Progbar(total_size)
  File "C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\lib\site-packages\keras\utils\generic_utils.py", line 270, in __init__
    self._dynamic_display = (sys.stdout.isatty() or

Any ideas on what's going on here? The suggestion of installing the reticulate package from git hub versus CRAN is suggested here , but this doesn't solve my issue. Any ideas?

My session info as it relates to keras and tensorflow is here:

> reticulate::py_config()
python:         C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\python.exe
libpython:      C:/Users/stc004/AppData/Local/CONTIN~1/ANACON~1/python36.dll
pythonhome:     C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1
version:        3.6.0 |Anaconda 4.3.1 (64-bit)| (default, Dec 23 2016, 11:57:41) [MSC v.1900 64 bit (AMD64)]
Architecture:   64bit
numpy:          C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\lib\site-packages\numpy
numpy_version:  1.11.3
keras:          C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\lib\site-packages\keras

python versions found:
 C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\python.exe
 C:\Users\stc004\AppData\Local\Programs\Python\PYTHON~1\\python.exe
> tf_config()
TensorFlow v1.2.1 (C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\lib\site-packages\keras)
Python v3.6 (C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\python.exe)

Body:
Changing Keras version to 2.0.0 helped me with similar problem.

pip install keras==2.0.0

I was using 2.0.9 before.


问:
Azure MARS agent software dependencies
What are the dependencies of the Azure backup agent, Azure backup server (such as the specific version of ".net framework" and any additional software) Can anyone list out these dependencies I can find it anywhere</p>

答:
Azure backup server needs .NET framework 4.6, server should be join to a domain and SQL Server Standard.

For more information refer: https://learn.microsoft.com/en-us/azure/backup/backup-azure-microsoft-azure-backup

Azure Backup agent needs Microsoft .NET framework 4.5 and windows PowerShell

For more information refer: https://learn.microsoft.com/en-us/azure/backup/backup-configure-vault

Title: Azure MARS agent software dependencies


问:
Android dependency '..' has different version for the compile (..) and runtime (..) classpath
I migrated to Android Studio 3 and Gradle 4. Then I changed compile to implementation in my build.gradle files. But I get the error:

```<code>Error:Execution failed for task ':app:preDebugBuild'.
> Android dependency 'com.google.firebase:firebase-core' has different version for the compile (9.0.0) and runtime (11.6.0) classpath. You should manually set the same version via DependencyResolution
</code>```

When I change implementation to api the error disappear. But this is not the solution. I have the app module and one library module. App build.gradle has only one dependency:

```<code>implementation project(':common-lib')
</code>```

The apply plugin: 'com.google.gms.google-services' is correctly placed at the bottom of the app build.gradle file (the project worked before migration to Gradle 4)

Dependencies from gradlew app:dependencies (clipping of text):

Compile

```<code>debugAndroidTestCompileClasspath - Resolved configuration for compilation for variant: debugAndroidTest
+--- com.google.firebase:firebase-core:9.0.0
|    \--- com.google.firebase:firebase-analytics:9.0.0
|         +--- com.google.android.gms:play-services-basement:9.0.0
|         |    \--- com.android.support:support-v4:23.0.0
|         |         \--- com.android.support:support-annotations:23.0.0
|         +--- com.google.firebase:firebase-common:9.0.0
|         |    +--- com.google.android.gms:play-services-basement:9.0.0 (*)
|         |    \--- com.google.android.gms:play-services-tasks:9.0.0
|         |         \--- com.google.android.gms:play-services-basement:9.0.0 (*)
|         \--- com.google.firebase:firebase-analytics-impl:9.0.0
|              +--- com.google.android.gms:play-services-base:9.0.0
|              |    +--- com.google.android.gms:play-services-basement:9.0.0 (*)
|              |    +--- com.google.firebase:firebase-common:9.0.0 (*)
|              |    \--- com.google.android.gms:play-services-tasks:9.0.0 (*)
|              +--- com.google.android.gms:play-services-basement:9.0.0 (*)
|              +--- com.google.firebase:firebase-iid:9.0.0
|              |    +--- com.google.android.gms:play-services-basement:9.0.0 (*)
|              |    \--- com.google.firebase:firebase-common:9.0.0 (*)
|              \--- com.google.firebase:firebase-common:9.0.0 (*)
\--- project :common-lib
(............)
</code>```

Runtime

```<code>debugAndroidTestRuntimeClasspath - Resolved configuration for runtime for variant: debugAndroidTest
+--- com.google.firebase:firebase-core:9.0.0 -> 11.6.0
|    \--- com.google.firebase:firebase-analytics:11.6.0
|         +--- com.google.android.gms:play-services-basement:11.6.0
|         |    +--- com.android.support:support-v4:25.2.0 -> 26.1.0
|         |    |    +--- com.android.support:support-compat:26.1.0
|         |    |    |    +--- com.android.support:support-annotations:26.1.0
|         |    |    |    \--- android.arch.lifecycle:runtime:1.0.0
|         |    |    |         +--- android.arch.lifecycle:common:1.0.0
|         |    |    |         \--- android.arch.core:common:1.0.0
|         |    |    +--- com.android.support:support-media-compat:26.1.0
|         |    |    |    +--- com.android.support:support-annotations:26.1.0
|         |    |    |    \--- com.android.support:support-compat:26.1.0 (*)
|         |    |    +--- com.android.support:support-core-utils:26.1.0
|         |    |    |    +--- com.android.support:support-annotations:26.1.0
|         |    |    |    \--- com.android.support:support-compat:26.1.0 (*)
|         |    |    +--- com.android.support:support-core-ui:26.1.0
|         |    |    |    +--- com.android.support:support-annotations:26.1.0
|         |    |    |    \--- com.android.support:support-compat:26.1.0 (*)
|         |    |    \--- com.android.support:support-fragment:26.1.0
|         |    |         +--- com.android.support:support-compat:26.1.0 (*)
|         |    |         +--- com.android.support:support-core-ui:26.1.0 (*)
|         |    |         \--- com.android.support:support-core-utils:26.1.0 (*)
|         |    \--- com.google.android.gms:play-services-basement-license:11.6.0
|         +--- com.google.firebase:firebase-common:11.6.0
|         |    +--- com.google.android.gms:play-services-basement:11.6.0 (*)
|         |    +--- com.google.android.gms:play-services-tasks:11.6.0
|         |    |    +--- com.google.android.gms:play-services-basement:11.6.0 (*)
|         |    |    \--- com.google.android.gms:play-services-tasks-license:11.6.0
|         |    \--- com.google.firebase:firebase-common-license:11.6.0
|         +--- com.google.firebase:firebase-analytics-impl:11.6.0
|         |    +--- com.google.android.gms:play-services-basement:11.6.0 (*)
|         |    +--- com.google.firebase:firebase-iid:11.6.0
|         |    |    +--- com.google.android.gms:play-services-basement:11.6.0 (*)
|         |    |    +--- com.google.firebase:firebase-common:11.6.0 (*)
|         |    |    +--- com.google.android.gms:play-services-tasks:11.6.0 (*)
|         |    |    \--- com.google.firebase:firebase-iid-license:11.6.0
|         |    +--- com.google.firebase:firebase-common:11.6.0 (*)
|         |    +--- com.google.android.gms:play-services-tasks:11.6.0 (*)
|         |    \--- com.google.firebase:firebase-analytics-impl-license:11.6.0
|         \--- com.google.firebase:firebase-analytics-license:11.6.0
\--- project :common-lib
(.............)
</code>```

Edited:

app dependencies

```<code>dependencies {
    implementation project(':common-lib')
}
</code>```

common-lib dependencies

```<code>dependencies {
    //android firebase
    implementation "com.google.firebase:firebase-core:$firebase_version"
    implementation "com.google.firebase:firebase-crash:$firebase_version"
    implementation "com.google.firebase:firebase-messaging:$firebase_version"
    implementation "com.google.firebase:firebase-ads:$firebase_version"
    //android support
    implementation "com.android.support:appcompat-v7:$support_version"
    implementation "com.android.support:design:$support_version"
    implementation "com.android.support:cardview-v7:$support_version"
    implementation "com.android.support:percent:$support_version"
    //others
    implementation 'com.google.code.gson:gson:2.8.0'
    implementation 'com.hannesdorfmann:adapterdelegates3:3.0.1'
    implementation 'net.danlew:android.joda:2.9.9'
    implementation 'org.ocpsoft.prettytime:prettytime:4.0.1.Final'
    implementation 'com.squareup.picasso:picasso:2.5.2'
    implementation 'com.github.simbiose:Encryption:2.0.1'

    //server
    implementation files('libs/xxx.jar')
    implementation files('libs/yyy.jar')
    implementation files('libs/zzz.jar')

    //tests
    testImplementation 'junit:junit:4.12'

}
</code>```

versions:

```<code>ext {
    firebase_version = '11.6.0'
    support_version = '26.1.0'
}
</code>```

答:
It appears that, previously, you were implicitly depending on the common-lib module to export Firebase SDKs to your app module.  Now that you've changed from "compile" to "implementation", you're no longer exporting those SDKs.  So, what's happening now is this: the google-services plugin is adding v9.0.0 of firebase-core to your app module since it no longer sees it present in the visible classpath of your app module.

You should be able to work around this by manually adding firebase-core to your app module at the correct version.  Or, you can continue to export Firebase SDKs from your library module to your app module by switching to an "api" dependency instead of an "implementation" dependency.

Body:
I migrated to Android Studio 3 and Gradle 4. Then I changed compile to implementation in my build.gradle files. But I get the error:

Error:Execution failed for task ':app:preDebugBuild'.
> Android dependency 'com.google.firebase:firebase-core' has different version for the compile (9.0.0) and runtime (11.6.0) classpath. You should manually set the same version via DependencyResolution

When I change implementation to api the error disappear. But this is not the solution. I have the app module and one library module. App build.gradle has only one dependency:

implementation project(':common-lib')

The apply plugin: 'com.google.gms.google-services' is correctly placed at the bottom of the app build.gradle file (the project worked before migration to Gradle 4)

Dependencies from gradlew app:dependencies (clipping of text):

Compile

debugAndroidTestCompileClasspath - Resolved configuration for compilation for variant: debugAndroidTest
+--- com.google.firebase:firebase-core:9.0.0
|    \--- com.google.firebase:firebase-analytics:9.0.0
|         +--- com.google.android.gms:play-services-basement:9.0.0
|         |    \--- com.android.support:support-v4:23.0.0
|         |         \--- com.android.support:support-annotations:23.0.0
|         +--- com.google.firebase:firebase-common:9.0.0
|         |    +--- com.google.android.gms:play-services-basement:9.0.0 (*)
|         |    \--- com.google.android.gms:play-services-tasks:9.0.0
|         |         \--- com.google.android.gms:play-services-basement:9.0.0 (*)
|         \--- com.google.firebase:firebase-analytics-impl:9.0.0
|              +--- com.google.android.gms:play-services-base:9.0.0
|              |    +--- com.google.android.gms:play-services-basement:9.0.0 (*)
|              |    +--- com.google.firebase:firebase-common:9.0.0 (*)
|              |    \--- com.google.android.gms:play-services-tasks:9.0.0 (*)
|              +--- com.google.android.gms:play-services-basement:9.0.0 (*)
|              +--- com.google.firebase:firebase-iid:9.0.0
|              |    +--- com.google.android.gms:play-services-basement:9.0.0 (*)
|              |    \--- com.google.firebase:firebase-common:9.0.0 (*)
|              \--- com.google.firebase:firebase-common:9.0.0 (*)
\--- project :common-lib
(............)

Runtime

debugAndroidTestRuntimeClasspath - Resolved configuration for runtime for variant: debugAndroidTest
+--- com.google.firebase:firebase-core:9.0.0 -> 11.6.0
|    \--- com.google.firebase:firebase-analytics:11.6.0
|         +--- com.google.android.gms:play-services-basement:11.6.0
|         |    +--- com.android.support:support-v4:25.2.0 -> 26.1.0
|         |    |    +--- com.android.support:support-compat:26.1.0
|         |    |    |    +--- com.android.support:support-annotations:26.1.0
|         |    |    |    \--- android.arch.lifecycle:runtime:1.0.0
|         |    |    |         +--- android.arch.lifecycle:common:1.0.0
|         |    |    |         \--- android.arch.core:common:1.0.0
|         |    |    +--- com.android.support:support-media-compat:26.1.0
|         |    |    |    +--- com.android.support:support-annotations:26.1.0
|         |    |    |    \--- com.android.support:support-compat:26.1.0 (*)
|         |    |    +--- com.android.support:support-core-utils:26.1.0
|         |    |    |    +--- com.android.support:support-annotations:26.1.0
|         |    |    |    \--- com.android.support:support-compat:26.1.0 (*)
|         |    |    +--- com.android.support:support-core-ui:26.1.0
|         |    |    |    +--- com.android.support:support-annotations:26.1.0
|         |    |    |    \--- com.android.support:support-compat:26.1.0 (*)
|         |    |    \--- com.android.support:support-fragment:26.1.0
|         |    |         +--- com.android.support:support-compat:26.1.0 (*)
|         |    |         +--- com.android.support:support-core-ui:26.1.0 (*)
|         |    |         \--- com.android.support:support-core-utils:26.1.0 (*)
|         |    \--- com.google.android.gms:play-services-basement-license:11.6.0
|         +--- com.google.firebase:firebase-common:11.6.0
|         |    +--- com.google.android.gms:play-services-basement:11.6.0 (*)
|         |    +--- com.google.android.gms:play-services-tasks:11.6.0
|         |    |    +--- com.google.android.gms:play-services-basement:11.6.0 (*)
|         |    |    \--- com.google.android.gms:play-services-tasks-license:11.6.0
|         |    \--- com.google.firebase:firebase-common-license:11.6.0
|         +--- com.google.firebase:firebase-analytics-impl:11.6.0
|         |    +--- com.google.android.gms:play-services-basement:11.6.0 (*)
|         |    +--- com.google.firebase:firebase-iid:11.6.0
|         |    |    +--- com.google.android.gms:play-services-basement:11.6.0 (*)
|         |    |    +--- com.google.firebase:firebase-common:11.6.0 (*)
|         |    |    +--- com.google.android.gms:play-services-tasks:11.6.0 (*)
|         |    |    \--- com.google.firebase:firebase-iid-license:11.6.0
|         |    +--- com.google.firebase:firebase-common:11.6.0 (*)
|         |    +--- com.google.android.gms:play-services-tasks:11.6.0 (*)
|         |    \--- com.google.firebase:firebase-analytics-impl-license:11.6.0
|         \--- com.google.firebase:firebase-analytics-license:11.6.0
\--- project :common-lib
(.............)

Edited:

app dependencies

dependencies {
    implementation project(':common-lib')
}

common-lib dependencies

dependencies {
    //android firebase
    implementation "com.google.firebase:firebase-core:$firebase_version"
    implementation "com.google.firebase:firebase-crash:$firebase_version"
    implementation "com.google.firebase:firebase-messaging:$firebase_version"
    implementation "com.google.firebase:firebase-ads:$firebase_version"
    //android support
    implementation "com.android.support:appcompat-v7:$support_version"
    implementation "com.android.support:design:$support_version"
    implementation "com.android.support:cardview-v7:$support_version"
    implementation "com.android.support:percent:$support_version"
    //others
    implementation 'com.google.code.gson:gson:2.8.0'
    implementation 'com.hannesdorfmann:adapterdelegates3:3.0.1'
    implementation 'net.danlew:android.joda:2.9.9'
    implementation 'org.ocpsoft.prettytime:prettytime:4.0.1.Final'
    implementation 'com.squareup.picasso:picasso:2.5.2'
    implementation 'com.github.simbiose:Encryption:2.0.1'

    //server
    implementation files('libs/xxx.jar')
    implementation files('libs/yyy.jar')
    implementation files('libs/zzz.jar')

    //tests
    testImplementation 'junit:junit:4.12'

}

versions:

ext {
    firebase_version = '11.6.0'
    support_version = '26.1.0'
}


问:
Are parameters to range() re-evaluated at each iteration of the loop?
If I use functions for range parameters, do they get called every time through?</p>

```<code>for i in range(min(some_list), max(other_list)):
    ...
</code>```

答:
As stack_n_queue answered in the comments:

No, calling for i in range(min(some_list), max(other_list)) will not result in the functions passed as arguments getting called on every iteration of range()

Body:
If I use functions for range parameters, do they get called every time through?

for i in range(min(some_list), max(other_list)):
    ...


答:
It becomes easy to answer your question with a little experiment.

```<code>In [294]: def foo(n):
     ...:     print('in foo')
     ...:     return n
     ...:

In [295]: for i in range(foo(5)):
     ...:     print(i)
     ...:
in foo
0
1
2
3
4
</code>```

So, yes, the parameters to range are evaluated only once, much like the parameters to any other function call.

Title: Are parameters to range() re-evaluated at each iteration of the loop?

Body:
It becomes easy to answer your question with a little experiment.

In [294]: def foo(n):
     ...:     print('in foo')
     ...:     return n
     ...:

In [295]: for i in range(foo(5)):
     ...:     print(i)
     ...:
in foo
0
1
2
3
4

So, yes, the parameters to range are evaluated only once, much like the parameters to any other function call.


问:
super.super.func()? - Java polymorphism
Say that I in Java have 3 classes, wheres the super one has a function named func(), I now make a subclass which overrides this, and a subclass to my subclass, now working on my sub-sub-class how will I call the 'func()' of the sub class, and the superclass?

I tried casting the 'this' "pointer", but Java 'fixes' it at runtime and calls the subsub func().

Edit:
Thanks everyone; 'Skeen is back at the drawing board'.

答: This isn't possible in Java. And btw. there aren't any pointers in Java.</p>

Title: super.super.func()? - Java polymorphism

OwnerDisplayName: anon


问:
Jenkins - how to NOT include any external environment variables when running shell script?
I've found a ton of information on how to include environment variables when running jenkins shell scripts, but I need to do the opposite. I need to start with a 'fresh' environment, and set/export everything in the script(s) I'm running. Is there any way to do this in jenkins? Specifically, jenkins scripted pipeline's sh step?</p>

答:
You could use env -i:

```<code>/usr/bin/env -i FIRST_VAR=1 SECOND_VAR=2 printenv
</code>```

Replace printenv with your program.

https://linux.die.net/man/1/env

Body:
You could use env -i:

/usr/bin/env -i FIRST_VAR=1 SECOND_VAR=2 printenv

Replace printenv with your program.

https://linux.die.net/man/1/env