问:
SQL Server Code Reuse Via Stored Procedures - Good or Bad Practice?
I'm currently considering design options for a reporting application based on an existing dataset.

There are several clear opportunities for code reuse given that many of the reports need to use the same base data set (Edited).

The tempation is to create some base stored procedure that I can reuse throughout this system, however, the contract I was on 6 months ago or so showed me what the down side of this practice - multiple layers of - large stored procedure calls returning subsets of data in, making it very very difficult to workout what was going on, debug and test.

I'm these days of the opinion that code reuse does not necessarily enhance maintainability in database design.

I'm looking for some insight on this from a more experienced SQL Server dev than myself?

Thanks in advance.

答:
Disclaimer: This isn't a "don't use stored procedures - think of the children!" post, and I'm not aiming to ignite a flame-war. I'm just suggesting code re-use is easier and possibly more suited to certain situations and platforms than others.

Code Reuse as a concept does generally improve a codebase. You keep things DRY and begin to form a layer of common functionality to solve common problems in the same way.

However like anything, one can get it wrong (with power comes responsibility blah blah blah).

It's relatively simple in most modern programming languages to reuse code, either by writing functions, or even creating whole frameworks that can be used again and again. However, in T-SQL it's tricksy because you have less options.  Stored procedures can do it, but you've seen how awkward they can be.

My personal preference is to keep business logic out of the database. That means I don't use views, UDFs, sprocs etc (unless after performance profiling we think we can speed something up using these techniques) and instead keep it in my application code. This often causes thoughts of a "business logic layer" but there are various flavours of that so it's probably a misnomer. It's certainly not code directly behind UI button click handlers and so on, though.

I aim to limit the database to storing and retrieving data, because that's what they're reaaally good at. We all know how clunky and outdated T-SQL can be as a language (think exception-handling, deployment, cursors etc). Being database-agnostic is completely impossible if your application is written into the database itself, and you also can't scale your application, because the database is the application. If you have that business logic in application code, it can be scaled out much more easily.

In this case the "business logic" is the queries and transformations used to generate your reports, and I would investigate how it might be possible to reuse code in your reporting tool/code, before considering other options.


来源: stackexchange

问:
why mapping result is undefined?
I'm trying get jSon from server and mapping it to the class in Angular 5 app.
Following is service method that working without errors:

```<code>getSearchResultTable(hash: number): Observable<Model.SearchResult.RootObject> {

    return this.http.get<Model.SearchResult.RootObject>('http://somelink/api/SearchResult/123')
    .map(res => new Model.SearchResult.RootObject());
    return tmp;
}
</code>```

following comoponent class:

```<code>export class SearchResultPageComponent implements OnInit {
  searchResult: Model.SearchResult.RootObject;

  constructor(private searchResultService: SearchResultService, private router: Router) { }

  ngOnInit(): void {
    this.searchResultService.getSearchResultTable(122).subscribe( data => {
      this.searchResult = data;
    });
    let t = this.searchResult;
  }
}
</code>```

The Model.SearchResult.RootObject is an complex object and i generate it by jSon on following service.

In all examples this method is described...but in my case this.searchResult is undefined. What i'm doing wrong?

UPDATE

Also I tried remove map and change the service method in a way:

```<code>getSearchResultTable(hash: number): Model.SearchResult.RootObject {
this.http.get<Model.SearchResult.RootObject>('http://somelink/api/SearchResult/123')
    .subscribe( data => {
        this.searchResult = data;
      });
    return this.searchResult;
}
</code>```

And component method like:

```<code>  ngOnInit(): void {
    this.searchResult = this.searchResultService.getSearchResultTable(122);
    }
</code>```

Service get next exception:

ReferenceError: data is not defined

at eval (eval at SearchResultService.getSearchResultTable (webpack-internal:///../../../../../src/app/search-module/services/search-result.service.ts),
:1:1)

at SearchResultService.getSearchResultTable (webpack-internal:///../../../../../src/app/search-module/services/search-result.service.ts:27:21)

at SearchResultPageComponent.ngOnInit (webpack-internal:///../../../../../src/app/search-module/pages/search-result/search-result.component.ts:23:54)

at checkAndUpdateDirectiveInline (webpack-internal:///../../../core/esm5/core.js:12291:19)

at checkAndUpdateNodeInline (webpack-internal:///../../../core/esm5/core.js:13794:20)

at checkAndUpdateNode (webpack-internal:///../../../core/esm5/core.js:13737:16)

at debugCheckAndUpdateNode (webpack-internal:///../../../core/esm5/core.js:14609:76)

at debugCheckDirectivesFn (webpack-internal:///../../../core/esm5/core.js:14550:13)

at Object.eval [as updateDirectives] (ng:///SearchModule/SearchResultPageComponent_Host.ngfactory.js:9:5)

at Object.debugUpdateDirectives [as updateDirectives] (webpack-internal:///../../../core/esm5/core.js:14535:21)

UPDATE

In my case following snippet is correct:

```<code>this.http.get<Model.SearchResult.RootObject>('http://someurl/api/SearchResult/123')
.subscribe( (data: Model.SearchResult.RootObject) => {
    this.searchResult = data;
  });
return this.searchResult;
</code>```

答: In angular 5 you don't need to use map you can directly covert your response in json form in the the subscribe method</p>

ContentLicense: CC BY-SA 3.0

Title: why mapping result is undefined?

Body:
I'm trying get jSon from server and mapping it to the class in Angular 5 app.
Following is service method that working without errors:

getSearchResultTable(hash: number): Observable<Model.SearchResult.RootObject> {

    return this.http.get<Model.SearchResult.RootObject>('http://somelink/api/SearchResult/123')
    .map(res => new Model.SearchResult.RootObject());
    return tmp;
}

following comoponent class:

export class SearchResultPageComponent implements OnInit {
  searchResult: Model.SearchResult.RootObject;

  constructor(private searchResultService: SearchResultService, private router: Router) { }

  ngOnInit(): void {
    this.searchResultService.getSearchResultTable(122).subscribe( data => {
      this.searchResult = data;
    });
    let t = this.searchResult;
  }
}

The Model.SearchResult.RootObject is an complex object and i generate it by jSon on following service.

In all examples this method is described...but in my case this.searchResult is undefined. What i'm doing wrong?

UPDATE

Also I tried remove map and change the service method in a way:

getSearchResultTable(hash: number): Model.SearchResult.RootObject {
this.http.get<Model.SearchResult.RootObject>('http://somelink/api/SearchResult/123')
    .subscribe( data => {
        this.searchResult = data;
      });
    return this.searchResult;
}

And component method like:

  ngOnInit(): void {
    this.searchResult = this.searchResultService.getSearchResultTable(122);
    }

Service get next exception:

ReferenceError: data is not defined

at eval (eval at SearchResultService.getSearchResultTable (webpack-internal:///../../../../../src/app/search-module/services/search-result.service.ts),
:1:1)

at SearchResultService.getSearchResultTable (webpack-internal:///../../../../../src/app/search-module/services/search-result.service.ts:27:21)

at SearchResultPageComponent.ngOnInit (webpack-internal:///../../../../../src/app/search-module/pages/search-result/search-result.component.ts:23:54)

at checkAndUpdateDirectiveInline (webpack-internal:///../../../core/esm5/core.js:12291:19)

at checkAndUpdateNodeInline (webpack-internal:///../../../core/esm5/core.js:13794:20)

at checkAndUpdateNode (webpack-internal:///../../../core/esm5/core.js:13737:16)

at debugCheckAndUpdateNode (webpack-internal:///../../../core/esm5/core.js:14609:76)

at debugCheckDirectivesFn (webpack-internal:///../../../core/esm5/core.js:14550:13)

at Object.eval [as updateDirectives] (ng:///SearchModule/SearchResultPageComponent_Host.ngfactory.js:9:5)

at Object.debugUpdateDirectives [as updateDirectives] (webpack-internal:///../../../core/esm5/core.js:14535:21)

UPDATE

In my case following snippet is correct:

this.http.get<Model.SearchResult.RootObject>('http://someurl/api/SearchResult/123')
.subscribe( (data: Model.SearchResult.RootObject) => {
    this.searchResult = data;
  });
return this.searchResult;


问:
Printing certain values using Collections.frequency()
I have an array as follows:

```<code>int[] array = {11, 14, 17, 11, 48, 33, 29, 11, 17, 22, 11, 48, 18};
</code>```

What I wanted to do was to find the duplicate values, and print them.

So my way of doing this was to convert to ArrayList, then to Set and use a stream on the Set.

```<code>ArrayList<Integer> list = new ArrayList<>(array.length);
for (int i = 0; i < array.length; i++) {
    list.add(array[i]);
}

Set<Integer> dup = new HashSet<>(list);
</code>```

I then used a stream to loop through it and print the values using Collections.frequency.

```<code>dup.stream().forEach((key) -> {
            System.out.println(key + ": " + Collections.frequency(list, key));
        });
</code>```

Which will of course print them all, even if the count is one.

I thought adding in if(key > 1) but it's the value I want not the key.

How can I get the value in this instance to print only where value > 2.

I could probably put in:

```<code>int check = Collections.frequency(list, key);
            if (check > 1) {
</code>```

but this then duplicates Collections.frequency(list, key) in the stream and is quite ugly.

答:
Probably you can to use filter to get only the values great than 2 :

```<code>dup.stream()
       .filter(t -> Collections.frequency(list, t) > 2)
       .forEach(key -> System.out.println(key + ": " + Collections.frequency(list, key)));
</code>```

result in your case is :

```<code>11: 4
</code>```

Edit

Another solution :

No need to use a Set or Collections.frequency you can just use :

```<code>Integer[] array = {11, 14, 17, 11, 48, 33, 29, 11, 17, 22, 11, 48, 18};
Arrays.stream(array).collect(Collectors.groupingBy(p -> p, Collectors.counting()))
        .entrySet().stream().filter(t -> t.getValue() > 1)
        .forEach(key -> System.out.println(key.getKey() + ": " + key.getValue()));
</code>```

Output

```<code>48: 2
17: 2
11: 4
</code>```

Body:
I have an array as follows:

int[] array = {11, 14, 17, 11, 48, 33, 29, 11, 17, 22, 11, 48, 18};

What I wanted to do was to find the duplicate values, and print them.

So my way of doing this was to convert to ArrayList, then to Set and use a stream on the Set.

ArrayList<Integer> list = new ArrayList<>(array.length);
for (int i = 0; i < array.length; i++) {
    list.add(array[i]);
}

Set<Integer> dup = new HashSet<>(list);

I then used a stream to loop through it and print the values using Collections.frequency.

dup.stream().forEach((key) -> {
            System.out.println(key + ": " + Collections.frequency(list, key));
        });

Which will of course print them all, even if the count is one.

I thought adding in if(key > 1) but it's the value I want not the key.

How can I get the value in this instance to print only where value > 2.

I could probably put in:

int check = Collections.frequency(list, key);
            if (check > 1) {

but this then duplicates Collections.frequency(list, key) in the stream and is quite ugly.

Body:
Probably you can to use filter to get only the values great than 2 :

dup.stream()
       .filter(t -> Collections.frequency(list, t) > 2)
       .forEach(key -> System.out.println(key + ": " + Collections.frequency(list, key)));

result in your case is :

11: 4

Edit

Another solution :

No need to use a Set or Collections.frequency you can just use :

Integer[] array = {11, 14, 17, 11, 48, 33, 29, 11, 17, 22, 11, 48, 18};
Arrays.stream(array).collect(Collectors.groupingBy(p -> p, Collectors.counting()))
        .entrySet().stream().filter(t -> t.getValue() > 1)
        .forEach(key -> System.out.println(key.getKey() + ": " + key.getValue()));

Output

48: 2
17: 2
11: 4


问:
Error parsing url fileld from JSON stream C#
I am trying to deserialze this json stream:

```<code>[{"id":11,"title":"xyz","image":{"url":"/uploads/xxx/yyy/11/pic_1234.jpg"},"target":1}]
</code>```

This is the simplified fragment of the code I am using to deserialze the stream:

```<code>public class Template
{
    [JsonProperty(PropertyName = "id")]
    public string Id { get; set; }

    [JsonProperty(PropertyName = "title")]
    public string Title { get; set; }

    [JsonProperty(PropertyName = "image")]
    public string Image { get; set; }

    [JsonProperty(PropertyName = "target")]
    public string Target { get; set; }
}

string url = @"http://my-url-here";

IList<Template> templates = new List<Template>();

using (var webClient = new WebClient())
{
    var json = webClient.DownloadString(url);
    templates = JsonConvert.DeserializeObject<List<Template>>(json);
    ...
}
</code>```

JsonConvert.DeserializeObject throws an exception parsing image field:

...Unexpected character encountered while parsing value: {. Path '[0].image',...

This is the full exception:

Newtonsoft.Json.JsonReaderException occurred
  HResult=0x80131500
  Message=Unexpected character encountered while parsing value: {. Path '[0].image', line 1, position 171.
  Source=Newtonsoft.Json
  StackTrace:
   at Newtonsoft.Json.JsonTextReader.ReadStringValue(ReadType readType)
   at Newtonsoft.Json.JsonTextReader.ReadAsString()
   at Newtonsoft.Json.JsonReader.ReadForType(JsonContract contract, Boolean hasConverter)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateList(IList list, JsonReader reader, JsonArrayContract contract, JsonProperty containerProperty, String id)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateList(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, Object existingValue, String id)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
   at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
   at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
   at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)
   at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value)
   at Promociones.JsonApi.GetTemplates() in C:\xxxxx...\Program.cs:line 19

答:
In the JSON fragment, the image property is not a string, but an object that contains the url string property.

Therefore, you should have the following model:

```<code>public class Image
{
    [JsonProperty(PropertyName = "url")]
    public string Url { get; set; }
}

public class Template
{
    [JsonProperty(PropertyName = "id")]
    public string Id { get; set; }

    [JsonProperty(PropertyName = "title")]
    public string Title { get; set; }

    [JsonProperty(PropertyName = "image")]
    public Image Image { get; set; }

    [JsonProperty(PropertyName = "target")]
    public string Target { get; set; }
}
</code>```

Body:
I am trying to deserialze this json stream:

[{"id":11,"title":"xyz","image":{"url":"/uploads/xxx/yyy/11/pic_1234.jpg"},"target":1}]

This is the simplified fragment of the code I am using to deserialze the stream:

public class Template
{
    [JsonProperty(PropertyName = "id")]
    public string Id { get; set; }

    [JsonProperty(PropertyName = "title")]
    public string Title { get; set; }

    [JsonProperty(PropertyName = "image")]
    public string Image { get; set; }

    [JsonProperty(PropertyName = "target")]
    public string Target { get; set; }
}

string url = @"http://my-url-here";

IList<Template> templates = new List<Template>();

using (var webClient = new WebClient())
{
    var json = webClient.DownloadString(url);
    templates = JsonConvert.DeserializeObject<List<Template>>(json);
    ...
}

JsonConvert.DeserializeObject throws an exception parsing image field:

...Unexpected character encountered while parsing value: {. Path '[0].image',...

This is the full exception:

Newtonsoft.Json.JsonReaderException occurred
  HResult=0x80131500
  Message=Unexpected character encountered while parsing value: {. Path '[0].image', line 1, position 171.
  Source=Newtonsoft.Json
  StackTrace:
   at Newtonsoft.Json.JsonTextReader.ReadStringValue(ReadType readType)
   at Newtonsoft.Json.JsonTextReader.ReadAsString()
   at Newtonsoft.Json.JsonReader.ReadForType(JsonContract contract, Boolean hasConverter)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateList(IList list, JsonReader reader, JsonArrayContract contract, JsonProperty containerProperty, String id)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateList(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, Object existingValue, String id)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
   at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
   at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
   at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)
   at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value)
   at Promociones.JsonApi.GetTemplates() in C:\xxxxx...\Program.cs:line 19

Body:
In the JSON fragment, the image property is not a string, but an object that contains the url string property.

Therefore, you should have the following model:

public class Image
{
    [JsonProperty(PropertyName = "url")]
    public string Url { get; set; }
}

public class Template
{
    [JsonProperty(PropertyName = "id")]
    public string Id { get; set; }

    [JsonProperty(PropertyName = "title")]
    public string Title { get; set; }

    [JsonProperty(PropertyName = "image")]
    public Image Image { get; set; }

    [JsonProperty(PropertyName = "target")]
    public string Target { get; set; }
}


问:
Android Google Map Alternate Route and Shortest Path
I have searched all over and I haven't found an answer. Similar to this
How can I change the color to the alternate route?  urlDestination +"&alternatives=true"
Adding that code will display the shortest route and alternate routes. Problem is, I don't know how to change the color of the alternate route to a specific color.
Example: Shortest route should be blue and alternate routes should be grey.
Help is much needed.

Something like this... that the alternate routes should be grey

答:
It's pretty straight forward. I believe you have a list or array of Routes.
Iterate through that to find the min distance index. (usually it's the first one, but just to make sure).

```<code>int minDistanceIndex = 0;
int minDistance = Integer.MAX_VALUE;
for(int i = 0; i < routes.size(); i++){
    Route route = routes.get(i);
    int distance = route.getDistanceValue();
    if(distance < minDistance){
       minDistance = distance;
       minDistanceIndex = i;
    }
}
</code>```

Now use the minDistanceIndex to show the default route(blue) and others as gray like below.

```<code>PolylineOptions lineOptions;
for (int i = 0; i < routes.size(); i++) {
    points = routes.get(i).getPoints();
    lineOptions = new PolylineOptions();
    // Adding all the points in the route to LineOptions
    lineOptions.addAll(points);
    if(minDistanceIndex != i) {
        lineOptions.width(15);
        lineOptions.color(ContextCompat.getColor(getActivity(), android.R.color.darker_gray));
    }
    lineOptions.clickable(true);
    // Drawing polyline in the Google Map for the i-th route
    if(map != null) {
        polylines.add(map.addPolyline(lineOptions));
        map.setOnPolylineClickListener(polylineListener);
    }
}
//finally draw the shortest route
lineOptions = new PolylineOptions();
lineOptions.width(18);
lineOptions.color(ContextCompat.getColor(getActivity(), android.R.color.holo_blue_dark));
// Drawing polyline in the Google Map for the i-th route
if(map != null) {
    polylines.add(map.addPolyline(lineOptions));
}
</code>```

You can add an on click listener to polylines to change the color when user selects another polyline just like in Google Maps.

IMP: You need to draw the shortest route at last cause otherwise part of that route can be overlapped by alternate route, hence leaving you with part blue and part gray route.

Hope this helps!

Body:
It's pretty straight forward. I believe you have a list or array of Routes.
Iterate through that to find the min distance index. (usually it's the first one, but just to make sure).

int minDistanceIndex = 0;
int minDistance = Integer.MAX_VALUE;
for(int i = 0; i < routes.size(); i++){
    Route route = routes.get(i);
    int distance = route.getDistanceValue();
    if(distance < minDistance){
       minDistance = distance;
       minDistanceIndex = i;
    }
}

Now use the minDistanceIndex to show the default route(blue) and others as gray like below.

PolylineOptions lineOptions;
for (int i = 0; i < routes.size(); i++) {
    points = routes.get(i).getPoints();
    lineOptions = new PolylineOptions();
    // Adding all the points in the route to LineOptions
    lineOptions.addAll(points);
    if(minDistanceIndex != i) {
        lineOptions.width(15);
        lineOptions.color(ContextCompat.getColor(getActivity(), android.R.color.darker_gray));
    }
    lineOptions.clickable(true);
    // Drawing polyline in the Google Map for the i-th route
    if(map != null) {
        polylines.add(map.addPolyline(lineOptions));
        map.setOnPolylineClickListener(polylineListener);
    }
}
//finally draw the shortest route
lineOptions = new PolylineOptions();
lineOptions.width(18);
lineOptions.color(ContextCompat.getColor(getActivity(), android.R.color.holo_blue_dark));
// Drawing polyline in the Google Map for the i-th route
if(map != null) {
    polylines.add(map.addPolyline(lineOptions));
}

You can add an on click listener to polylines to change the color when user selects another polyline just like in Google Maps.

IMP: You need to draw the shortest route at last cause otherwise part of that route can be overlapped by alternate route, hence leaving you with part blue and part gray route.

Hope this helps!


问:
Can only import win32com.client with IDLE. What extra work do i need to set up pywin32?
I have a Tkinter program that i use for time management.  I decided to have it scan my inbox in outlook to check emails for tags, and then based on the tag, add it to my list of tasks to do for the night.

The code i wrote works just fine, but i'm getting an error when I import win32com.client.  I can import it in IDLE, but it is having problems importing when i try to run the code with a .bat file, or double clicking the .py file.

I have found several people with similar problems, but from what i can tell, it's having problems with win32api module, or pywin32

```<code>Traceback (most recent call last):
    File "my_program_filename.py", line 1, in <module>
import win32com.client
    File "c:/Python27/lib/site-packages/win32com/__init__.py", line 5, in <module>
import win32api, sys, os
ImportError:  DLL load failed: The specified module could not be found
</code>```

I'm really confused.  When i get the sys.path it's the same with IDLE as it is running from the .py file with the exception of an added "c:/users/username/desktop/timer" for my .py file.

I'm really lost and haven't had to mess with the system path, but I'm not able to figure out what i need to do to fix this.

What do I need to do to get pywin32 working so I can use win32com.client?

Any help is greatly appreciated.  Thanks!

答:
in my case typing in cmd:
python C:\Python27\Scripts\pywin32_postinstall.py -install

I hope this helps

Body:
I have a Tkinter program that i use for time management.  I decided to have it scan my inbox in outlook to check emails for tags, and then based on the tag, add it to my list of tasks to do for the night.

The code i wrote works just fine, but i'm getting an error when I import win32com.client.  I can import it in IDLE, but it is having problems importing when i try to run the code with a .bat file, or double clicking the .py file.

I have found several people with similar problems, but from what i can tell, it's having problems with win32api module, or pywin32

Traceback (most recent call last):
    File "my_program_filename.py", line 1, in <module>
import win32com.client
    File "c:/Python27/lib/site-packages/win32com/__init__.py", line 5, in <module>
import win32api, sys, os
ImportError:  DLL load failed: The specified module could not be found

I'm really confused.  When i get the sys.path it's the same with IDLE as it is running from the .py file with the exception of an added "c:/users/username/desktop/timer" for my .py file.

I'm really lost and haven't had to mess with the system path, but I'm not able to figure out what i need to do to fix this.

What do I need to do to get pywin32 working so I can use win32com.client?

Any help is greatly appreciated.  Thanks!


问:
DataGrid.BeginningEdit event not firing when I use TextBox in DataGridTemplateColumn.CellTemplate
I want to show data in data grid. And only some of the cells in a column can be edited.So, for this purpose I defined the Column template for one column as shown below:

```<code><DataGridTemplateColumn>
  <DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
      <TextBox IsReadOnly="{Binding IsReadOnly}"  BorderThickness="0" Text="{Binding Value, UpdateSourceTrigger= LostFocus}"></TextBox>
   </DataTemplate>
  </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</code>```

So, depending upon the read only property of the model object, cell will be editable or not.This is working great.But now I want to perform some operation when user starts editing the cell, so I created a handler for the BeginningEdit event for the DataGrid.But the event handler is not getting called.I replaced the TextBox with DataGridCell.Now, the event handler is called, but I can't edit the cell value.So, how do I solve this issue.

答:
It is the CellEditingTemplate that is applied when the cell is put into edit mode, which is when the BeginningEdit event occurs, so you should add your TextBox to this one:

```<code><DataGridTemplateColumn>
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Value}"></TextBlock>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
    <DataGridTemplateColumn.CellEditingTemplate>
        <DataTemplate>
            <TextBox IsReadOnly="{Binding IsReadOnly}"  BorderThickness="0"
                     Text="{Binding Value, UpdateSourceTrigger= LostFocus}"></TextBox>
        </DataTemplate>
    </DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
</code>```

Body:
I want to show data in data grid. And only some of the cells in a column can be edited.So, for this purpose I defined the Column template for one column as shown below:

<DataGridTemplateColumn>
  <DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
      <TextBox IsReadOnly="{Binding IsReadOnly}"  BorderThickness="0" Text="{Binding Value, UpdateSourceTrigger= LostFocus}"></TextBox>
   </DataTemplate>
  </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

So, depending upon the read only property of the model object, cell will be editable or not.This is working great.But now I want to perform some operation when user starts editing the cell, so I created a handler for the BeginningEdit event for the DataGrid.But the event handler is not getting called.I replaced the TextBox with DataGridCell.Now, the event handler is called, but I can't edit the cell value.So, how do I solve this issue.

Body:
It is the CellEditingTemplate that is applied when the cell is put into edit mode, which is when the BeginningEdit event occurs, so you should add your TextBox to this one:

<DataGridTemplateColumn>
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Value}"></TextBlock>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
    <DataGridTemplateColumn.CellEditingTemplate>
        <DataTemplate>
            <TextBox IsReadOnly="{Binding IsReadOnly}"  BorderThickness="0"
                     Text="{Binding Value, UpdateSourceTrigger= LostFocus}"></TextBox>
        </DataTemplate>
    </DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>


答:
In Your JSon Stream You have part

```<code>"image": {"url":"/uploads/xxx/yyy/11/pic_1234.jpg"}
</code>```

and it means that You try to deserialize not string but an object which could be described as

```<code>public class ImagePath {
     [JsonProperty(PropertyName = "url")]
     public string Url { get; set; }
}
</code>```

and In Your deserialized class

```<code>[JsonProperty(PropertyName = "image")]
public ImagePath Image { get; set; }
</code>```

Title: Error parsing url fileld from JSON stream C#

Body:
In Your JSon Stream You have part

"image": {"url":"/uploads/xxx/yyy/11/pic_1234.jpg"}

and it means that You try to deserialize not string but an object which could be described as

public class ImagePath {
     [JsonProperty(PropertyName = "url")]
     public string Url { get; set; }
}

and In Your deserialized class

[JsonProperty(PropertyName = "image")]
public ImagePath Image { get; set; }


问:
How do I include my company's global styles CDN (for dev use) using Webpack, within a Vue cli project?
I've tried importing via the entry file (main.js)...

```<code>import Vue from 'vue'
import App from '@/App'
import router from '@/router/router'
import store from '@/store/store'
import BootstrapVue from 'bootstrap-vue'
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'
import { Popover } from 'bootstrap-vue/es/directives'
import 'https://mycompany/main.min.css'

Vue.use(BootstrapVue)
Vue.use(Popover)

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  store,
  router,
  template: '<App/>',
  components: { App }
})
</code>```

I've tried to find a place within webpack.base.config (externals or publicPath) via numerous posts online - but none answered my question enough to make it work...

The css file delivered over the CDN essentially uses (and thus overwrites) Bootstrap classes, so it needs to be injected into the  after Bootstrap - can I do this with my current setup? Vue/Webpack.. or do i need a task runner like Gulp? It's not enough to inject the cdn once we've built the project and have dist files.. we need to see the style changes whilst dev's work on the project.
Is there an easier way than either of those 2 methods, and before anyone asks - no.. they won't make it an npm package due to privacy/security.

答:
The easy way would be to just include it in your index.html after all other Styles.
Btw: you can publish private repos on npm.</p>

Body:
I've tried importing via the entry file (main.js)...

import Vue from 'vue'
import App from '@/App'
import router from '@/router/router'
import store from '@/store/store'
import BootstrapVue from 'bootstrap-vue'
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'
import { Popover } from 'bootstrap-vue/es/directives'
import 'https://mycompany/main.min.css'

Vue.use(BootstrapVue)
Vue.use(Popover)

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  store,
  router,
  template: '<App/>',
  components: { App }
})

I've tried to find a place within webpack.base.config (externals or publicPath) via numerous posts online - but none answered my question enough to make it work...

The css file delivered over the CDN essentially uses (and thus overwrites) Bootstrap classes, so it needs to be injected into the  after Bootstrap - can I do this with my current setup? Vue/Webpack.. or do i need a task runner like Gulp? It's not enough to inject the cdn once we've built the project and have dist files.. we need to see the style changes whilst dev's work on the project.
Is there an easier way than either of those 2 methods, and before anyone asks - no.. they won't make it an npm package due to privacy/security.


问:
How to use format() on a moment.js duration?
Is there any way I can use the moment.js format method on duration objects?  I can't find it anywhere in the docs and it doesn't seen to be an attribute on duration objects.

I'd like to be able to do something like:

```<code>var diff = moment(end).unix() - moment(start).unix();
moment.duration(diff).format('hh:mm:ss')
</code>```

Also, if there are any other libraries which can easily accommodate this sort of functionality, I'd be interested in recommendations.

Thanks!

答:
If all hours must be displayed (more than 24) and if '0' before hours is not necessary, then formatting can be done with a short line of code:</p>

```<code>Math.floor(duration.as('h')) + moment.utc(duration.as('ms')).format(':mm:ss')
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Is there any way I can use the moment.js format method on duration objects?  I can't find it anywhere in the docs and it doesn't seen to be an attribute on duration objects.

I'd like to be able to do something like:

var diff = moment(end).unix() - moment(start).unix();
moment.duration(diff).format('hh:mm:ss')

Also, if there are any other libraries which can easily accommodate this sort of functionality, I'd be interested in recommendations.

Thanks!

Body:
If all hours must be displayed (more than 24) and if '0' before hours is not necessary, then formatting can be done with a short line of code:

Math.floor(duration.as('h')) + moment.utc(duration.as('ms')).format(':mm:ss')


问:
Flip Up Animation
I'm trying to make a flipping animation in Android.
I am using this code:

```<code><set xmlns:android="http://schemas.android.com/apk/res/android">
  <!-- Set alpha to 0 before animation -->
  <objectAnimator
    android:valueFrom="1.0"
    android:valueTo="0.0"
    android:propertyName="alpha"
    android:duration="0"/>

  <!-- Rotate -->
  <objectAnimator
    android:valueFrom="180"
    android:valueTo="0"
    android:propertyName="rotationY"
    android:interpolator="@android:interpolator/accelerate_decelerate"
    android:duration="@integer/card_flip_time_full"/>

  <!-- Half-way through the rotation set the alpha to 1 -->
  <objectAnimator
    android:valueFrom="0.0"
    android:valueTo="1.0"
    android:propertyName="alpha"
    android:startOffset="@integer/card_flip_time_half"
    android:duration="1"/>
</set>
</code>```

However, I want it to flip from top to bottom. Something like this:

How do I do this?

答:
You can do it programmatically. Here is the C# from Xamarin. Can't test the Java right now but it will be very similar.</p>

```<code>ImageView block = FindViewById<ImageView>(Resource.Id.imgBlock);
ObjectAnimator blockSpin = ObjectAnimator.OfFloat(block, "rotationX", 0, 360);
imageCard.PivotX = 0.5f; //so it spins on center

float scale = metrics.Density;
imageCard.SetCameraDistance(8000*scale);
  /*Set camera distance as required to avoid distortion.
     Multiplying by scale keeps distance the same across devices. */
blockSpin.SetDuration(500);
blockSpin.Start();
</code>```

Title: Flip Up Animation

Body:
I'm trying to make a flipping animation in Android.
I am using this code:

<set xmlns:android="http://schemas.android.com/apk/res/android">

  <objectAnimator
    android:valueFrom="1.0"
    android:valueTo="0.0"
    android:propertyName="alpha"
    android:duration="0"/>

  <objectAnimator
    android:valueFrom="180"
    android:valueTo="0"
    android:propertyName="rotationY"
    android:interpolator="@android:interpolator/accelerate_decelerate"
    android:duration="@integer/card_flip_time_full"/>

  <objectAnimator
    android:valueFrom="0.0"
    android:valueTo="1.0"
    android:propertyName="alpha"
    android:startOffset="@integer/card_flip_time_half"
    android:duration="1"/>
</set>

However, I want it to flip from top to bottom. Something like this:

How do I do this?

Body:
You can do it programmatically. Here is the C# from Xamarin. Can't test the Java right now but it will be very similar.

ImageView block = FindViewById<ImageView>(Resource.Id.imgBlock);
ObjectAnimator blockSpin = ObjectAnimator.OfFloat(block, "rotationX", 0, 360);
imageCard.PivotX = 0.5f; //so it spins on center

float scale = metrics.Density;
imageCard.SetCameraDistance(8000*scale);
  /*Set camera distance as required to avoid distortion.
     Multiplying by scale keeps distance the same across devices. */
blockSpin.SetDuration(500);
blockSpin.Start();


问:
Accordion open next on button click
Hi been searching for few days now but couldnt find anything. I have an accordion that has three accordion group, I have added a button to open the next accordion but cant seem to get it working. Can some one please help. here is what I have so far

```<code><accordion [closeOthers]="true" style="margin-top:5px;">
        <accordion-group *ngFor="let registration of registrationArray; let i = index" #groupval style="margin-top:5px;" [isOpen]="registration.isAccordionOpen">
          <div accordion-heading style="width:100%;">
            Registrant No. {{i + 1}}
            <i class="pull-right float-xs-right glyphicon"
               [ngClass]="{'glyphicon-chevron-down': groupval?.isOpen, 'glyphicon-chevron-up': !groupval?.isOpen}"></i>
          </div>
          <form [formGroup]="myGroup" (ngSubmit)="gotoAddons(myDetails)">
            <div formArrayName="myDetails">
              <div class="panel-body" [formGroupName]="i">
                <div style="padding-top:20px;clear:both;">
                  <div style="width:100%;background-color:#578ebe;border: 1px solid #7ca7cc;">
                    Your Address
                  </div>
                  <div style="padding-top:30px;clear:both;">
                    <div style="width:100%">
                      <div style="float:left;width:30%;text-align:right;">
                        <span class="required">*</span><label>Address Line 1</label>
                      </div>
                      <div style="float:left;width:70%;padding-left:10px;">
                        <input autofocus class="form-control" type="text" id="address" name="address" formControlName="address" required>
                        <div *ngIf="myGroup.controls.myDetails.controls[i].controls.address.errors && (myGroup.controls.myDetails.controls[i].controls.address.dirty || myGroup.controls.myDetails.controls[i].controls.address.touched || submitted)" class="alert alert-danger">
                          <div [hidden]="!myGroup.controls.myDetails.controls[i].controls.address.errors.required">
                            Address Line 1 is required!
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                <div style="width:100%;" *ngIf="i < registrationArray.length - 1">
                  <div style="float:right;">
                    <button (click)="groupval.isOpen = !groupval.isOpen" class="btn green">Open next tab</button>
                  </div>
                </div>
                <div style="width:100%;"  *ngIf="i == registrationArray.length - 1" >
                  <div style="float:right;">
                    <button type="submit" class="btn green">Continue</button>
                  </div>
                </div>
               </div>
            </div>
          </form>
        </accordion-group>
      </accordion>
</code>```

Removed some code for clarification. Can some one please let me know how I can open the next accordion group on the button click. Thanks in advance

Here is a working example

plunkr

stackblitz link

stackblitz

答:
In your case I see that you're actually just closing the opened panel and that's all. Along with this you need to open a next panel which can be done by setting its isOpen property to true.
A small plunkr with test implementation - https://stackblitz.com/edit/ngx-bootstrap-ifmpph?file=app/app.component.html

Title: Accordion open next on button click

Body:
Hi been searching for few days now but couldnt find anything. I have an accordion that has three accordion group, I have added a button to open the next accordion but cant seem to get it working. Can some one please help. here is what I have so far

<accordion [closeOthers]="true" style="margin-top:5px;">
        <accordion-group *ngFor="let registration of registrationArray; let i = index" #groupval style="margin-top:5px;" [isOpen]="registration.isAccordionOpen">

            Registrant No. {{i + 1}}

          <form [formGroup]="myGroup" (ngSubmit)="gotoAddons(myDetails)">

                    Your Address

                        *Address Line 1

                        <input autofocus class="form-control" type="text" id="address" name="address" formControlName="address" required>

                            Address Line 1 is required!

                <div style="width:100%;" *ngIf="i < registrationArray.length - 1">

                    <button (click)="groupval.isOpen = !groupval.isOpen" class="btn green">Open next tab</button>

                    <button type="submit" class="btn green">Continue</button>

          </form>
        </accordion-group>
      </accordion>

Removed some code for clarification. Can some one please let me know how I can open the next accordion group on the button click. Thanks in advance

Here is a working example

plunkr

stackblitz link

stackblitz


问:
can we make multi color gradient in xml for android background?
I have been trying to make a multi-color background in XML but there only 3 option available start, center, end and specified angles. Can't we make backgrounds like this below..

Can we make like this background in android ??

答: You can do it with layer-list of radial gradients, then you set different opacity for different items</p>


问:
How to add role to user?
We used Yii2 framework last alpha. Role for user already created but problem is how it assign to user. Documentation is absent. </p>

答:
A really simple way to achieve an admin role is to add this to your controller:

```<code>use yii;
/**
 * @inheritdoc
 */
public function behaviors()
{
    return [
        'access' => [
            'class' => AccessControl::className(),
            'rules' => [
                [
                    'allow' => true,
                    'actions' => ['index'],
                    'roles' => ['@'],
                ],
                [
                    'allow' => !Yii::$app->user->isGuest && Yii::$app->user->identity->isAdmin(),
                    'actions' => ['view', 'create', 'update', 'delete'],
                ],
            ],
        ],
    ];
}
</code>```

Then add to your User model an isAdmin() which returns true for your admin user(s) and false for everyone else. Personally, I use:

```<code>public function isAdmin() {
    return Self::ROLE_ADMIN === $this->role;
}
</code>```

Admittedly, this is not "by the book". But it is simple, quick and effective.

Title: How to add role to user?

Body:
A really simple way to achieve an admin role is to add this to your controller:

use yii;
/**
 * @inheritdoc
 */
public function behaviors()
{
    return [
        'access' => [
            'class' => AccessControl::className(),
            'rules' => [
                [
                    'allow' => true,
                    'actions' => ['index'],
                    'roles' => ['@'],
                ],
                [
                    'allow' => !Yii::$app->user->isGuest && Yii::$app->user->identity->isAdmin(),
                    'actions' => ['view', 'create', 'update', 'delete'],
                ],
            ],
        ],
    ];
}

Then add to your User model an isAdmin() which returns true for your admin user(s) and false for everyone else. Personally, I use:

public function isAdmin() {
    return Self::ROLE_ADMIN === $this->role;
}

Admittedly, this is not "by the book". But it is simple, quick and effective.


问:
Extended JTable clipping problem
Hi I'm using set of classes I found on internet that extends JTable capabilities making me able to merge or split some cells.

Mentioned capability works ok but I have two problems with how the table is displayed. The extended JTable is stored in JScrollPane and it is stored in Box.

The first issue is that when I have a lot of collumns the last one or last two ( depends on how many collumns I have ) is being clipped ( when I move scrollbar to the right edge I don't see last collumn or it is clipped so only the part of the data is visible.)

I did some experiments and I add some empty collumns and that helped so I assume it is something connected with how JScrollPane gets the width of the table it should display but I could not figure out how can I change that. I was trying to call table_.setPreferredScrollableViewportSize(new Dimension()); with Dimentsion set to something really big but it did not help.

Second issue is that when I click on a cell that is placed closer to the right edge then the next cell is being selected. The further the cell is from the left edge the further cell to its right is being selected. I can't see selection when I click on the cell from last collumn.

答: If there is no easy answer maybe someone knows some open source alternative to display data in table with merging capabilities. I found only commercial ones which cost a lot of money.</p>

ContentLicense: CC BY-SA 2.5

Title: Extended JTable clipping problem


问:
Set Timeout and NgZone in Angular
I saw the following today in my code base and am trying to wrap my head around what it could be doing:

```<code>public ngOnInit(): void {
    this.siteTitle = this.modalService.site ? this.modalService.site.siteTitle : null;
        setTimeout(() => {
            if (!this.modalService.site) {
                this.ngZone.run(() => {
                    this.modalService.close();
                });
            }
        }, 0);
}
</code>```

I've been reading some articles such as this one but still would like some clarification. I know that because the setTimeout parameter is 0 it will still be placed into the event queue and will execute once all other non-JS pieces are finished.

Thanks

答:
I think the blog which you have pointed out is the most appropriate that you could get.

NgZone enables us to explicitly run certain code outside Angular’s
  Zone, preventing Angular to run any change detection. So basically,
  handlers will still be executed, but since they won’t run inside
  Angular’s Zone, Angular won’t get notified that a task is done and
  therefore no change detection will be performed. We only want to run
  change detection once we release the box we are dragging.

As you have already pointed out that you know why you are using setTimeout the confusion should be solves by reading these lines again once more.

The reason he is trying to use setTimeOut is because he wants to avoid getting the error

ExpressionChangedAfterItHasBeenCheckedError

which occurs when you try and change the value of the variable before Angular change detection completes

credits - https://blog.angularindepth.com/everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror-error-e3fd9ce7dbb4

https://blog.thoughtram.io/angular/2017/02/21/using-zones-in-angular-for-better-performance.html

Title: Set Timeout and NgZone in Angular

Body:
I saw the following today in my code base and am trying to wrap my head around what it could be doing:

public ngOnInit(): void {
    this.siteTitle = this.modalService.site ? this.modalService.site.siteTitle : null;
        setTimeout(() => {
            if (!this.modalService.site) {
                this.ngZone.run(() => {
                    this.modalService.close();
                });
            }
        }, 0);
}

I've been reading some articles such as this one but still would like some clarification. I know that because the setTimeout parameter is 0 it will still be placed into the event queue and will execute once all other non-JS pieces are finished.

Thanks


答:
You can use Filter :</p>

```<code>dup.stream().filter(key -> Collections.frequency(list,key)>2).forEach(System.out::println);
</code>```

Title: Printing certain values using Collections.frequency()

Body:
I have an array as follows:

int[] array = {11, 14, 17, 11, 48, 33, 29, 11, 17, 22, 11, 48, 18};

What I wanted to do was to find the duplicate values, and print them.

So my way of doing this was to convert to ArrayList, then to Set and use a stream on the Set.

ArrayList<Integer> list = new ArrayList<>(array.length);
for (int i = 0; i < array.length; i++) {
    list.add(array[i]);
}

Set<Integer> dup = new HashSet<>(list);

I then used a stream to loop through it and print the values using Collections.frequency.

dup.stream().forEach((key) -> {
            System.out.println(key + ": " + Collections.frequency(list, key));
        });

Which will of course print them all, even if the count is one.

I thought adding in if(key > 1) but it's the value I want not the key.

How can I get the value in this instance to print only where value > 2.

I could probably put in:

int check = Collections.frequency(list, key);
            if (check > 1) {

but this then duplicates Collections.frequency(list, key) in the stream and is quite ugly.

Body:
You can use Filter :

dup.stream().filter(key -> Collections.frequency(list,key)>2).forEach(System.out::println);


问:
Access items from a ListView ItemSource in Xamarin
I have the following ListView and associated template:

```<code>listView = new ListView()
        {
            ItemTemplate = dtemplate
        };
        listView.SetBinding(ListView.ItemsSourceProperty, new Binding("Items"));

var dtemplate = new DataTemplate(() =>
        {
            var stacklayout = new StackLayout()
            {
                Orientation = StackOrientation.Horizontal
            };
            var lbl = new Label();
            lbl.SetBinding(Label.TextProperty, new Binding("Title")); //<-- this
            stacklayout.Children.Add(lbl);
            return new ViewCell { View = stacklayout };
        });
</code>```

Referring to the line marked "//<-- this", How do I set the binding programmatically without using a text literal, is there no way?

答: you can use nameof(SomeProperty) to get the Property name as a string

Body:
I have the following ListView and associated template:

listView = new ListView()
        {
            ItemTemplate = dtemplate
        };
        listView.SetBinding(ListView.ItemsSourceProperty, new Binding("Items"));

var dtemplate = new DataTemplate(() =>
        {
            var stacklayout = new StackLayout()
            {
                Orientation = StackOrientation.Horizontal
            };
            var lbl = new Label();
            lbl.SetBinding(Label.TextProperty, new Binding("Title")); //<-- this
            stacklayout.Children.Add(lbl);
            return new ViewCell { View = stacklayout };
        });

Referring to the line marked "//<-- this", How do I set the binding programmatically without using a text literal, is there no way?


问:
Stacking ternary operators in BASH
Yes this is a question, but let me give a little back story first. Someone in a forum that I frequent said BASH scripts are stupid little tricks to make idiots look good. Now I'm not a BASH programmer, but I wanted to have the title "I told you so" and prove that with consistence, persistence, and insistence, anything can be achieved.

So this is really nothing that is for an active project, or anything that I really have no need for but to prove that it can be done. I also understand that I can use python, java, ruby, etc, etc, etc... I just want to continue learning.

Obviously although BASH doesn't truly have a ternary support it can be achieved with something like this:

```<code>varA=$([ "varB" == "true" ] && echo "$OKSYMB" || echo "$BADSYMB")
</code>```

Basically just like it looks varA will be $OKSYMB if true anything else would be the $BADSYMB - There are 1000's of examples all over the interwebs. But here is where my question comes in, what if there are 3 flags, and I understand I can (which I have already done it this way) do it this way:

```<code>case "$webservermenustatus" in
     "disabled") webservermenuicon="$DISABLEDSYMB";;
     "true") webservermenuicon="$OKSYMB";;
     "false") webservermenuicon="$BADSYMB";;
esac
</code>```

I would love to do it this way:

```<code>webservermenuicon=$([ "$webservermenustatus" == "true" ] && echo -e "$OKSYMB" || [ "$webservermenustatus" == "false" ] && echo -e "$BADSYMB" || echo -e "$DISABLEDSYMB")
</code>```

Oddly enough it kinda works, although the $OKSYMB cuts off everything after the variable. The other 2 works great.

I have attached 5 images notice image number 3 versus 4 and 5.

the switch code https://image.ibb.co/mhm4oR/theswitchcode.png

the display code https://image.ibb.co/chQx8R/thedisplaycode.png

the true icon https://image.ibb.co/dqK2a6/truemenu.png

the false icon https://image.ibb.co/i1GR2m/falsemenu.png

the disabled icon. https://image.ibb.co/f5aav6/disabledmenu.png

The green OK just cuts off the rest of the Menu item title?

I understand that the case works, I can use IF THEN ELIF FI, I can set everything to TRUE and then separate the difference between FALSE and DISABLED, this was more to see if anyone has figured out BASH stacked ternary operators.

答:
Actually, I just figured it out with this little script:

```<code>#!/bin/bash

status=$1

switchstatus=$([ "$status" == "true" ] && echo "TRUE" || ([ "$status" == "false" ] && echo "FALSE" || echo "DISABLED"))

echo "You have made a $switchstatus choice in your life"
</code>```

I needed to place the second part of the ternary in () -- Now to explain why this is happening, when you are echo'ing the result back to the variable, without the parentheses it is responding with

You have made a TRUE
FALSE choice in your life

Which is sending both the TRUE and the next && together
once it is separated with (), it will then only send the first set of && to the variable.

-- Sometimes simplicity is your enemy :)

Title: Stacking ternary operators in BASH

Body:
Yes this is a question, but let me give a little back story first. Someone in a forum that I frequent said BASH scripts are stupid little tricks to make idiots look good. Now I'm not a BASH programmer, but I wanted to have the title "I told you so" and prove that with consistence, persistence, and insistence, anything can be achieved.

So this is really nothing that is for an active project, or anything that I really have no need for but to prove that it can be done. I also understand that I can use python, java, ruby, etc, etc, etc... I just want to continue learning.

Obviously although BASH doesn't truly have a ternary support it can be achieved with something like this:

varA=$([ "varB" == "true" ] && echo "$OKSYMB" || echo "$BADSYMB")

Basically just like it looks varA will be $OKSYMB if true anything else would be the $BADSYMB - There are 1000's of examples all over the interwebs. But here is where my question comes in, what if there are 3 flags, and I understand I can (which I have already done it this way) do it this way:

case "$webservermenustatus" in
     "disabled") webservermenuicon="$DISABLEDSYMB";;
     "true") webservermenuicon="$OKSYMB";;
     "false") webservermenuicon="$BADSYMB";;
esac

I would love to do it this way:

webservermenuicon=$([ "$webservermenustatus" == "true" ] && echo -e "$OKSYMB" || [ "$webservermenustatus" == "false" ] && echo -e "$BADSYMB" || echo -e "$DISABLEDSYMB")

Oddly enough it kinda works, although the $OKSYMB cuts off everything after the variable. The other 2 works great.

I have attached 5 images notice image number 3 versus 4 and 5.

the switch code https://image.ibb.co/mhm4oR/theswitchcode.png

the display code https://image.ibb.co/chQx8R/thedisplaycode.png

the true icon https://image.ibb.co/dqK2a6/truemenu.png

the false icon https://image.ibb.co/i1GR2m/falsemenu.png

the disabled icon. https://image.ibb.co/f5aav6/disabledmenu.png

The green OK just cuts off the rest of the Menu item title?

I understand that the case works, I can use IF THEN ELIF FI, I can set everything to TRUE and then separate the difference between FALSE and DISABLED, this was more to see if anyone has figured out BASH stacked ternary operators.

Body:
Actually, I just figured it out with this little script:

#!/bin/bash

status=$1

switchstatus=$([ "$status" == "true" ] && echo "TRUE" || ([ "$status" == "false" ] && echo "FALSE" || echo "DISABLED"))

echo "You have made a $switchstatus choice in your life"

I needed to place the second part of the ternary in () -- Now to explain why this is happening, when you are echo'ing the result back to the variable, without the parentheses it is responding with

You have made a TRUE
FALSE choice in your life

Which is sending both the TRUE and the next && together
once it is separated with (), it will then only send the first set of && to the variable.

-- Sometimes simplicity is your enemy :)


问:
Is there a way in C# to trigger a onclick() event and still be able to detect onDrag() event while still holding mouse click down
I tried the dragOver event handler but it didn't work as it should.

I am working on a piano and I want to be able to play the note even if the mousedown didn't happen on that key.

Is there an event handler for this?

The below is a picture of the piano I am working on.

答:
When the MouseUp event goes off, you can check if the mouse is over another button. If it is, then perform a click on that button. I took the GetCursorPosition code from an answer in this question.

Had to put true and false into button tags to be able to tell if the ButtonClick was already handled for that button or not.

```<code>// running as Console window
// output from...
// 1. clicking and releasing on button1
// 2. clicking and holding on button1 and then releasing not over button1 or button2,
// 3. clicking and holding on button1 and then
// moving mouse to over button2 and releasing mouse.

// button1 Click
// button1 Ding!
// button1 MouseUp
// button1 MouseUp
// button1 Ding!
// button1 MouseUp
// button1 Ding!
// button2 Click
// button2 Ding!

private List<Button> _buttons { get; set; }

public Form1()
{
    InitializeComponent();

    button1.MouseUp += Button_MouseUp;
    button2.MouseUp += Button_MouseUp;

    button1.Click += Button_Click;
    button2.Click += Button_Click;

    button1.Tag = false;
    button2.Tag = false;

    _buttons = new List<Button>()
    {
        button1, button2
    };
}

private void Button_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
    var button = sender as Button;
    Console.WriteLine($"{button.Text} MouseUp");
    if (!(bool)button.Tag)
        ButtonClick(button);
    else
        button.Tag = false;

    Func<Button, bool> ContainsMouse = (b) =>
    {
        var rect = b.RectangleToScreen(b.DisplayRectangle);
        var pos = GetCursorPosition();
        return rect.Contains(pos.X, pos.Y);
    };

    var hoverButton = _buttons.SingleOrDefault(b => ContainsMouse(b));
    if (hoverButton != null && !hoverButton.Equals(button))
        hoverButton.PerformClick();
}

private void Button_Click(object sender, EventArgs e)
{
    var button = sender as Button;
    Console.WriteLine($"{button.Text} Click");
    ButtonClick(button);
    button.Tag = true;
}

private void ButtonClick(Button button)
{
    Console.WriteLine($"{button.Text} Ding!");
}

[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
    public int X;
    public int Y;

    public static implicit operator Point(POINT point)
    {
        return new Point(point.X, point.Y);
    }
}

/// <summary>
/// Retrieves the cursor's position, in screen coordinates.
/// </summary>
/// <see>See MSDN documentation for further information.</see>
[DllImport("user32.dll")]
public static extern bool GetCursorPos(out POINT lpPoint);

public static Point GetCursorPosition()
{
    POINT lpPoint;
    GetCursorPos(out lpPoint);
    //bool success = User32.GetCursorPos(out lpPoint);
    // if (!success)

    return lpPoint;
}
</code>```

Body:
When the MouseUp event goes off, you can check if the mouse is over another button. If it is, then perform a click on that button. I took the GetCursorPosition code from an answer in this question.

Had to put true and false into button tags to be able to tell if the ButtonClick was already handled for that button or not.

// running as Console window
// output from...
// 1. clicking and releasing on button1
// 2. clicking and holding on button1 and then releasing not over button1 or button2,
// 3. clicking and holding on button1 and then
// moving mouse to over button2 and releasing mouse.

// button1 Click
// button1 Ding!
// button1 MouseUp
// button1 MouseUp
// button1 Ding!
// button1 MouseUp
// button1 Ding!
// button2 Click
// button2 Ding!

private List<Button> _buttons { get; set; }

public Form1()
{
    InitializeComponent();

    button1.MouseUp += Button_MouseUp;
    button2.MouseUp += Button_MouseUp;

    button1.Click += Button_Click;
    button2.Click += Button_Click;

    button1.Tag = false;
    button2.Tag = false;

    _buttons = new List<Button>()
    {
        button1, button2
    };
}

private void Button_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
    var button = sender as Button;
    Console.WriteLine($"{button.Text} MouseUp");
    if (!(bool)button.Tag)
        ButtonClick(button);
    else
        button.Tag = false;

    Func<Button, bool> ContainsMouse = (b) =>
    {
        var rect = b.RectangleToScreen(b.DisplayRectangle);
        var pos = GetCursorPosition();
        return rect.Contains(pos.X, pos.Y);
    };

    var hoverButton = _buttons.SingleOrDefault(b => ContainsMouse(b));
    if (hoverButton != null && !hoverButton.Equals(button))
        hoverButton.PerformClick();
}

private void Button_Click(object sender, EventArgs e)
{
    var button = sender as Button;
    Console.WriteLine($"{button.Text} Click");
    ButtonClick(button);
    button.Tag = true;
}

private void ButtonClick(Button button)
{
    Console.WriteLine($"{button.Text} Ding!");
}

[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
    public int X;
    public int Y;

    public static implicit operator Point(POINT point)
    {
        return new Point(point.X, point.Y);
    }
}

/// <summary>
/// Retrieves the cursor's position, in screen coordinates.
/// </summary>
/// <see>See MSDN documentation for further information.</see>
[DllImport("user32.dll")]
public static extern bool GetCursorPos(out POINT lpPoint);

public static Point GetCursorPosition()
{
    POINT lpPoint;
    GetCursorPos(out lpPoint);
    //bool success = User32.GetCursorPos(out lpPoint);
    // if (!success)

    return lpPoint;
}


问:
How to git ignore folder based on content
Is it possible to ignore a full folder based on some criteria about it's content. For example I want to ignore everything in all folders that contain at least one html file. How can this be done? (If at all)</p>

答: I don't think there is a direct way in git.  However, you could run a script (python, etc.) that does the checking for you and then writes the gitignore on the folder.</p>


问:
svg not updated when using jquery .appendTo
Chrome and Firefox don't visually update svg after adding an element with jQuery :

```<code>  <!DOCTYPE html>
  <html>
    <head>
      <meta charset="utf-8">
      <script src="../js/jquery-3.2.1.min.js"></script>
    </head>
    <body>
      <svg width="300" height="300" viewBox="0 0 300 300" >
      </svg>
      <script>
         jQuery('<circle/>', {
                 r: "25",
                 cx: "80",
                 cy: "80"
              }).appendTo('svg');
      </script>
    </body>
  </html>
</code>```

Element  is visible and editable in devTools but it appears only after inserting a space in the tag.

What do I miss ?

答:
In short, jQuery is made for handling HTML elements and can't deal with svg. See this answer for a more detailed explanation. You need to use plain javascript to manipulate the DOM as demonstrated here:

```<code>var svg = document.getElementsByTagName('svg')[0];  //Get the first svg element
var shape = svg.createElementNS("http://www.w3.org/2000/svg", "circle");
shape.setAttributeNS(null, "cx", 80);
shape.setAttributeNS(null, "cy", 80);
shape.setAttributeNS(null, "r",  25);
</code>```

But a cool alternative that can help with this if you're doing a lot of SVG manipulation is Snap.svg Using Snap.svg you could, instead, create it like this:

```<code>var s = Snap("svg");
var circle = s.circle(80, 80, 25);
</code>```

Body:
Chrome and Firefox don't visually update svg after adding an element with jQuery :

  <!DOCTYPE html>

      <meta charset="utf-8">

      <svg width="300" height="300" viewBox="0 0 300 300" >
      </svg>

Element  is visible and editable in devTools but it appears only after inserting a space in the tag.

What do I miss ?

Body:
In short, jQuery is made for handling HTML elements and can't deal with svg. See this answer for a more detailed explanation. You need to use plain javascript to manipulate the DOM as demonstrated here:

var svg = document.getElementsByTagName('svg')[0];  //Get the first svg element
var shape = svg.createElementNS("http://www.w3.org/2000/svg", "circle");
shape.setAttributeNS(null, "cx", 80);
shape.setAttributeNS(null, "cy", 80);
shape.setAttributeNS(null, "r",  25);

But a cool alternative that can help with this if you're doing a lot of SVG manipulation is Snap.svg Using Snap.svg you could, instead, create it like this:

var s = Snap("svg");
var circle = s.circle(80, 80, 25);


问:
Rails - good way to convert string to array if not array rails
I receive a param and want it to be either a string like this :

```<code>"abc,efg"
</code>```

or an Array like this

```<code>["abc","efg"]
</code>```

In the first case I want to convert it into an Array, what would be the good way ?

Here is what I thought

```<code>if params[:ids] && params[:ids].is_a? Array
     ids = params[:ids]
else if params[:ids]
    ids = params[:ids].split(",")
</code>```

答:
I'd use a ternary for this to keep it simple and on one line:

ids = params[:ids].is_a?(String) ? params[:ids].split(',') : params[:ids]

I've reversed the order so you don't get an undefined method error if you try calling split on nil should params[:ids] be missing.

Body:
I receive a param and want it to be either a string like this :

"abc,efg"

or an Array like this

["abc","efg"]

In the first case I want to convert it into an Array, what would be the good way ?

Here is what I thought

if params[:ids] && params[:ids].is_a? Array
     ids = params[:ids]
else if params[:ids]
    ids = params[:ids].split(",")


问:
How do I select this using Mysqli in php
How do I select users from the database where the sum of their salaries will be equal to some amount..

```<code>"select * from users where sum(salary)=10000";
</code>```

The sum of 4 users salary can bring the total 10000.

答: SELECT O.*, (SELECT sum(salary) FROM users WHERE Id = O.Id) 'RunningTotal' FROM users O WHERE RunningTotal = 10000</p>

Body:
How do I select users from the database where the sum of their salaries will be equal to some amount..

"select * from users where sum(salary)=10000";

The sum of 4 users salary can bring the total 10000.


问:
Edit email template in Laravel
I need to edit template which used for emails in admin panel. Any Ideas?

I think about several ways:

Save email template in DB in the text field, edit it in the admin panel and then display the text in the blade's view.

The problem of this way's realization is I have to display php variables in blade template and then use the final code as the html for email. I think, it's so difficult for Laravel.

And the additional problem is if I store {{ $var }} in template's text in DB - it will display as the text, blade compiler doesn't process it.

Store only the static text information from email in the DB and then display it in the template. PHP variables will transfer separately.

This way will solve the problem with the php var's display, but I still don't know how to use the final code in the Mail::send, because Laravel allows using the template's name only, not a HTML, as I know...

I think about the following way:

```<code>$view = view('template')->render();
mail(..., $view, ...);
</code>```

But I don't want to use it because I want use Mail::queue() for querying emails and I don't know how to use it with PHP mail().

Thanks to everybody for replies.

答:
I was doing this for a project yesterday and found a good post describing Alexander's answer in more detail. The core is creating an EmailTemplate model with this method:

```<code>public function parse($data)
{
    $parsed = preg_replace_callback('/{{(.*?)}}/', function ($matches) use ($data) {
        list($shortCode, $index) = $matches;

        if( isset($data[$index]) ) {
            return $data[$index];
        } else {
            throw new Exception("Shortcode {$shortCode} not found in template id {$this->id}", 1);
        }

    }, $this->content);

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

Example usage:

```<code>$template = EmailTemplate::where('name', 'welcome-email')->first();

Mail::send([], [], function($message) use ($template, $user)
{
    $data = [
        'firstname' => $user->firstname
    ];

    $message->to($user->email, $user->fullname)
        ->subject($template->subject)
        ->setBody($template->parse($data));
});
</code>```

For all the details (db migration, unit test, etc), see the original post at http://tnt.studio/blog/email-templates-from-database

Title: Edit email template in Laravel

Body:
I need to edit template which used for emails in admin panel. Any Ideas?

I think about several ways:

Save email template in DB in the text field, edit it in the admin panel and then display the text in the blade's view.

The problem of this way's realization is I have to display php variables in blade template and then use the final code as the html for email. I think, it's so difficult for Laravel.

And the additional problem is if I store {{ $var }} in template's text in DB - it will display as the text, blade compiler doesn't process it.

Store only the static text information from email in the DB and then display it in the template. PHP variables will transfer separately.

This way will solve the problem with the php var's display, but I still don't know how to use the final code in the Mail::send, because Laravel allows using the template's name only, not a HTML, as I know...

I think about the following way:

$view = view('template')->render();
mail(..., $view, ...);

But I don't want to use it because I want use Mail::queue() for querying emails and I don't know how to use it with PHP mail().

Thanks to everybody for replies.

Body:
I was doing this for a project yesterday and found a good post describing Alexander's answer in more detail. The core is creating an EmailTemplate model with this method:

public function parse($data)
{
    $parsed = preg_replace_callback('/{{(.*?)}}/', function ($matches) use ($data) {
        list($shortCode, $index) = $matches;

        if( isset($data[$index]) ) {
            return $data[$index];
        } else {
            throw new Exception("Shortcode {$shortCode} not found in template id {$this->id}", 1);
        }

    }, $this->content);

    return $parsed;
}

Example usage:

$template = EmailTemplate::where('name', 'welcome-email')->first();

Mail::send([], [], function($message) use ($template, $user)
{
    $data = [
        'firstname' => $user->firstname
    ];

    $message->to($user->email, $user->fullname)
        ->subject($template->subject)
        ->setBody($template->parse($data));
});

For all the details (db migration, unit test, etc), see the original post at http://tnt.studio/blog/email-templates-from-database


问:
Javascript : RemoveEventListener with Anonym Function
How to remove and event listener with an Anonym function , with removeEventListener();

```<code>document.getElementById("object").onclick = function(e){
    if(e && e.stopPropagation) {
        e.stopPropagation();
    } else {
          e = window.event;
          e.cancelBubble = true;
    }
}
</code>```

So I have this piece of code and the function what's called must be anonym I'dont know why but If it's not then doesn't works correctly, maybe beacuse of the event :|

But If it's anonym how can I remove it?

答:
Well you havent added an actual event listener, you have just populated the onclick variable with a function to be run. So you should be able to just use something like this:

```<code>document.getElementById("object").onclick = false;
</code>```

EDIT

Just tried it in jsFiddle and what I suggested works.

Body:
How to remove and event listener with an Anonym function , with removeEventListener();

document.getElementById("object").onclick = function(e){
    if(e && e.stopPropagation) {
        e.stopPropagation();
    } else {
          e = window.event;
          e.cancelBubble = true;
    }
}

So I have this piece of code and the function what's called must be anonym I'dont know why but If it's not then doesn't works correctly, maybe beacuse of the event :|

But If it's anonym how can I remove it?

Body:
Well you havent added an actual event listener, you have just populated the onclick variable with a function to be run. So you should be able to just use something like this:

document.getElementById("object").onclick = false;

EDIT

Just tried it in jsFiddle and what I suggested works.


问:
Matlab calculating line parameter x for 10 layers in the given wavelength range
I know how to calculate the line parameter defined as x below for one layer, considering the given wavelength range 50 to 550 um. Now I want to repeat this calculation for all 10 layers. all the other parameters remain as a constant while temperature varies from layer 1 to 10.Any suggestion would be greatly appreciated.   </p>

```<code>wl=[100 200 300 400 500]; %5 wavelengths, 5 spectral lines
br=[0.12 0.56 0.45 0.67 0.89]; % broadening parameter for each wavelength
T=[101 102 103 104 105 106 107 108 109 110];% temperature for 10 layers
wlall=linspace(50,550,40);%all the wavelength in 50um to 550 um range

% x is defined as,
%(br*wl/(br*br + (wlall-wl)^2))*br;
%If I do a calculation for the first line
((br(1)*T(1)*wl(1))./(br(1)*br(1)*(T(1)) + (wlall(:)-wl(1)).^2))*br(1)*T(1)

%Now I'm going to calculate it for all the lines in the first layer
k= repmat(wlall,5,1);

for i=1:5;
       kn(i,:)=(br(i)*T(1)* wl(i)./(br(i)*br(i)*T(1) + (k(i,:)-
       wl(i)).^2))*br(i)*T(1);

end

%Above code gives me x parameter for all the wavelengths in the
%given range( 50 to 550 um) in the first layer, dimension is (5,40)

% I need only the maximum value of each column

an=(kn(:,:)');
[ll,mm]=sort(an,2,'descend');
vn=(ll(:,1))'
</code>```

<p>%Now my output has the dimension , (1,40) one is for the first layer, 40 is
   %for the maximum x parameter corresponding to each wavelength in first layer
   %Now I want to calculate the x parameter in all 10 layers,So T should vary
   %from T(1) to T(10) and get the
   %maximum in each column, so my output should have the dimension ( 10, 40) </p>

答:
You just need to run an extra 'for' loop for each value of 'T'. Here is an example: </p>

```<code>            clc; close all; clear all;

            wl=[100 200 300 400 500]; %5 wavelengths, 5 spectral lines
            br=[0.12 0.56 0.45 0.67 0.89]; % broadening parameter for each wavelength
            T=[101 102 103 104 105 106 107 108 109 110];% temperature for 10 layers
            wlall=linspace(50,550,40);%all the wavelength in 50um to 550 um range

            % x is defined as,
            %(br*wl/(br*br + (wlall-wl)^2))*br;
            %If I do a calculation for the first line
            ((br(1)*T(1)*wl(1))./(br(1)*br(1)*(T(1)) + (wlall(:)-wl(1)).^2))*br(1)*T(1)

            %Now I'm going to calculate it for all the lines in the first layer
            k= repmat(wlall,5,1);

            for index = 1:numel(T)

                for i=1:5

                       kn(i,:, index)=(br(i)*T(index)* wl(i)./(br(i)*br(i)*T(index) + (k(i,:)- wl(i)).^2))*br(i)*T(index);

                end

                an(:, :, index) = transpose(kn(:, :, index));

                vn(:, index) = max(an(:, :, index), [], 2);

            end

            vn = transpose(vn);
</code>```

Body:
I know how to calculate the line parameter defined as x below for one layer, considering the given wavelength range 50 to 550 um. Now I want to repeat this calculation for all 10 layers. all the other parameters remain as a constant while temperature varies from layer 1 to 10.Any suggestion would be greatly appreciated.

wl=[100 200 300 400 500]; %5 wavelengths, 5 spectral lines
br=[0.12 0.56 0.45 0.67 0.89]; % broadening parameter for each wavelength
T=[101 102 103 104 105 106 107 108 109 110];% temperature for 10 layers
wlall=linspace(50,550,40);%all the wavelength in 50um to 550 um range

% x is defined as,
%(br*wl/(br*br + (wlall-wl)^2))*br;
%If I do a calculation for the first line
((br(1)*T(1)*wl(1))./(br(1)*br(1)*(T(1)) + (wlall(:)-wl(1)).^2))*br(1)*T(1)

%Now I'm going to calculate it for all the lines in the first layer
k= repmat(wlall,5,1);

for i=1:5;
       kn(i,:)=(br(i)*T(1)* wl(i)./(br(i)*br(i)*T(1) + (k(i,:)-
       wl(i)).^2))*br(i)*T(1);

end

%Above code gives me x parameter for all the wavelengths in the
%given range( 50 to 550 um) in the first layer, dimension is (5,40)

% I need only the maximum value of each column

an=(kn(:,:)');
[ll,mm]=sort(an,2,'descend');
vn=(ll(:,1))'

%Now my output has the dimension , (1,40) one is for the first layer, 40 is
   %for the maximum x parameter corresponding to each wavelength in first layer
   %Now I want to calculate the x parameter in all 10 layers,So T should vary
   %from T(1) to T(10) and get the
   %maximum in each column, so my output should have the dimension ( 10, 40)

Body:
You just need to run an extra 'for' loop for each value of 'T'. Here is an example:

            clc; close all; clear all;

            wl=[100 200 300 400 500]; %5 wavelengths, 5 spectral lines
            br=[0.12 0.56 0.45 0.67 0.89]; % broadening parameter for each wavelength
            T=[101 102 103 104 105 106 107 108 109 110];% temperature for 10 layers
            wlall=linspace(50,550,40);%all the wavelength in 50um to 550 um range

            % x is defined as,
            %(br*wl/(br*br + (wlall-wl)^2))*br;
            %If I do a calculation for the first line
            ((br(1)*T(1)*wl(1))./(br(1)*br(1)*(T(1)) + (wlall(:)-wl(1)).^2))*br(1)*T(1)

            %Now I'm going to calculate it for all the lines in the first layer
            k= repmat(wlall,5,1);

            for index = 1:numel(T)

                for i=1:5

                       kn(i,:, index)=(br(i)*T(index)* wl(i)./(br(i)*br(i)*T(index) + (k(i,:)- wl(i)).^2))*br(i)*T(index);

                end

                an(:, :, index) = transpose(kn(:, :, index));

                vn(:, index) = max(an(:, :, index), [], 2);

            end

            vn = transpose(vn);


问:
Mathematica: define function controlling order of substitutions
I want to define a function s[t, n] that returns the value at point t of the FourierTrigSeries of n terms of a given function f(t). For instance, for f(t) = t^2:

```<code>s[t_, n_] = FourierTrigSeries[t^2, t, n];  (* 2nd input = indep. variable *)
s[t, 3]
    Out =   Pi^2 / 3 + 4 (-Cos[t] + 1/4 Cos[2 t] - 1/9 Cos[3 t])
</code>```

which is fine (a function of t). To evaluate it at t = 0:

```<code>s[t, 3] /. t -> 0
    Out =   -31 / 9 + Pi^2 / 3
</code>```

This is what I would like to see as the output of s[0, 3], meaning "evaluate at t=0 the FourierTrigSeries of 3 terms".

However doing s[0,3] makes t = 0 "too early", so the original function f(t)=t^2 becomes identically 0; even the independent variable t (second input to FourierTrigSeries) becomes 0 too, which makes no sense. The result is that Mathematica cannot read my mind and returns as follows:

```<code>s[0, 3]
    Out =     FourierTrigSeries[0,0,3]
</code>```

Summarizing: I would like to define the function s[t, n] such that n is substituted for its value first and, only after that, t is substituted by its value for evaluation.

I have tried doing s[n, t] instead of s[t, n]; also tried := (delayed evaluation) instead of = in different ways, and in combination with things like

```<code>ss[tdelay_, n_] = s[t, n] /. t -> tdelay
</code>```

But nothing seems to work. How can I get the behavior I want?

Thank you in advance!

答:
Use SetDelayed and a temporary (local) variable.

```<code>s[t_, n_] := Module[{t0}, FourierTrigSeries[t0^2, t0, n] /. t0 -> t]

s[0, 3]
</code>```

```<code>-(31/9) + Pi^2/3
</code>```

Body:
I want to define a function s[t, n] that returns the value at point t of the FourierTrigSeries of n terms of a given function f(t). For instance, for f(t) = t^2:

s[t_, n_] = FourierTrigSeries[t^2, t, n];  (* 2nd input = indep. variable *)
s[t, 3]
    Out =   Pi^2 / 3 + 4 (-Cos[t] + 1/4 Cos[2 t] - 1/9 Cos[3 t])

which is fine (a function of t). To evaluate it at t = 0:

s[t, 3] /. t -> 0
    Out =   -31 / 9 + Pi^2 / 3

This is what I would like to see as the output of s[0, 3], meaning "evaluate at t=0 the FourierTrigSeries of 3 terms".

However doing s[0,3] makes t = 0 "too early", so the original function f(t)=t^2 becomes identically 0; even the independent variable t (second input to FourierTrigSeries) becomes 0 too, which makes no sense. The result is that Mathematica cannot read my mind and returns as follows:

s[0, 3]
    Out =     FourierTrigSeries[0,0,3]

Summarizing: I would like to define the function s[t, n] such that n is substituted for its value first and, only after that, t is substituted by its value for evaluation.

I have tried doing s[n, t] instead of s[t, n]; also tried := (delayed evaluation) instead of = in different ways, and in combination with things like

ss[tdelay_, n_] = s[t, n] /. t -> tdelay

But nothing seems to work. How can I get the behavior I want?

Thank you in advance!

Body:
Use SetDelayed and a temporary (local) variable.

s[t_, n_] := Module[{t0}, FourierTrigSeries[t0^2, t0, n] /. t0 -> t]

s[0, 3]

-(31/9) + Pi^2/3


问:
Printing certain values using Collections.frequency()
I have an array as follows:

```<code>int[] array = {11, 14, 17, 11, 48, 33, 29, 11, 17, 22, 11, 48, 18};
</code>```

What I wanted to do was to find the duplicate values, and print them.

So my way of doing this was to convert to ArrayList, then to Set and use a stream on the Set.

```<code>ArrayList<Integer> list = new ArrayList<>(array.length);
for (int i = 0; i < array.length; i++) {
    list.add(array[i]);
}

Set<Integer> dup = new HashSet<>(list);
</code>```

I then used a stream to loop through it and print the values using Collections.frequency.

```<code>dup.stream().forEach((key) -> {
            System.out.println(key + ": " + Collections.frequency(list, key));
        });
</code>```

Which will of course print them all, even if the count is one.

I thought adding in if(key > 1) but it's the value I want not the key.

How can I get the value in this instance to print only where value > 2.

I could probably put in:

```<code>int check = Collections.frequency(list, key);
            if (check > 1) {
</code>```

but this then duplicates Collections.frequency(list, key) in the stream and is quite ugly.

答:
This should work:

```<code>int[] array = {11, 14, 17, 11, 48, 33, 29, 11, 17, 22, 11, 48, 18};

List<Integer> list = Arrays.stream(array).boxed().collect(Collectors.toList());

// print values appearing more than once
list.stream().filter(i -> Collections.frequency(list, i) >1)
        .collect(Collectors.toSet()).forEach(System.out::println);
</code>```

Would print:

```<code>48
17
11
</code>```

If you also would like to get the occurences you could do something like this:

```<code>int[] array = {11, 14, 17, 11, 48, 33, 29, 11, 17, 22, 11, 48, 18};

List<Integer> list = Arrays.stream(array).boxed().collect(Collectors.toList());

list.stream()
    .filter(i -> Collections.frequency(list, i) >1)
    .collect(Collectors.toMap(identity(), v -> 1, Integer::sum))
    .forEach((x, y) -> System.out.println("Key: " + x +", occurence: "+ y));
</code>```

which prints

```<code>Key: 48, occurence: 2
Key: 17, occurence: 2
Key: 11, occurence: 4
</code>```

Body:
I have an array as follows:

int[] array = {11, 14, 17, 11, 48, 33, 29, 11, 17, 22, 11, 48, 18};

What I wanted to do was to find the duplicate values, and print them.

So my way of doing this was to convert to ArrayList, then to Set and use a stream on the Set.

ArrayList<Integer> list = new ArrayList<>(array.length);
for (int i = 0; i < array.length; i++) {
    list.add(array[i]);
}

Set<Integer> dup = new HashSet<>(list);

I then used a stream to loop through it and print the values using Collections.frequency.

dup.stream().forEach((key) -> {
            System.out.println(key + ": " + Collections.frequency(list, key));
        });

Which will of course print them all, even if the count is one.

I thought adding in if(key > 1) but it's the value I want not the key.

How can I get the value in this instance to print only where value > 2.

I could probably put in:

int check = Collections.frequency(list, key);
            if (check > 1) {

but this then duplicates Collections.frequency(list, key) in the stream and is quite ugly.

Body:
This should work:

int[] array = {11, 14, 17, 11, 48, 33, 29, 11, 17, 22, 11, 48, 18};

List<Integer> list = Arrays.stream(array).boxed().collect(Collectors.toList());

// print values appearing more than once
list.stream().filter(i -> Collections.frequency(list, i) >1)
        .collect(Collectors.toSet()).forEach(System.out::println);

Would print:

48
17
11

If you also would like to get the occurences you could do something like this:

int[] array = {11, 14, 17, 11, 48, 33, 29, 11, 17, 22, 11, 48, 18};

List<Integer> list = Arrays.stream(array).boxed().collect(Collectors.toList());

list.stream()
    .filter(i -> Collections.frequency(list, i) >1)
    .collect(Collectors.toMap(identity(), v -> 1, Integer::sum))
    .forEach((x, y) -> System.out.println("Key: " + x +", occurence: "+ y));

which prints

Key: 48, occurence: 2
Key: 17, occurence: 2
Key: 11, occurence: 4


问:
How to convert a datetime from sqlserver to java.util.Date
I am getting a row from a table with sql server database (with Asp net core as web api) using retrofit library in android and as far as I understood I must consider an string equivalent to datetime and then convert it to java.util.Date. An example of retrieved date time is 2018-10-29T19:56:59. Is there anyway to convert datetime to java.util.Date directly?
the code is shown below.

```<code>public class Food {
    @SerializedName("Id")
    private long Id;

    @SerializedName("Name")
    private String Name;

    @SerializedName("Content")
    private String Content;

    @SerializedName("IsActive")
    private boolean IsActive;

    @SerializedName("DoesExist")
    private boolean DoesExist;

    @SerializedName("Cost")
    private int Cost;

    @SerializedName("OffPercentage")
    private int OffPercentage;

    @SerializedName("OffTimeout")
    private Date OffTimeout;
...
}
</code>```

答:
Try JodaTime with custom deserializer:</p>

```<code>//GSON config
Gson gson = new GsonBuilder()
            .registerTypeAdapter(DateTime.class, new DateTimeDeserializer ())
            .create();

// DateTimeDeserializer.class
    public class DateTimeDeserializer implements JsonDeserializer<DateTime > {

      @Override
      public DateTime deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context)
          throws JsonParseException {
        return DateTime.parse(json.getAsString());
      }
    }
</code>```

Body:
I am getting a row from a table with sql server database (with Asp net core as web api) using retrofit library in android and as far as I understood I must consider an string equivalent to datetime and then convert it to java.util.Date. An example of retrieved date time is 2018-10-29T19:56:59. Is there anyway to convert datetime to java.util.Date directly?
the code is shown below.

public class Food {
    @SerializedName("Id")
    private long Id;

    @SerializedName("Name")
    private String Name;

    @SerializedName("Content")
    private String Content;

    @SerializedName("IsActive")
    private boolean IsActive;

    @SerializedName("DoesExist")
    private boolean DoesExist;

    @SerializedName("Cost")
    private int Cost;

    @SerializedName("OffPercentage")
    private int OffPercentage;

    @SerializedName("OffTimeout")
    private Date OffTimeout;
...
}

Body:
Try JodaTime with custom deserializer:

//GSON config
Gson gson = new GsonBuilder()
            .registerTypeAdapter(DateTime.class, new DateTimeDeserializer ())
            .create();

// DateTimeDeserializer.class
    public class DateTimeDeserializer implements JsonDeserializer<DateTime > {

      @Override
      public DateTime deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context)
          throws JsonParseException {
        return DateTime.parse(json.getAsString());
      }
    }


问:
Get the first character of each word in a String
I am trying to get a program working which does the following:

Let's say we have a String called name, set to "Stack Overflow Exchange". I want to output to the user "SOE", with the first characters of each word. I tried with the split() method, but I failed to do it.

My code:

```<code>public class q4 {
    public static void main(String args[]) {
        String x = "michele jones";
        String[] myName = x.split("");
        for(int i = 0; i < myName.length; i++) {
            if(myName[i] == "") {
                String s = myName[i];
                System.out.println(s);
            }
        }
    }
}
</code>```

I am trying to detect if there are any spaces, then I can simply take the next index. Could anyone tell me what I am doing wrong?

答:
The accepted reply in Java 8:</p>

```<code>/**
 * Gets the first character of every word in the sentence.
 *
 * @param string
 * @return
 */
public static String getFirstLetterFromEachWordInSentence(final String string) {
    if (string == null) {
        return null;
    }
    StringBuilder sb = new StringBuilder();
    Arrays.asList(string.split(" ")).forEach(s -> sb.append(s.charAt(0)).append(" "));
    return sb.toString().trim();
}
</code>```

Body:
I am trying to get a program working which does the following:

Let's say we have a String called name, set to "Stack Overflow Exchange". I want to output to the user "SOE", with the first characters of each word. I tried with the split() method, but I failed to do it.

My code:

public class q4 {
    public static void main(String args[]) {
        String x = "michele jones";
        String[] myName = x.split("");
        for(int i = 0; i < myName.length; i++) {
            if(myName[i] == "") {
                String s = myName[i];
                System.out.println(s);
            }
        }
    }
}

I am trying to detect if there are any spaces, then I can simply take the next index. Could anyone tell me what I am doing wrong?

Body:
The accepted reply in Java 8:

/**
 * Gets the first character of every word in the sentence.
 *
 * @param string
 * @return
 */
public static String getFirstLetterFromEachWordInSentence(final String string) {
    if (string == null) {
        return null;
    }
    StringBuilder sb = new StringBuilder();
    Arrays.asList(string.split(" ")).forEach(s -> sb.append(s.charAt(0)).append(" "));
    return sb.toString().trim();
}


问:
Can a seaborn (distplot) yaxis be automatically rescaled?
Can a Seaborn distplot be set to automatically re-scale the yaxis to capture the maximum y extent of multiple plotted datasets?

When doing batches of plots using Seaborn, sometimes it is unavoidable  that data is provided without an increasing maximum frequency value. When this happens the created plot yaxis cuts off data. However, sns.distplot() is fine if data is provided with increasing maximum.

This can be fixed via Matplotlib.patches or just by calling ax.autoscale()(Thanks @ImportanceOfBeingErnest for the later suggestion), but either seems "kludgey"...

Simple worked example:

```<code># Import modules
import numpy as np
from scipy.stats import truncnorm
import matplotlib.pyplot as plt
import seaborn as sns; sns.set(color_codes=True)

# Make some random data (credit: [@bakkal's Answer][3])
scale = 3.
range = 10
size = 100000
X = truncnorm(a=-range/scale, b=+range/scale, scale=scale).rvs(size=size)

# --- first time to show issue
# Now plot up 1st set of data (with first dataset having high Y values)
ax= sns.distplot( X*4 )
# Now plot up two more
for i in np.arange(1, 3):
    sns.distplot( X*i, ax=ax )
plt.show()
</code>```

```<code># --- Second time with a "kludgey" fix
ax = sns.distplot( X*4 )
# Now plot up two more
for i in np.arange(1, 3):
    sns.distplot( X*i, ax=ax )
# Now force y axis extent to be correct
ax.autoscale()
plt.show()
</code>```

```<code># --- Third time with increasing max in data provided
ax= sns.distplot( X )
# Now plot up two more
for i in np.arange(2, 4 ):
    sns.distplot( X*i, ax=ax )
plt.show()
</code>```

答:
This was an issue in Seaborn (0.8.0) and a fix has been a submitted on github.

If you also see this issue please update just Seaborn (>= version 0.8.1).

Body:
Can a Seaborn distplot be set to automatically re-scale the yaxis to capture the maximum y extent of multiple plotted datasets?

When doing batches of plots using Seaborn, sometimes it is unavoidable  that data is provided without an increasing maximum frequency value. When this happens the created plot yaxis cuts off data. However, sns.distplot() is fine if data is provided with increasing maximum.

This can be fixed via Matplotlib.patches or just by calling ax.autoscale()(Thanks @ImportanceOfBeingErnest for the later suggestion), but either seems "kludgey"...

Simple worked example:

# Import modules
import numpy as np
from scipy.stats import truncnorm
import matplotlib.pyplot as plt
import seaborn as sns; sns.set(color_codes=True)

# Make some random data (credit: [@bakkal's Answer][3])
scale = 3.
range = 10
size = 100000
X = truncnorm(a=-range/scale, b=+range/scale, scale=scale).rvs(size=size)

# --- first time to show issue
# Now plot up 1st set of data (with first dataset having high Y values)
ax= sns.distplot( X*4 )
# Now plot up two more
for i in np.arange(1, 3):
    sns.distplot( X*i, ax=ax )
plt.show()

# --- Second time with a "kludgey" fix
ax = sns.distplot( X*4 )
# Now plot up two more
for i in np.arange(1, 3):
    sns.distplot( X*i, ax=ax )
# Now force y axis extent to be correct
ax.autoscale()
plt.show()

# --- Third time with increasing max in data provided
ax= sns.distplot( X )
# Now plot up two more
for i in np.arange(2, 4 ):
    sns.distplot( X*i, ax=ax )
plt.show()