问:
thumbnail over the youtubeVideoplayer in xml of android studio?
How to put thumbnail over the youtubeVideoplayer in Layout-xml file of android studio 2.3.2, As I am able to play the youtube video in my app but I want to show the thumbnail of that video before playing video so that it look nice.</p>

答:
Every you tube video have unique ID and that is the only difference in each you tube video URL. Like video, every thumbnail alo have unique ID which is of course the same as video which belongs. Basically you have to extract or put unique ID and then download thumbnail using your own methods for downloading bitmaps or using some third party library like Glide. Something like this:

```<code>String  url = MessageFormat.format("http://img.youtube.com/vi/{0}/hqdefault.jpg", idOfYourVideo);
Glide.with(YourActivityName.this).load(url).asBitmap().into(new
     SimpleTarget<Bitmap>() {
        @Override
        public void onResourceReady(Bitmap resource, GlideAnimation<? super
        Bitmap> glideAnimation) {
            thumbnail.setImageBitmap(resource);
        }
    });
</code>```

Body:
Every you tube video have unique ID and that is the only difference in each you tube video URL. Like video, every thumbnail alo have unique ID which is of course the same as video which belongs. Basically you have to extract or put unique ID and then download thumbnail using your own methods for downloading bitmaps or using some third party library like Glide. Something like this:

String  url = MessageFormat.format("http://img.youtube.com/vi/{0}/hqdefault.jpg", idOfYourVideo);
Glide.with(YourActivityName.this).load(url).asBitmap().into(new
     SimpleTarget<Bitmap>() {
        @Override
        public void onResourceReady(Bitmap resource, GlideAnimation<? super
        Bitmap> glideAnimation) {
            thumbnail.setImageBitmap(resource);
        }
    });


来源: stackexchange

问:
Fastest method of collection searching by DateTime
I have a Dictionary containing 10 keys, each with a list containing up to 30,000 values. The values contain a DateTime property.

I frequently need to extract a small subset of one of the keys, like a date range of 30 - 60 seconds.

Doing this is easy, but getting it to run fast is not so. What would be the most efficient way to query this in-memory data?

Thanks a lot.

答: In reply to Aliostad: I don't think bsearch will not work if the list of the collection is a linked list. It still takes O(n)</p>

ContentLicense: CC BY-SA 2.5


问:
How do I define messages for checkboxes that are dynamically generated?
How do I define messages for checkboxes that are dynamically generated?

```<code>topicTocheckbox : Topic -> Html Msg
topicTocheckbox topic =
    div []
        [ input [ type_ "checkbox", name "topic", onClick TopicSelected, value <| getTopic topic ] []
        , label [] [ text <| getTopic topic ]
        ]
</code>```

It would be easier for me to pattern-match on the attached data of a message. In my case, I would attach the topic to the TopicSelected union case.

Hence, I wish I could define a message like this:

```<code>type Msg
    = TopicSelected topic
</code>```

However, that doesn't align with the example that I am referencing.

Here's how the checkboxes are being generated:

```<code>topicsUI : List Topic -> Html Msg
topicsUI topics =
    let
        formattedTopics =
            topics |> List.map topicTocheckbox
    in
        Html.form [ action "" ] formattedTopics
</code>```

答:
You can give TopicSelected a parameter. In the example you linked, you referenced this Msg definition:

type Msg
  = ToggleNotifications
  | ToggleAutoplay
  | ToggleLocation
```

<p>You could rewrite this as a single <code>Toggle</code> msg with a <code>Target</code> type:</p>

<pre class="lang-elm prettyprint-override"><code>type Target
  = Notifications
  | Autoplay
  | Location

type Msg
  = Toggle Target
</code>```

Then you can pattern match in update by each variation:

update : Msg -> Model -> Model
update msg model =
  case msg of
    Toggle Notifications ->
      { model | notifications = not model.notifications }

    Toggle Autoplay ->
      { model | autoplay = not model.autoplay }

    Toggle Location ->
      { model | location = not model.location }
```

<p>The view for this new definition in the beginnerProgram example looks like this:</p>

<pre class="lang-elm prettyprint-override"><code>checkbox (Toggle Notifications) "Email Notifications"
</code>```

This translates well to your Topic example. Depending on how Topic is defined, you could do this:

type Topic
    = Math
    | Literature
    | Music

type Msg
    = TopicSelected Topic
```

<p>Your <code>onClick</code> could look like this:</p>

<pre class="lang-elm prettyprint-override"><code>onClick (TopicSelected topic)
</code>```

and your update could specify each topic by pattern matching:

update msg model =
  case msg of
    TopicSelected Math ->
      model

    TopicSelected Literature ->
      model
    ...
```

ContentLicense: CC BY-SA 3.0

Body:
How do I define messages for checkboxes that are dynamically generated?

topicTocheckbox : Topic -> Html Msg
topicTocheckbox topic =
    div []
        [ input [ type_ "checkbox", name "topic", onClick TopicSelected, value <| getTopic topic ] []
        , label [] [ text <| getTopic topic ]
        ]

It would be easier for me to pattern-match on the attached data of a message. In my case, I would attach the topic to the TopicSelected union case.

Hence, I wish I could define a message like this:

type Msg
    = TopicSelected topic

However, that doesn't align with the example that I am referencing.

Here's how the checkboxes are being generated:

topicsUI : List Topic -> Html Msg
topicsUI topics =
    let
        formattedTopics =
            topics |> List.map topicTocheckbox
    in
        Html.form [ action "" ] formattedTopics

Body:
You can give TopicSelected a parameter. In the example you linked, you referenced this Msg definition:

type Msg
  = ToggleNotifications
  | ToggleAutoplay
  | ToggleLocation

You could rewrite this as a single Toggle msg with a Target type:

type Target
  = Notifications
  | Autoplay
  | Location

type Msg
  = Toggle Target

Then you can pattern match in update by each variation:

update : Msg -> Model -> Model
update msg model =
  case msg of
    Toggle Notifications ->
      { model | notifications = not model.notifications }

    Toggle Autoplay ->
      { model | autoplay = not model.autoplay }

    Toggle Location ->
      { model | location = not model.location }

The view for this new definition in the beginnerProgram example looks like this:

checkbox (Toggle Notifications) "Email Notifications"

This translates well to your Topic example. Depending on how Topic is defined, you could do this:

type Topic
    = Math
    | Literature
    | Music

type Msg
    = TopicSelected Topic

Your onClick could look like this:

onClick (TopicSelected topic)

and your update could specify each topic by pattern matching:

update msg model =
  case msg of
    TopicSelected Math ->
      model

    TopicSelected Literature ->
      model
    ...


问:
Better null-management try-catch with Java 8
Given the following code:

```<code>StaticPOIDataType response = null;
try {
  final JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class);
  final Unmarshaller unmarshaller = jc.createUnmarshaller();
  unmarshaller.setSchema(getSchema());

  response =((JAXBElement<StaticPOIDataType>) unmarshaller.unmarshal(cpoGatewayURL)).getValue();

} catch (JAXBException e) {
  e.printStackTrace();
} finally {
  return response;
}
</code>```

I heard of a new Java 8-feature to express this in a much more elegant way by avoiding null-initializiation. But I don't know what to search for.

答:
What you are looking is for optional. here is the below code enjoy</p>

```<code>try {
        final JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class);
        final Unmarshaller unmarshaller = jc.createUnmarshaller();
        unmarshaller.setSchema(getSchema());

        return Optional.ofNullable((JAXBElement<StaticPOIDataType>) unmarshaller.unmarshal(cpoGatewayURL)).getValue());

    } catch (JAXBException e) {
        e.printStackTrace();
    }

    return Optional.empty();
</code>```

Body:
Given the following code:

StaticPOIDataType response = null;
try {
  final JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class);
  final Unmarshaller unmarshaller = jc.createUnmarshaller();
  unmarshaller.setSchema(getSchema());

  response =((JAXBElement<StaticPOIDataType>) unmarshaller.unmarshal(cpoGatewayURL)).getValue();

} catch (JAXBException e) {
  e.printStackTrace();
} finally {
  return response;
}

I heard of a new Java 8-feature to express this in a much more elegant way by avoiding null-initializiation. But I don't know what to search for.

Body:
What you are looking is for optional. here is the below code enjoy

try {
        final JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class);
        final Unmarshaller unmarshaller = jc.createUnmarshaller();
        unmarshaller.setSchema(getSchema());

        return Optional.ofNullable((JAXBElement<StaticPOIDataType>) unmarshaller.unmarshal(cpoGatewayURL)).getValue());

    } catch (JAXBException e) {
        e.printStackTrace();
    }

    return Optional.empty();


问:
Changing the entire string in a string builder object
I have the following code:

```<code>using System;
using System.Text;

public class Program
{
    private static StringBuilder mystrb = new StringBuilder("hello");
    public static void Main()
    {
        mystrb.Clear();
        mystrb.Append("chau");
    }
}
</code>```

is there any other way of entirly replacing the string in the string builder, i am looking for a one sentence way of doing it if it exist.

答:
I think Ian's solution of simply overwriting your object with a new one is the best solution, but if for some reason you don't like that then you could do something like this:

```<code>static void StringBuilderReplaceText(StringBuilder sb, string newText)
{
    sb.Clear();
    sb.AppendLine(newText);
}
</code>```

I was initially going to simply inherit from the StringBuilder object and add a new Replace extension method but apparently the object is sealed for some reason.

So yea, technically this would allow you to replace the content of a StringBuilder with a single line by later using StringBuilderReplaceText(myStringBuilder, "my new text"); but I really don't see why you'd do this instead of just re-using the constructor.

Body:
I have the following code:

using System;
using System.Text;

public class Program
{
    private static StringBuilder mystrb = new StringBuilder("hello");
    public static void Main()
    {
        mystrb.Clear();
        mystrb.Append("chau");
    }
}

is there any other way of entirly replacing the string in the string builder, i am looking for a one sentence way of doing it if it exist.

Body:
I think Ian's solution of simply overwriting your object with a new one is the best solution, but if for some reason you don't like that then you could do something like this:

static void StringBuilderReplaceText(StringBuilder sb, string newText)
{
    sb.Clear();
    sb.AppendLine(newText);
}

I was initially going to simply inherit from the StringBuilder object and add a new Replace extension method but apparently the object is sealed for some reason.

So yea, technically this would allow you to replace the content of a StringBuilder with a single line by later using StringBuilderReplaceText(myStringBuilder, "my new text"); but I really don't see why you'd do this instead of just re-using the constructor.


问:
Download & Install Xcode version without Premium Developer Account
I do not have Apple Developer Premium Account and I need Xcode Beta (recent major release of Application Development tool by Apple).

How can I download Xcode (beta) version without Premium Apple Developer Account?

Is there any way that I can get the Xcode beta or stable release?

答:
Yes,

You can download Xcode with/without Paid (Premium) Apple Developer Account from below links.

Xcode 13 RC

Use this link to get the very latest versions at any time:

https://stackoverflow.com/a/10335943/294884

Xcode 13 RC

 - (Command Line Tool (Xcode 13 RC) - for macOS BigSur +)

Apple Download Portal

Look at here: How to install & set command line tool

ContentLicense: CC BY-SA 4.0


问:
Return same row alternate column value after successful LARGE?
I'm using =LARGE(H5:H24,1) to find the largest value in a column H. I also want the equivalent Column A value, i.e. If this formula returns Column H Row 3, I also want the Column A Row 3 value (this can be returned to a different result/cell). I tried VLookup but keep getting errors in the formula. Thanks

Body: =INDEX(A5:A24,MATCH(LARGE(H5:H24,1),H5:H24,0))


问:
Decode jQuery dataTables aoData.push parameter in controller
I am using jQuery dataTables verion 1.9.4 and spring MVC. I want to pass encoded parameters to controller using aoData.push method. I have used :

aoData.push({"name":"message", "value":encodeURIComponent("test Message")})
```

.. But in the controller I am receiving test%20message instead test message. Is there any way to decode the dataTable parameters in controller like filters?

Any help or guidance would be appreciated.

答:
You can try this:</p>

```<code>nServerParams": function (aoData) {
    aoData.push({ "name": "message", "value": encodeURIComponent("test
    Message").replace(" ", "%20")});
},
</code>```

Body:
I am using jQuery dataTables verion 1.9.4 and spring MVC. I want to pass encoded parameters to controller using aoData.push method. I have used :

aoData.push({"name":"message", "value":encodeURIComponent("test Message")})

.. But in the controller I am receiving test%20message instead test message. Is there any way to decode the dataTable parameters in controller like filters?

Any help or guidance would be appreciated.

Body:
You can try this:

nServerParams": function (aoData) {
    aoData.push({ "name": "message", "value": encodeURIComponent("test
    Message").replace(" ", "%20")});
},


问:
How to change tab ordering in Flex (Actionscript, SDK 3.5)
The flex tab ordering is important both for usability (obvious) and accessibility (it defines the screen readers read ordering). However, Flex 3.5 seems to have next to no support to influence it for more complicated applications.

From what I know so far:

the tab ordering is calculated by the mx.managers.FocusManager, which takes care of one "tab cycle" for the entire application (i.e. there is not one for each container, but one for the whole app). The exception being embedded .swf files and popups, each of which have their own FocusManager.

the logic inside the FocusManager is marked as private, and the class is instantiated in Application.initialize(), so it's not easy to change the behaviour (short of rewriting parts of the SDK, which might pose license trouble)

The tab ordering looks for each components tabIndex (int) property. All components which have this property set (>0) are ordered by its value, otherwise the visual hierarchy is used (which uses container nesting and child order inside the containers).

All components without tabIndex are sorted to be after the components which have it set (internally, "tabIndex not set" is mapped to "tabIndex = int.MAX_VALUE)

two components with the same tabIndex are ordered by visual hierarchy.

This means that you can either use the automatic ordering by visual hierarchy (mostly what you want) OR you can use specifying tabIndexes directly - BUT if you do this you completely screw the automatic ordering. This is especially bad if you work with custom components and want to change the tab ordering inside those: once you do this, you ruined the tab order for all screens using your component. Also you cannot just set the tab ordering only on the highest level mxml file, as often you don't have access to the inner workings of the components you use.

Example:

accVerticalStuff.mxml

```<code><mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml">

    <mx:Label text="One"/>
    <mx:TextInput tabIndex="1" id="One" />

    <mx:Label text="Two" />
    <mx:TextInput tabIndex="2" id="Two"/>

    <mx:Label text="Three" />
    <mx:TextInput tabIndex="3" id="Three"/>

</mx:VBox>
</code>```

Application.mxml

Expected Result: the tab order would be first the three vertical items on the left, then the three vertical items on the right, i.e. grouped by the containers. The TopLevelElement is the first in the tab order.
(it works exactly in this way if no tabIndex is specified, however then we're not able to actuall change the tabIndex to e.g. switch One and Three for whatever reasons we might want to do so)

Actual Result: the tab ordering is horizontal, i.e. jumping between the two input forms. The TopLevelElement (w/o tabIndex specified) is last in the tab order.

Changing the nesting of containers will not work in modularized projects, and changing the ordering of childs would affect their display position (whereas going for Canvas container looses the AutoLayout).

Is there a way (possibly complicated, but preferably short of rewriting the SDK) to specify the tab ordering for single components, independently of other components?

if all else fails, would upgrading to Flex4 help in solving this issue?

答:
after a little research i found out the following:

if (even a single) DisplayObject has tabIndex > 0 it means that from now pressing TAB will only switcth focus between instances with tabIndex > 0

if there's only one instance with tabIndex > 0 it will be focused forever

if current.tabIndex - next.tabIndex > 1 it doesn't matter, tabIndex will increase to the next existing value

if several instances have equal tabIndex values they will recieve focus in a native order (as if tabIndex is never defined)

-------------------------------------------------------------------------------

so:

for setting up TAB navigation between some DisplayObjects (no matter where're they located in the display list) - just set tabIndex > 0 for every of them.

for removing an instance from TAB list - set tabIndex = 0 (but if there are only DisplayObjects with tabIndex == 0 left in the app - TAB will switch focus naturally between them). tabEnabled = false should be a better choice

for creating several groups of DisplayObjects with natural TAB order inside each one while keeping certain order between the groups - select one tabIndex for each group (small values appear first) and apply the tabIndex you selected to every member of a group.

i think that too much instances in the TAB list are useless and annoying so the best way to manage it should be making it equal to list of top e.g. 10 most useful UI elements for current app state.

and a little bit of code (based on your example):

showclasses.NewFile.mxml:

```<code><mx:VBox xmlns:mx="library://ns.adobe.com/flex/mx"
         xmlns:fx="http://ns.adobe.com/mxml/2009" data="1,2,3" creationComplete="addFocuses();">
    <fx:Script>
        <![CDATA[
        private function addFocuses():void{
            var focs:Array = data.split(',');
            One.tabIndex = focs[0];
            Two.tabIndex = focs[1];
            Three.tabIndex = focs[2];
        }
        ]]>
    </fx:Script>
    <mx:Label text="One"/>
    <mx:TextInput id="One" />
    <mx:Label text="Two" />
    <mx:TextInput id="Two"/>
    <mx:Label text="Three" />
    <mx:TextInput id="Three"/>
</mx:VBox>
</code>```

Main.mxml:

```<code><mx:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:s="library://ns.adobe.com/flex/spark"
    xmlns:mx="library://ns.adobe.com/flex/mx"
    xmlns:th="showclasses.*">
    <mx:HBox>
        <th:NewFile data="1,2,3" />
        <th:NewFile data="1,2,3" />
        <th:NewFile data="1,2,3" />
    </mx:HBox>
</mx:Application>
</code>```

if data values are 1,2,3; 1,2,3; 1,2,3 - focus moves horizontally from left to right (naturally because tabIndex is constant inside each row) and then switches to the left element of the next row down.

if they are 2; null,3; 0,null,1 (null == 0 for tabIndex) - focus will appear in the lower-right corner then in the upper-left and at last in the center.
hope this'll be useful

Body:
The flex tab ordering is important both for usability (obvious) and accessibility (it defines the screen readers read ordering). However, Flex 3.5 seems to have next to no support to influence it for more complicated applications.

From what I know so far:

the tab ordering is calculated by the mx.managers.FocusManager, which takes care of one "tab cycle" for the entire application (i.e. there is not one for each container, but one for the whole app). The exception being embedded .swf files and popups, each of which have their own FocusManager.

the logic inside the FocusManager is marked as private, and the class is instantiated in Application.initialize(), so it's not easy to change the behaviour (short of rewriting parts of the SDK, which might pose license trouble)

The tab ordering looks for each components tabIndex (int) property. All components which have this property set (>0) are ordered by its value, otherwise the visual hierarchy is used (which uses container nesting and child order inside the containers).

All components without tabIndex are sorted to be after the components which have it set (internally, "tabIndex not set" is mapped to "tabIndex = int.MAX_VALUE)

two components with the same tabIndex are ordered by visual hierarchy.

This means that you can either use the automatic ordering by visual hierarchy (mostly what you want) OR you can use specifying tabIndexes directly - BUT if you do this you completely screw the automatic ordering. This is especially bad if you work with custom components and want to change the tab ordering inside those: once you do this, you ruined the tab order for all screens using your component. Also you cannot just set the tab ordering only on the highest level mxml file, as often you don't have access to the inner workings of the components you use.

Example:

accVerticalStuff.mxml

<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml">

    <mx:Label text="One"/>
    <mx:TextInput tabIndex="1" id="One" />

    <mx:Label text="Two" />
    <mx:TextInput tabIndex="2" id="Two"/>

    <mx:Label text="Three" />
    <mx:TextInput tabIndex="3" id="Three"/>

</mx:VBox>

Application.mxml

Expected Result: the tab order would be first the three vertical items on the left, then the three vertical items on the right, i.e. grouped by the containers. The TopLevelElement is the first in the tab order.
(it works exactly in this way if no tabIndex is specified, however then we're not able to actuall change the tabIndex to e.g. switch One and Three for whatever reasons we might want to do so)

Actual Result: the tab ordering is horizontal, i.e. jumping between the two input forms. The TopLevelElement (w/o tabIndex specified) is last in the tab order.

Changing the nesting of containers will not work in modularized projects, and changing the ordering of childs would affect their display position (whereas going for Canvas container looses the AutoLayout).

Is there a way (possibly complicated, but preferably short of rewriting the SDK) to specify the tab ordering for single components, independently of other components?

if all else fails, would upgrading to Flex4 help in solving this issue?

Body:
after a little research i found out the following:

if (even a single) DisplayObject has tabIndex > 0 it means that from now pressing TAB will only switcth focus between instances with tabIndex > 0

if there's only one instance with tabIndex > 0 it will be focused forever

if current.tabIndex - next.tabIndex > 1 it doesn't matter, tabIndex will increase to the next existing value

if several instances have equal tabIndex values they will recieve focus in a native order (as if tabIndex is never defined)

-------------------------------------------------------------------------------

so:

for setting up TAB navigation between some DisplayObjects (no matter where're they located in the display list) - just set tabIndex > 0 for every of them.

for removing an instance from TAB list - set tabIndex = 0 (but if there are only DisplayObjects with tabIndex == 0 left in the app - TAB will switch focus naturally between them). tabEnabled = false should be a better choice

for creating several groups of DisplayObjects with natural TAB order inside each one while keeping certain order between the groups - select one tabIndex for each group (small values appear first) and apply the tabIndex you selected to every member of a group.

i think that too much instances in the TAB list are useless and annoying so the best way to manage it should be making it equal to list of top e.g. 10 most useful UI elements for current app state.

and a little bit of code (based on your example):

showclasses.NewFile.mxml:

<mx:VBox xmlns:mx="library://ns.adobe.com/flex/mx"
         xmlns:fx="http://ns.adobe.com/mxml/2009" data="1,2,3" creationComplete="addFocuses();">
    <fx:Script>
        <![CDATA[
        private function addFocuses():void{
            var focs:Array = data.split(',');
            One.tabIndex = focs[0];
            Two.tabIndex = focs[1];
            Three.tabIndex = focs[2];
        }
        ]]>
    </fx:Script>
    <mx:Label text="One"/>
    <mx:TextInput id="One" />
    <mx:Label text="Two" />
    <mx:TextInput id="Two"/>
    <mx:Label text="Three" />
    <mx:TextInput id="Three"/>
</mx:VBox>

Main.mxml:

<mx:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:s="library://ns.adobe.com/flex/spark"
    xmlns:mx="library://ns.adobe.com/flex/mx"
    xmlns:th="showclasses.*">
    <mx:HBox>
        <th:NewFile data="1,2,3" />
        <th:NewFile data="1,2,3" />
        <th:NewFile data="1,2,3" />
    </mx:HBox>
</mx:Application>

if data values are 1,2,3; 1,2,3; 1,2,3 - focus moves horizontally from left to right (naturally because tabIndex is constant inside each row) and then switches to the left element of the next row down.

if they are 2; null,3; 0,null,1 (null == 0 for tabIndex) - focus will appear in the lower-right corner then in the upper-left and at last in the center.
hope this'll be useful


问:
Build html parts from value of a js function
I really don't know how to put that in words correctly, sorry if the title misleads.

I have a function in a js file, which checks if an element is in a data array. If so the html page should show all the values of the element (so far so good). But if the element is not in the array, my html page should only display: Element not found.

js function:

```<code>function containsID(arr, number) {
    var i = arr.length;
    while (i--) {
       if (arr[i].id === number) {
           return true;
       }
    }
    return false;
}
</code>```

html:

```<code>{% if containsID(data, id) %} //I want something like that
    <p>{{data[id].text}}</p>
{% else %}
    <p> Not found </p>
{% endif %}
</code>```

答:
To output something from Javascript in HTML you can set the innerHTML value of an element.

function getElement(e) {
    return document.getElementById(e);
}

function foo() {
    getElement("output").innerHTML = "Foo";
}

function bar() {
    getElement("output").innerHTML = "Bar";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="output">

</div>

<input type="button" onclick="foo()" value="Foo">
<input type="button" onclick="bar()" value="Bar"></code>```

Body:
I really don't know how to put that in words correctly, sorry if the title misleads.

I have a function in a js file, which checks if an element is in a data array. If so the html page should show all the values of the element (so far so good). But if the element is not in the array, my html page should only display: Element not found.

js function:

function containsID(arr, number) {
    var i = arr.length;
    while (i--) {
       if (arr[i].id === number) {
           return true;
       }
    }
    return false;
}

html:

{% if containsID(data, id) %} //I want something like that

{{data[id].text}}

{% else %}

 Not found

{% endif %}

Body:
To output something from Javascript in HTML you can set the innerHTML value of an element.

function getElement(e) {
    return document.getElementById(e);
}

function foo() {
    getElement("output").innerHTML = "Foo";
}

function bar() {
    getElement("output").innerHTML = "Bar";
}

<div id="output">
    &nbsp;
</div>

<input type="button" onclick="foo()" value="Foo">
<input type="button" onclick="bar()" value="Bar">


问:
Unity build doesn't work specifically on Huawei devices, how to fix or figure this out?
My first question asked! I have developed a game using Unity3D and published it to google play for mobile devices. The game works on all devices so far except for the Huawei Watch 1st Gen. (yes building Unity games for smartwatches). Short of running out and buying a $200 watch to test and test more,

Does anyone know of any reason why a mobile game would work on literally every device except for one? If so how can I go about figuring this out if answers are from reach?

UPDATE I have been given a stack trace from google =)

```<code>native: pc 00000000005f8278  /data/app/com.stonegolemstudios.combatwear-1/lib/arm/libunity.so
native: pc 0000000000add428  /data/app/com.stonegolemstudios.combatwear-1/lib/arm/libunity.so
</code>```

Not sure what this is but it was part of the crash report.

signal 11 (SIGSEGV), code 1 (SEGV_MAPERR)

Hope this helps to solve the problem.

答:
If its doesnt work on specific device than your device might need update or reset, but if its doesnt work on Huawie smart watches it must be because of your resulation / screen preferances when you compiling your app, and you should check api level as well in order to solve that problem.

I hope this will help you :)

Body:
My first question asked! I have developed a game using Unity3D and published it to google play for mobile devices. The game works on all devices so far except for the Huawei Watch 1st Gen. (yes building Unity games for smartwatches). Short of running out and buying a $200 watch to test and test more,

Does anyone know of any reason why a mobile game would work on literally every device except for one? If so how can I go about figuring this out if answers are from reach?

UPDATE I have been given a stack trace from google =)

native: pc 00000000005f8278  /data/app/com.stonegolemstudios.combatwear-1/lib/arm/libunity.so
native: pc 0000000000add428  /data/app/com.stonegolemstudios.combatwear-1/lib/arm/libunity.so

Not sure what this is but it was part of the crash report.

signal 11 (SIGSEGV), code 1 (SEGV_MAPERR)

Hope this helps to solve the problem.


问:
Rows to column in SQL Server with duplicate name
I have three tables ProductMaster and ProductParameter and ParameterMaster.

ProductMaster contains multiple products and each product has multiple parameters whose values are stored in productparameter.

Now I need ProductParameter values as a column. I am using pivot but I can only get one product value. I want a list of all product like

```<code>ProductID   Name         ParameterValue1  ParameterValue2
--------------------------------------------------------------
  1         Product-1    test             test2
  2         Product-     anothervalue     another value2
</code>```

Tables are as below

Parameter Master

```<code>ParameterID
Name
</code>```

ProductParameter

```<code>ProductParameterID
ProductID
ParameterID
Value
</code>```

ProductMaster

```<code>ProductID
Name
</code>```

答:
```<code>  select pp.ProductParameterId, pp.ProductID, pp.ParameterID, pp.value
  from ParameterMaster pm, ProductParameter pp, ProductMaster p
  where  p.name = pm.name
  and
  pp.ProductId = p.ProductId
  and
  pm.ParameterId = pp.ParameterId;
</code>```

In oracle something like this:

Body:
I have three tables ProductMaster and ProductParameter and ParameterMaster.

ProductMaster contains multiple products and each product has multiple parameters whose values are stored in productparameter.

Now I need ProductParameter values as a column. I am using pivot but I can only get one product value. I want a list of all product like

ProductID   Name         ParameterValue1  ParameterValue2
--------------------------------------------------------------
  1         Product-1    test             test2
  2         Product-     anothervalue     another value2

Tables are as below

Parameter Master

ParameterID
Name

ProductParameter

ProductParameterID
ProductID
ParameterID
Value

ProductMaster

ProductID
Name

Body:
  select pp.ProductParameterId, pp.ProductID, pp.ParameterID, pp.value
  from ParameterMaster pm, ProductParameter pp, ProductMaster p
  where  p.name = pm.name
  and
  pp.ProductId = p.ProductId
  and
  pm.ParameterId = pp.ParameterId;

In oracle something like this:


问:
Can't center divs HTML CSS
i'm having a small issue getting my divs to sit inline with each other and in the center of the parent div. So I have one parent "page" then 6 other divs inside of that the "pageName" which sits above "bg_01", "bg_02", "bg_03", "bg_04", "bg_05", "bg_06" which all sit inline with each other. However it works when the window is quite small however i'm trying to get it to work when the window is any size, can anyone see where I'm going wrong?

Thanks again guys.

p {
  margin: 0;
}

#page {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #fff;
  width: 100%;
  height: 200px;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}

#bg_01 {
  background-color: #80b3ff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

#bg_02 {
  background-color: #afe9af;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

#bg_03 {
  background-color: #ffb380;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

#bg_04 {
  background-color: #ffaaaa;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

#bg_05 {
  background-color: #eeaaff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="page">
  <div id="pageName" }>
    <p>Colour</p>
  </div>
  <div id="bg_01">
  </div>

  <div id="bg_02">
  </div>

  <div id="bg_03">
  </div>

  <div id="bg_04">
  </div>

  <div id="bg_05">
  </div>
</div></code>```

答:
1) wrap Elments in DIV with class center

```<code><div class="center"> <-------------------

  <div id="bg_01">
  </div>
  <div id="bg_02">
  </div>
  <div id="bg_03">
  </div>
  <div id="bg_04">
  </div>
  <div id="bg_05">
  </div>

</div>
</code>```

2) Remove float: left; and use display:inline block

```<code>#bg_01,#bg_02,#bg_03,#bg_04,#bg_05 {
  display: inline-block;
  float: left;<--------Remove
  More code...
}
</code>```

3) added css For .center :

```<code>.center {
  text-align: center;
  }
</code>```

Full Code :

p {
  margin: 0;
}

#page {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #fff;
  width: 100%;
  height: 200px;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;

}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}

#bg_01 {
  background-color: #80b3ff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  display: inline-block;

}

#bg_02 {
  background-color: #afe9af;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
display: inline-block;
}

#bg_03 {
  background-color: #ffb380;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
display: inline-block;
}

#bg_04 {
  background-color: #ffaaaa;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
display: inline-block;
}

#bg_05 {
  background-color: #eeaaff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
display: inline-block;
}
.center {
  text-align: center;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="page">
  <div id="pageName">
    <p>Colour</p>
  </div>
  <div class="center">
    <div id="bg_01">
    </div>
    <div id="bg_02">
    </div>
    <div id="bg_03">
    </div>
    <div id="bg_04">
    </div>
    <div id="bg_05">
    </div>
  </div>
</div></code>```

Title: Can't center divs HTML CSS

Body:
i'm having a small issue getting my divs to sit inline with each other and in the center of the parent div. So I have one parent "page" then 6 other divs inside of that the "pageName" which sits above "bg_01", "bg_02", "bg_03", "bg_04", "bg_05", "bg_06" which all sit inline with each other. However it works when the window is quite small however i'm trying to get it to work when the window is any size, can anyone see where I'm going wrong?

Thanks again guys.

p {
  margin: 0;
}

#page {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #fff;
  width: 100%;
  height: 200px;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}

#bg_01 {
  background-color: #80b3ff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

#bg_02 {
  background-color: #afe9af;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

#bg_03 {
  background-color: #ffb380;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

#bg_04 {
  background-color: #ffaaaa;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

#bg_05 {
  background-color: #eeaaff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

Colour

Body:
1) wrap Elments in DIV with class center

<div class="center"> <-------------------

  <div id="bg_01">
  </div>
  <div id="bg_02">
  </div>
  <div id="bg_03">
  </div>
  <div id="bg_04">
  </div>
  <div id="bg_05">
  </div>

</div>

2) Remove float: left; and use display:inline block

#bg_01,#bg_02,#bg_03,#bg_04,#bg_05 {
  display: inline-block;
  float: left;<--------Remove
  More code...
}

3) added css For .center :

.center {
  text-align: center;
  }

Full Code :

p {
  margin: 0;
}

#page {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #fff;
  width: 100%;
  height: 200px;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;

}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}

#bg_01 {
  background-color: #80b3ff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  display: inline-block;

}

#bg_02 {
  background-color: #afe9af;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
display: inline-block;
}

#bg_03 {
  background-color: #ffb380;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
display: inline-block;
}

#bg_04 {
  background-color: #ffaaaa;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
display: inline-block;
}

#bg_05 {
  background-color: #eeaaff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
display: inline-block;
}
.center {
  text-align: center;
  }

<div id="page">
  <div id="pageName">
    <p>Colour</p>
  </div>
  <div class="center">
    <div id="bg_01">
    </div>
    <div id="bg_02">
    </div>
    <div id="bg_03">
    </div>
    <div id="bg_04">
    </div>
    <div id="bg_05">
    </div>
  </div>
</div>


问:
Dynamic SQL to Update One table form Multiple table?
I have a table PI_Catalogue_Update which store Schema Name, Table Name, Count(*) as Volume and max(ETLRunTime) as LastUpdate from multiple original tables. How can I build a query which will use the SchemaName and TableName from PI_Catalogue_Update and query over the original tables and update the volume and LastUpdate every time I run the SP.

Probably I need some dynamic SQL. Still I can not figure out how to do.

the table looks like:

```<code>SchemaName      TableName   Volume     LastUpdate
ProdInsights_In abc         4680816    2017-06-04 00:00:00.000
ProdInsights_In bcd         52250      2017-06-04 00:00:00.000
ProdInsights_In def         744225     2017-06-04 00:00:00.000
ProdInsights_In gih         668502     2017-06-04 00:00:00.000
</code>```

The Query I have written is another way of doing, I have created a view form the original table, [ProdInsights_In].[View_Table_Catalogue].View looks Like:

```<code>CREATE VIEW  [ProdInsights_In].[View_Table_Catalogue] AS
select
  'ProdInsights_In' as SchemaName
  ,'abc' as TableName
  ,Count(*) Volume
  ,MAX(ETLRunTime) as LastUpdate
From [ProdInsights_In].[abc]
Union All
select
  'ProdInsights_In' as SchemaName
  ,'bcd' as TableName
  ,Count(*) Volume
  ,MAX(ETLRunTime) as LastUpdate
From [ProdInsights_In].[bcd]
Union All ....
</code>```

Then I am using the following SP to Update the PI_Catalogue_Update table from the View.
Procedure looks like:

```<code>MERGE
INTO    [dbo].[PI_Project_Catalogue] t1
USING   [ProdInsights_In].[View_Table_Catalogue] t2
ON      t1.SchemaName = t2.SchemaName
    and t1.TableName = t2.TableName
WHEN MATCHED THEN
UPDATE
SET     t1.Volume = t2.Volume
       ,t1.LastUpdate = t2.LastUpdate
WHEN NOT MATCHED THEN
INSERT  (SchemaName, TableName, Volume, LastUpdate)
VALUES  (t2.SchemaName. t2.TableName, t2.Volume, t2.LastUpdate)
</code>```

答:
You can avoid dynamic sql and use system views to get the row counts instead of executing select count(*) from ... for each table.

```<code>select
    [SchemaName]= s.name
  , [TableName] = o.name
  , [row_count] = p.rows
from sys.partitions p
  inner join sys.indexes i
    on p.object_id = i.object_id
      and p.index_id = i.index_id
      and i.index_id < 2
  inner join sys.objects o
    on i.object_id = o.object_id
  inner join sys.schemas s
    on o.schema_id = s.schema_id
where o.is_ms_shipped=0
</code>```

As an update:

```<code>update picu
    set [Volume] = p.rows
      , [LastUpdate] = sysutcdatetime()
from sys.partitions p
  inner join sys.indexes i
    on p.object_id = i.object_id
      and p.index_id = i.index_id
      and i.index_id < 2
  inner join sys.objects o
    on i.object_id = o.object_id
  inner join sys.schemas s
    on o.schema_id = s.schema_id
  inner join PI_Catalogue_Update picu
    on picu.SchemaName = s.name
   and picu.TableName  = o.name
</code>```

Reference:

Bad habits : Counting rows the hard way - Aaron Bertrand

To get the max(ETLRunTime) using a temporary table and a loop to update with dynamic sql:

```<code>/* --- get all tables and row count that have `ETLRunDate` column. --- */
create table #tmp (
    id int not null identity(1,1)
  , SchemaName sysname collate Latin1_General_CI_AS -- set collation to match collation of `pi_Project_Catalogue`
  , TableName  sysname collate Latin1_General_CI_AS
  , Volume bigint
  , LastUpdate date
);
insert into #tmp (SchemaName, TableName, Volume)
select
    [SchemaName]= s.name
  , [TableName] = o.name
  , [Volume] = p.rows
from sys.partitions p
  inner join sys.indexes i
    on p.object_id = i.object_id
      and p.index_id = i.index_id
      and i.index_id < 2
  inner join sys.objects o on i.object_id = o.object_id
  inner join sys.schemas s on o.schema_id = s.schema_id
where o.is_ms_shipped=0
  and exists (
    select 1
    from sys.columns c
    where c.object_id = o.object_id
      and c.name = 'ETLRunTime'
      )
/* --- loop --- */
declare @c   bigint = (select max(id) from #tmp);
declare @id  bigint = 1;
declare @sql nvarchar(4000);
declare @params nvarchar(32) = N'@id bigint';
while @id <= @c
begin;
  select @sql = N'
    update #tmp
      set LastUpdate = (
        select max(ETLRunTime)
        from '+quotename(SchemaName)+'.'+quotename(TableName)+'
      )
    where id = @id;'
  from #tmp where id = @id
  exec sp_executesql @sql, @params, @id;
set @id = @id+1;
end;
/* --- merge --- */
merge into [dbo].[pi_Project_Catalogue] with (holdlock) as tar
using #tmp as src
  on tar.SchemaName = src.SchemaName
 and tar.TableName  = src.TableName
when matched then update
  set tar.Volume     = src.Volume
    , tar.LastUpdate = src.LastUpdate
when not matched then insert (SchemaName, TableName, Volume, LastUpdate)
  values (src.SchemaName, src.TableName, src.Volume, src.LastUpdate);
</code>```

Instead of the merge that you use, you could do separate statements for update and then insert. I used merge, as that is what you have in your question, with the addition of with (holdlock).

rextester demo: http://rextester.com/HCOLM75894

returns:

```<code>+------------+-----------+--------+---------------------+
| SchemaName | TableName | Volume |     LastUpdate      |
+------------+-----------+--------+---------------------+
| dbo        | a         |      1 | 01.01.2017 00:00:00 |
| dbo        | c         |      2 | 06.06.2017 00:00:00 |
| dbo        | d         |      3 | 06.06.2017 00:00:00 |
+------------+-----------+--------+---------------------+
</code>```

using this dummy data:

```<code>create table pi_Project_Catalogue (SchemaName sysname collate Latin1_General_CI_AS, TableName sysname collate Latin1_General_CI_AS, Volume bigint, LastUpdate date)
create table a (id int not null identity(1,1) primary key clustered, ETLRunTime date)
insert into  a values ('20170101');
create table b (id int not null identity(1,1) ); -- no ETLRunTime  column
insert into  b default values
create table c (id int not null identity(1,1), ETLRunTime date );
insert into  c values (sysutcdatetime()),(sysutcdatetime());
create table d (id int not null identity(1,1), ETLRunTime date );
insert into  d values (sysutcdatetime()),(sysutcdatetime()),(sysutcdatetime());
</code>```

merge reference:

Use Caution with SQL Server''s MERGE Statement - Aaron Bertrand

UPSERT Race Condition With Merge - Dan Guzman

An Interesting MERGE Bug - Paul White

Can I optimize this merge statement - Aaron Bertrand

If you are using indexed views and MERGE, please read this! - Aaron Bertrand

The Case of the Blocking Merge Statement (LCK_M_RS_U locks) - Kendra Little

Writing t-sql merge statements the right way - David Stein

Body:
I have a table PI_Catalogue_Update which store Schema Name, Table Name, Count(*) as Volume and max(ETLRunTime) as LastUpdate from multiple original tables. How can I build a query which will use the SchemaName and TableName from PI_Catalogue_Update and query over the original tables and update the volume and LastUpdate every time I run the SP.

Probably I need some dynamic SQL. Still I can not figure out how to do.

the table looks like:

SchemaName      TableName   Volume     LastUpdate
ProdInsights_In abc         4680816    2017-06-04 00:00:00.000
ProdInsights_In bcd         52250      2017-06-04 00:00:00.000
ProdInsights_In def         744225     2017-06-04 00:00:00.000
ProdInsights_In gih         668502     2017-06-04 00:00:00.000

The Query I have written is another way of doing, I have created a view form the original table, [ProdInsights_In].[View_Table_Catalogue].View looks Like:

CREATE VIEW  [ProdInsights_In].[View_Table_Catalogue] AS
select
  'ProdInsights_In' as SchemaName
  ,'abc' as TableName
  ,Count(*) Volume
  ,MAX(ETLRunTime) as LastUpdate
From [ProdInsights_In].[abc]
Union All
select
  'ProdInsights_In' as SchemaName
  ,'bcd' as TableName
  ,Count(*) Volume
  ,MAX(ETLRunTime) as LastUpdate
From [ProdInsights_In].[bcd]
Union All ....

Then I am using the following SP to Update the PI_Catalogue_Update table from the View.
Procedure looks like:

MERGE
INTO    [dbo].[PI_Project_Catalogue] t1
USING   [ProdInsights_In].[View_Table_Catalogue] t2
ON      t1.SchemaName = t2.SchemaName
    and t1.TableName = t2.TableName
WHEN MATCHED THEN
UPDATE
SET     t1.Volume = t2.Volume
       ,t1.LastUpdate = t2.LastUpdate
WHEN NOT MATCHED THEN
INSERT  (SchemaName, TableName, Volume, LastUpdate)
VALUES  (t2.SchemaName. t2.TableName, t2.Volume, t2.LastUpdate)

Body:
You can avoid dynamic sql and use system views to get the row counts instead of executing select count(*) from ... for each table.

select
    [SchemaName]= s.name
  , [TableName] = o.name
  , [row_count] = p.rows
from sys.partitions p
  inner join sys.indexes i
    on p.object_id = i.object_id
      and p.index_id = i.index_id
      and i.index_id < 2
  inner join sys.objects o
    on i.object_id = o.object_id
  inner join sys.schemas s
    on o.schema_id = s.schema_id
where o.is_ms_shipped=0

As an update:

update picu
    set [Volume] = p.rows
      , [LastUpdate] = sysutcdatetime()
from sys.partitions p
  inner join sys.indexes i
    on p.object_id = i.object_id
      and p.index_id = i.index_id
      and i.index_id < 2
  inner join sys.objects o
    on i.object_id = o.object_id
  inner join sys.schemas s
    on o.schema_id = s.schema_id
  inner join PI_Catalogue_Update picu
    on picu.SchemaName = s.name
   and picu.TableName  = o.name

Reference:

Bad habits : Counting rows the hard way - Aaron Bertrand

To get the max(ETLRunTime) using a temporary table and a loop to update with dynamic sql:

/* --- get all tables and row count that have `ETLRunDate` column. --- */
create table #tmp (
    id int not null identity(1,1)
  , SchemaName sysname collate Latin1_General_CI_AS -- set collation to match collation of `pi_Project_Catalogue`
  , TableName  sysname collate Latin1_General_CI_AS
  , Volume bigint
  , LastUpdate date
);
insert into #tmp (SchemaName, TableName, Volume)
select
    [SchemaName]= s.name
  , [TableName] = o.name
  , [Volume] = p.rows
from sys.partitions p
  inner join sys.indexes i
    on p.object_id = i.object_id
      and p.index_id = i.index_id
      and i.index_id < 2
  inner join sys.objects o on i.object_id = o.object_id
  inner join sys.schemas s on o.schema_id = s.schema_id
where o.is_ms_shipped=0
  and exists (
    select 1
    from sys.columns c
    where c.object_id = o.object_id
      and c.name = 'ETLRunTime'
      )
/* --- loop --- */
declare @c   bigint = (select max(id) from #tmp);
declare @id  bigint = 1;
declare @sql nvarchar(4000);
declare @params nvarchar(32) = N'@id bigint';
while @id <= @c
begin;
  select @sql = N'
    update #tmp
      set LastUpdate = (
        select max(ETLRunTime)
        from '+quotename(SchemaName)+'.'+quotename(TableName)+'
      )
    where id = @id;'
  from #tmp where id = @id
  exec sp_executesql @sql, @params, @id;
set @id = @id+1;
end;
/* --- merge --- */
merge into [dbo].[pi_Project_Catalogue] with (holdlock) as tar
using #tmp as src
  on tar.SchemaName = src.SchemaName
 and tar.TableName  = src.TableName
when matched then update
  set tar.Volume     = src.Volume
    , tar.LastUpdate = src.LastUpdate
when not matched then insert (SchemaName, TableName, Volume, LastUpdate)
  values (src.SchemaName, src.TableName, src.Volume, src.LastUpdate);

Instead of the merge that you use, you could do separate statements for update and then insert. I used merge, as that is what you have in your question, with the addition of with (holdlock).

rextester demo: http://rextester.com/HCOLM75894

returns:

+------------+-----------+--------+---------------------+
| SchemaName | TableName | Volume |     LastUpdate      |
+------------+-----------+--------+---------------------+
| dbo        | a         |      1 | 01.01.2017 00:00:00 |
| dbo        | c         |      2 | 06.06.2017 00:00:00 |
| dbo        | d         |      3 | 06.06.2017 00:00:00 |
+------------+-----------+--------+---------------------+

using this dummy data:

create table pi_Project_Catalogue (SchemaName sysname collate Latin1_General_CI_AS, TableName sysname collate Latin1_General_CI_AS, Volume bigint, LastUpdate date)
create table a (id int not null identity(1,1) primary key clustered, ETLRunTime date)
insert into  a values ('20170101');
create table b (id int not null identity(1,1) ); -- no ETLRunTime  column
insert into  b default values
create table c (id int not null identity(1,1), ETLRunTime date );
insert into  c values (sysutcdatetime()),(sysutcdatetime());
create table d (id int not null identity(1,1), ETLRunTime date );
insert into  d values (sysutcdatetime()),(sysutcdatetime()),(sysutcdatetime());

merge reference:

Use Caution with SQL Server''s MERGE Statement - Aaron Bertrand

UPSERT Race Condition With Merge - Dan Guzman

An Interesting MERGE Bug - Paul White

Can I optimize this merge statement - Aaron Bertrand

If you are using indexed views and MERGE, please read this! - Aaron Bertrand

The Case of the Blocking Merge Statement (LCK_M_RS_U locks) - Kendra Little

Writing t-sql merge statements the right way - David Stein


问:
How to call a function whenever global variable changes it value?
How can I call a function change_label whenever global variable a changes its value?  With change_variable I am trying to simulate actual changing of the variable (the variable changes on button click).

```<code>from tkinter import *

a = 3

class Application(Frame):

    def __init__(self, master):
        Frame.__init__(self, master)
        self.master = master
        self.button = Button(self.master, text='Change Variable', command=self.change_variable)
        self.button.grid(row=0)
        self.label = Label(self.master, text='Test')
        self.label.grid(row=1)

    def change_label(self):
        self.label.config(bg='Red', fg='Yellow')

    def change_variable(self):
        global a
        a = 1

def main():
    root = Tk()
    Application(root)
    root.mainloop()

if __name__ == '__main__':
    main()
</code>```

答:
If you use one of tkinters special variables (StringVar, etc) you can add a "trace" that will trigger a callback whenever the variable is set or unset.

For example:

```<code>class Application(Frame):

    def __init__(self, master):
        Frame.__init__(self, master)
        ...
        self.a = tk.IntVar(value=3)
        self.a.trace("w", self.change_label)
        ...

    def change_label(self, *args):
        self.label.config(bg='Red', fg='Yellow')

    def change_variable(self):
        self.a.set(1)
</code>```

With that, whenever you set the value of self.a via the set method, the function bound with the trace will be called.

Any widget that uses that variable also will be updated. For example, change your label to this:

```<code>self.label = tk.Label(self.master, textvariable=self.a)
</code>```

When you click the button, notice that the label changes to reflect the change.

For a description of what arguments are passed to the trace function, see What are the arguments to Tkinter variable trace method callbacks?

These variables have a good description here: The Variable Classes (BooleanVar, DoubleVar, IntVar, StringVar)

Body:
How can I call a function change_label whenever global variable a changes its value?  With change_variable I am trying to simulate actual changing of the variable (the variable changes on button click).

from tkinter import *

a = 3

class Application(Frame):

    def __init__(self, master):
        Frame.__init__(self, master)
        self.master = master
        self.button = Button(self.master, text='Change Variable', command=self.change_variable)
        self.button.grid(row=0)
        self.label = Label(self.master, text='Test')
        self.label.grid(row=1)

    def change_label(self):
        self.label.config(bg='Red', fg='Yellow')

    def change_variable(self):
        global a
        a = 1

def main():
    root = Tk()
    Application(root)
    root.mainloop()

if __name__ == '__main__':
    main()

Body:
If you use one of tkinters special variables (StringVar, etc) you can add a "trace" that will trigger a callback whenever the variable is set or unset.

For example:

class Application(Frame):

    def __init__(self, master):
        Frame.__init__(self, master)
        ...
        self.a = tk.IntVar(value=3)
        self.a.trace("w", self.change_label)
        ...

    def change_label(self, *args):
        self.label.config(bg='Red', fg='Yellow')

    def change_variable(self):
        self.a.set(1)

With that, whenever you set the value of self.a via the set method, the function bound with the trace will be called.

Any widget that uses that variable also will be updated. For example, change your label to this:

self.label = tk.Label(self.master, textvariable=self.a)

When you click the button, notice that the label changes to reflect the change.

For a description of what arguments are passed to the trace function, see What are the arguments to Tkinter variable trace method callbacks?

These variables have a good description here: The Variable Classes (BooleanVar, DoubleVar, IntVar, StringVar)


问:
Any way to differentiate a building from a road in Google Maps?
So if I have a general GPS Lat/Lng point, would it be possible to say, yes this point is in a building, or this point is on a road which a car could travel on?</p>

答: Best place to ask is https://gis.stackexchange.com/. Isn't it possible to figure out the road location from the layer which contains the roads? You'll be given the lat-long's of all road nodes. Unless it's a curved line, you can find if your lat-long point lies on the road line. To convert lat-long to cartesian, follow the link.</p>


问:
Do WebSocket SendAsync() synchronously
I have a Websocket HTTPListener as a server, and the clients are WebSocket's

I keep all the current clients in a list, and I want to have a function which sends information to all the clients asynchronously.

So what I currently have is:

```<code>private async Task SendToAll(byte[] buffer)
{
    foreach (WebSocket webSocket in clients)
    {
        await Send(webSocket, buffer, buffer.Length);
    }
}

private async Task Send(WebSocket webSocket, byte[] buffer, int bufferLength)
{
    try
    {
        await webSocket.SendAsync(
            new ArraySegment<byte>(buffer, 0, bufferLength),
            WebSocketMessageType.Text, true,
            CancellationToken.None);
    }
    catch (WebSocketException ex)
    {
        RemoveClient(webSocket, WebSocketCloseStatus.InternalServerError, ex.Message);
    }
}
</code>```

Problem is, if a have a big number of clients I'm opening a meaningful number of threads, which is a waste to me. So I thought that the Send() function could occur synchronously, but WebSockets doesn't have a synchronous functions, which is strange to me.

As I believe it's not a good practice to run Task functions synchronously, is there a good way of doing it? I don't want just to drop the await.

答:
Problem is, if a have a big number of clients I'm opening a meaningful number of threads, which is a waste to me.

Two questions:

Have you measured the threads? How much exactly is "a meaningful number"?

Does the performance testing indicate that these threads are a "waste"?

Since writing to a network socket doesn't consume a thread, the code is already making appropriate use of the thread pool. I would not expect the number of threads to increase significantly in this code. If there are a handful of additional threads being created, then it's because those additional threads are useful. It's difficult to do better for such I/O-bound operations.

On an unrelated side note, I would recommend sending to all clients concurrently, rather than one at a time:

```<code>private async Task SendToAll(byte[] buffer)
{
  var tasks = clients.Select(webSocket => Send(webSocket, buffer, buffer.Length));
  await Task.WhenAll(tasks);
}
</code>```

Title: Do WebSocket SendAsync() synchronously

Body:
I have a Websocket HTTPListener as a server, and the clients are WebSocket's

I keep all the current clients in a list, and I want to have a function which sends information to all the clients asynchronously.

So what I currently have is:

private async Task SendToAll(byte[] buffer)
{
    foreach (WebSocket webSocket in clients)
    {
        await Send(webSocket, buffer, buffer.Length);
    }
}

private async Task Send(WebSocket webSocket, byte[] buffer, int bufferLength)
{
    try
    {
        await webSocket.SendAsync(
            new ArraySegment<byte>(buffer, 0, bufferLength),
            WebSocketMessageType.Text, true,
            CancellationToken.None);
    }
    catch (WebSocketException ex)
    {
        RemoveClient(webSocket, WebSocketCloseStatus.InternalServerError, ex.Message);
    }
}

Problem is, if a have a big number of clients I'm opening a meaningful number of threads, which is a waste to me. So I thought that the Send() function could occur synchronously, but WebSockets doesn't have a synchronous functions, which is strange to me.

As I believe it's not a good practice to run Task functions synchronously, is there a good way of doing it? I don't want just to drop the await.

Body:
Problem is, if a have a big number of clients I'm opening a meaningful number of threads, which is a waste to me.

Two questions:

Have you measured the threads? How much exactly is "a meaningful number"?

Does the performance testing indicate that these threads are a "waste"?

Since writing to a network socket doesn't consume a thread, the code is already making appropriate use of the thread pool. I would not expect the number of threads to increase significantly in this code. If there are a handful of additional threads being created, then it's because those additional threads are useful. It's difficult to do better for such I/O-bound operations.

On an unrelated side note, I would recommend sending to all clients concurrently, rather than one at a time:

private async Task SendToAll(byte[] buffer)
{
  var tasks = clients.Select(webSocket => Send(webSocket, buffer, buffer.Length));
  await Task.WhenAll(tasks);
}


问:
Angular Adding items from multiple arrays into Json object
I have 3 sets of Json data

```<code>data1 [{id:1, systemName: "foo", moreInfo: "blah},
       {id:2, systemName: "boo", moreInfo: "blahBlah}]

data2 [{systemName: "foo",count: 21},
       {systemName: "boo",count: 454}]

data3 [{systemName: "foo",count: 643},
       {systemName: "boo",count: 674}]
</code>```

what I require is to take the counts from data 2 and 3 and add them to their respective objects in data1 with new name like data2Count and Data3Count

so data1 would look like this:

```<code>data1 [{id:1, systemName: "foo", moreInfo: "blah, data2Count: 21, data3Count: 643},
       {id:2, systemName: "boo", moreInfo: "blahBlah, data2Count: 454, data3Count: 674}]
</code>```

Currently I can only achieve this:

```<code>data1 [{id:1, systemName: "foo", moreInfo: "blah"}
       {id:2, systemName: "boo", moreInfo: "blahBlah"} data2Count: 454]
</code>```

Using:

```<code>angular.forEach(data1, function(value1, key1) {
    angular.forEach(data2, function(value0, key0) {
        if (value1.systemName === value1.systemName) {
            $scope.sysFlow.data2Count = value1.count
        }
    })
})
</code>```

答:
You can use Array#map to do something like this:

var data1 = [
    {id:1, systemName: "foo", moreInfo: "blah"},
    {id:2, systemName: "boo", moreInfo: "blahBlah"}
  ]

var data2 = [
    {systemName: "foo",count: 21},
    {systemName: "boo",count: 454}
  ]

var data3 = [
    {systemName: "foo",count: 643},
    {systemName: "boo",count: 674}
  ]

data1 = data1.map(function(obj) {

  obj.data2Count = data2.filter(function(o) {
    return o.systemName === obj.systemName
  })[0].count;

  obj.data3Count = data3.filter(function(o) {
    return o.systemName === obj.systemName
  })[0].count;

  return obj;
})

console.log(data1)```

Body:
I have 3 sets of Json data

data1 [{id:1, systemName: "foo", moreInfo: "blah},
       {id:2, systemName: "boo", moreInfo: "blahBlah}]

data2 [{systemName: "foo",count: 21},
       {systemName: "boo",count: 454}]

data3 [{systemName: "foo",count: 643},
       {systemName: "boo",count: 674}]

what I require is to take the counts from data 2 and 3 and add them to their respective objects in data1 with new name like data2Count and Data3Count

so data1 would look like this:

data1 [{id:1, systemName: "foo", moreInfo: "blah, data2Count: 21, data3Count: 643},
       {id:2, systemName: "boo", moreInfo: "blahBlah, data2Count: 454, data3Count: 674}]

Currently I can only achieve this:

data1 [{id:1, systemName: "foo", moreInfo: "blah"}
       {id:2, systemName: "boo", moreInfo: "blahBlah"} data2Count: 454]

Using:

angular.forEach(data1, function(value1, key1) {
    angular.forEach(data2, function(value0, key0) {
        if (value1.systemName === value1.systemName) {
            $scope.sysFlow.data2Count = value1.count
        }
    })
})


问:
OrientDB can full fill requirement of Solr or ElasticSearch
I have just started working on OrientDB, with OrientDB for search engine which tool we have to use Solr or ElasticSearch (driver compatibility). I also read somewhere that orientdb is giving Lucene Search itself if we define the index is different type. So if this is true then what about speed because Solr and **Elasticsearch ** serving data from primary memory.

Please suggest can OrientDB's internal functionality full fill search requirement so we use this instead of Solr or ElasticSearch.

答:
I'm the maintainer of the full text and spatial indexes of OrientDB.

First of all, here's the link to the documentation, just to have an overview:

http://orientdb.com/docs/last/Full-Text-Index.html

What do we offer?
We enable to define an index on one or more property of a Class (e.g. a Table) that uses Lucene as engine. This allow to perform queries where the full Lucene grammar could be used:

```<code>SELECT from Person WHERE Description LUCENE "progra* +senior -ruby"
</code>```

You can configure analyzers and stopwords, but for sure we cannot provide the same set of features  ES or SOLR are able to.

We are improving that component for the next 3.0: more like this, highlighting, query parser configuration at query time, custom analyzer configuration.

These will improve the user experience, allowing to explore the graph in a completely different way.

In my opinion, if your main target is search, ES or SOLR fit best: they are full of features about text!

On the other end, if you need a database to store data with strong relationships and would like to provide full text search done right (based on lucene) and even spatial search, OrientDB can help you.

Body:
I'm the maintainer of the full text and spatial indexes of OrientDB.

First of all, here's the link to the documentation, just to have an overview:

http://orientdb.com/docs/last/Full-Text-Index.html

What do we offer?
We enable to define an index on one or more property of a Class (e.g. a Table) that uses Lucene as engine. This allow to perform queries where the full Lucene grammar could be used:

SELECT from Person WHERE Description LUCENE "progra* +senior -ruby"

You can configure analyzers and stopwords, but for sure we cannot provide the same set of features  ES or SOLR are able to.

We are improving that component for the next 3.0: more like this, highlighting, query parser configuration at query time, custom analyzer configuration.

These will improve the user experience, allowing to explore the graph in a completely different way.

In my opinion, if your main target is search, ES or SOLR fit best: they are full of features about text!

On the other end, if you need a database to store data with strong relationships and would like to provide full text search done right (based on lucene) and even spatial search, OrientDB can help you.


问:
get a particular host name's ip with ansible
I have a host file that looks roughly like this:

```<code>[kibanamaster]
efk host_ip host user passwd
[elasticnode]
esnode host_ip user passwd
</code>```

and I am trying something in the style of

```<code>- name: get ip address node1
  debug: var=hostvars[inventory_host]['esnode']['ansible_default_ipv4']['address']
  register: es_node1
</code>```

But I get variable not defined. Anyone outthere able to help?

EDIT:
If I do

```<code>debug: var=hostvars[LOG1]['esnode']['ansible_default_ipv4']['address']
register: node_1
</code>```

I get

{"hostvars[LOG1]['ansible_default_ipv4']['address']": "VARIABLE IS NOT DEFINED!"}

答:
hostvars magic variable is a dictionary with keys named after hosts in your inventory.

So you may want to try:

```<code>hostvars['esnode']['ansible_default_ipv4']['address']
</code>```

to get ip address of esnode host.

Body:
I have a host file that looks roughly like this:

[kibanamaster]
efk host_ip host user passwd
[elasticnode]
esnode host_ip user passwd

and I am trying something in the style of

- name: get ip address node1
  debug: var=hostvars[inventory_host]['esnode']['ansible_default_ipv4']['address']
  register: es_node1

But I get variable not defined. Anyone outthere able to help?

EDIT:
If I do

debug: var=hostvars[LOG1]['esnode']['ansible_default_ipv4']['address']
register: node_1

I get

{"hostvars[LOG1]['ansible_default_ipv4']['address']": "VARIABLE IS NOT DEFINED!"}

Body:
hostvars magic variable is a dictionary with keys named after hosts in your inventory.

So you may want to try:

hostvars['esnode']['ansible_default_ipv4']['address']

to get ip address of esnode host.


问:
returns null mysql nodejs
please have a look at the dbfn.js file

```<code>/*database function file;*/

var db = require('./connection');

function check_conn(){
    if(db){
        console.log('We are connected to Database server'.bgGreen);
        return true;
    }else{
        console.log('We are not connected to DataBase server'.bgRed);
        return false;
    }
}

module.exports = {

    testCon : function(){
        if(check_conn() === true){
            return 'We are connected to DB';
        }else return 'We are not connected to DB';
    },

    get_user : function(){
        db.query('SELECT * FROM users',function(err,results,fields){
            if(err){
                console.log(err)
                return err;
            }
            if(results){
                console.log(results);
                return results;
            }
            console.log('nothing...');
        });
    }
};
</code>```

Now, look at routes.js file

```<code>var db = require('./dbfn');

module.exports = function(app){

    /*
        Routing starts here
    */

    //root route
    app.get('/', function(req, res){
        res.render('index.ejs');
    });

    //test route
    app.get('/test',function(req,res){

        var x = db.get_user();
        console.log(x);
        res.writeHead(200, {'Content-Type': 'text/json'});
        res.json(x);
    });

    //default it should stay at bottom
    app.get('*',function (req, res) {
        //res.redirect('/');
        res.send(404);
    });
}
</code>```

console.log on dbfn file writes full object from MySQL database but when I call it on routes.js file as var x it null I really don't understands how actually I can overcome with that. Yes, I am new student to NodeJs

Thanks.

答:
You can't return from an asynchronous call inside a synchronous function. Instead, you need to pass a callback to get_user() like this:

dbfn.js

```<code>var db = require('./connection');

function check_conn(){
    if(db){
        console.log('We are connected to Database server'.bgGreen);
        return true;
    }else{
        console.log('We are not connected to DataBase server'.bgRed);
        return false;
    }
}

module.exports = {

    testCon : function(){
        if(check_conn() === true){
            return 'We are connected to DB';
        }else return 'We are not connected to DB';
    },

    get_user : function(cb){
        db.query('SELECT * FROM users',function(err,results,fields){
            if(err){
                console.log(err)
                cb(err);
            }
            if(results){
                console.log(results);
                cb(null, results);
            }
            console.log('nothing...');
        });
    }

};
</code>```

routes.js

```<code>var db = require('./dbfn');

module.exports = function(app){

    /*
        Routing starts here
    */

    //root route
    app.get('/', function(req, res){
        res.render('index.ejs');
    });

    //test route
    app.get('/test',function(req,res){

        db.get_user(function(err, response) {
            if(err) {
                // handle error
            }
            else {
                var x = response;
                console.log(x);
                res.writeHead(200, {'Content-Type': 'text/json'});
                res.json(x);
            }
        });

    });

    //default it should stay at bottom
    app.get('*',function (req, res) {
        //res.redirect('/');
        res.send(404);
    });
}
</code>```

Now, the code within the callback will only fire once the DB query has completed.

Title: returns null mysql nodejs

Body:
please have a look at the dbfn.js file

/*database function file;*/

var db = require('./connection');

function check_conn(){
    if(db){
        console.log('We are connected to Database server'.bgGreen);
        return true;
    }else{
        console.log('We are not connected to DataBase server'.bgRed);
        return false;
    }
}

module.exports = {

    testCon : function(){
        if(check_conn() === true){
            return 'We are connected to DB';
        }else return 'We are not connected to DB';
    },

    get_user : function(){
        db.query('SELECT * FROM users',function(err,results,fields){
            if(err){
                console.log(err)
                return err;
            }
            if(results){
                console.log(results);
                return results;
            }
            console.log('nothing...');
        });
    }
};

Now, look at routes.js file

var db = require('./dbfn');

module.exports = function(app){

    /*
        Routing starts here
    */

    //root route
    app.get('/', function(req, res){
        res.render('index.ejs');
    });

    //test route
    app.get('/test',function(req,res){

        var x = db.get_user();
        console.log(x);
        res.writeHead(200, {'Content-Type': 'text/json'});
        res.json(x);
    });

    //default it should stay at bottom
    app.get('*',function (req, res) {
        //res.redirect('/');
        res.send(404);
    });
}

console.log on dbfn file writes full object from MySQL database but when I call it on routes.js file as var x it null I really don't understands how actually I can overcome with that. Yes, I am new student to NodeJs

Thanks.

Body:
You can't return from an asynchronous call inside a synchronous function. Instead, you need to pass a callback to get_user() like this:

dbfn.js

var db = require('./connection');

function check_conn(){
    if(db){
        console.log('We are connected to Database server'.bgGreen);
        return true;
    }else{
        console.log('We are not connected to DataBase server'.bgRed);
        return false;
    }
}

module.exports = {

    testCon : function(){
        if(check_conn() === true){
            return 'We are connected to DB';
        }else return 'We are not connected to DB';
    },

    get_user : function(cb){
        db.query('SELECT * FROM users',function(err,results,fields){
            if(err){
                console.log(err)
                cb(err);
            }
            if(results){
                console.log(results);
                cb(null, results);
            }
            console.log('nothing...');
        });
    }

};

routes.js

var db = require('./dbfn');

module.exports = function(app){

    /*
        Routing starts here
    */

    //root route
    app.get('/', function(req, res){
        res.render('index.ejs');
    });

    //test route
    app.get('/test',function(req,res){

        db.get_user(function(err, response) {
            if(err) {
                // handle error
            }
            else {
                var x = response;
                console.log(x);
                res.writeHead(200, {'Content-Type': 'text/json'});
                res.json(x);
            }
        });

    });

    //default it should stay at bottom
    app.get('*',function (req, res) {
        //res.redirect('/');
        res.send(404);
    });
}

Now, the code within the callback will only fire once the DB query has completed.


问:
Displaying from multiple table based on the time and showing the source table
So, for example, I have 3 tables

Table 1: name

```<code>id | name | time
 1 | Bob  | 20.42
</code>```

Table 2: item

```<code>id | item   | time
 1 | Bottle | 18.42
 2 | Box    | 21.42
</code>```

Table 3: food

```<code>id | Food | time
1 | Steak | 19.42
</code>```

So I want to display them like this

```<code>From table item: 1 | Bottle
From table food: 1 | Steak
From table name: 1 | Bob
From table item: 2 | Box
</code>```

答:
```<code>DROP TABLE IF EXISTS name;

CREATE TABLE name
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,name VARCHAR(12) NOT NULL
,time TIME NOT NULL
);

INSERT INTO name VALUES
(1,'Bob','20:42:00');

DROP TABLE IF EXISTS item;

CREATE TABLE item
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,item VARCHAR(12) NOT NULL
,time TIME NOT NULL
);

INSERT INTO item VALUES
(1,'Bottle','18:42:00'),
(2,'Box','21:42:00');

DROP TABLE IF EXISTS food;

CREATE TABLE food
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,food VARCHAR(12) NOT NULL
,time TIME NOT NULL
);

INSERT INTO food VALUES
(1,'Steak','19:42');

SELECT *, 'name' source FROM name
UNION ALL
SELECT *, 'item' FROM item
UNION ALL
SELECT *, 'food' FROM food
ORDER BY time;
+----+--------+----------+--------+
| id | name   | time     | source |
+----+--------+----------+--------+
|  1 | Bottle | 18:42:00 | item   |
|  1 | Steak  | 19:42:00 | food   |
|  1 | Bob    | 20:42:00 | name   |
|  2 | Box    | 21:42:00 | item   |
+----+--------+----------+--------+
</code>```

Body:
So, for example, I have 3 tables

Table 1: name

id | name | time
 1 | Bob  | 20.42

Table 2: item

id | item   | time
 1 | Bottle | 18.42
 2 | Box    | 21.42

Table 3: food

id | Food | time
1 | Steak | 19.42

So I want to display them like this

From table item: 1 | Bottle
From table food: 1 | Steak
From table name: 1 | Bob
From table item: 2 | Box


问:
Login with google BAD_AUTHENTICATION issue
```<code>E/Auth: [GoogleAccountDataServiceImpl] getToken() -> BAD_AUTHENTICATION. Account: <ELLIDED:652354120>, App: com.google.android.apps.maps, Service: oauth2:https://www.googleapis.com/auth/mobilemaps.firstparty
                                           efl: Long live credential not available.
                                               at efm.b(:com.google.android.gms:3117)
                                               at efm.a(:com.google.android.gms:119)
                                               at edt.a(:com.google.android.gms:437)
                                               at eds.a(:com.google.android.gms:31404)
                                               at eds.a(:com.google.android.gms:297)
                                               at flg.a(:com.google.android.gms:1189)
                                               at flf.a(:com.google.android.gms:480)
                                               at flf.a(:com.google.android.gms:185)
                                               at eaa.a(:com.google.android.gms:370)
                                               at eaa.a(:com.google.android.gms:225)
                                               at bwf.onTransact(:com.google.android.gms:137)
                                               at android.os.Binder.transact(Binder.java:380)
                                               at byl.onTransact(:com.google.android.gms:35)
                                               at android.os.Binder.execTransact(Binder.java:446)
</code>```

I have added SHA1 to signed apk and replaced google-services.json with new one. After release on app store getting this issue when going to login with google.

答:
It seems like you have a configuration issue with Firebase, Google API console and google-services.json file.

You would be aware of that release APK and debug APK have different SHA1 and different API keys for Google Services. So you need to add both of them on Firebase inside Project Setting. After doing this you need to download google-services.json file and put it in your project. Create a fresh release build with your keystore and publish you app on Google Play store.

Hope it helps.

Body:
E/Auth: [GoogleAccountDataServiceImpl] getToken() -> BAD_AUTHENTICATION. Account: <ELLIDED:652354120>, App: com.google.android.apps.maps, Service: oauth2:https://www.googleapis.com/auth/mobilemaps.firstparty
                                           efl: Long live credential not available.
                                               at efm.b(:com.google.android.gms:3117)
                                               at efm.a(:com.google.android.gms:119)
                                               at edt.a(:com.google.android.gms:437)
                                               at eds.a(:com.google.android.gms:31404)
                                               at eds.a(:com.google.android.gms:297)
                                               at flg.a(:com.google.android.gms:1189)
                                               at flf.a(:com.google.android.gms:480)
                                               at flf.a(:com.google.android.gms:185)
                                               at eaa.a(:com.google.android.gms:370)
                                               at eaa.a(:com.google.android.gms:225)
                                               at bwf.onTransact(:com.google.android.gms:137)
                                               at android.os.Binder.transact(Binder.java:380)
                                               at byl.onTransact(:com.google.android.gms:35)
                                               at android.os.Binder.execTransact(Binder.java:446)

I have added SHA1 to signed apk and replaced google-services.json with new one. After release on app store getting this issue when going to login with google.


问:
jacksonMessageConverter corrupt mp3 file as octet encode response
I have a spring MVC config with the following:

```<code>       public class SpringConfiguration extends WebMvcConfigurerAdapter {
        public MappingJackson2HttpMessageConverter jacksonMessageConverter() {
            MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();

            ObjectMapper mapper = new ObjectMapper();
            //Registering Hibernate4Module to support lazy objects
            mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            mapper.registerModule(new Hibernate4Module());

            messageConverter.setObjectMapper(mapper);
            return messageConverter;
        }
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        //Here we add our custom-configured HttpMessageConverter
        converters.add(jacksonMessageConverter());
        super.configureMessageConverters(converters);
        }
      }
</code>```

The previous method used to ignore all lazy relation without adding JsonIgnore in model
The problem is I have a route to steam mp3 file as an octet response as following

```<code>@GetMapping(value = "/audio/{id}")
public ResponseEntity<byte[]> streamMp3FileToAdmin(@PathVariable Integer id) {
    CorporateCampaign camp = corporateCampaignService.findById(id);
    final HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    return new ResponseEntity<byte[]>(Utilities.getFileAsBytes(camp.getVoiceUrl()),httpHeaders,HttpStatus.OK);
}
</code>```

If I remove jackson message converter the steaming works fine but when I add jackson message converter the stream doesn't work any more

I read this question Spring MVC: How to return image in @ResponseBody?

and a lot but I didn't find a solution yet

答: You need to add produces = MediaType.APPLICATION_OCTET_STREAM to the @GetMapping(value = "/audio/{id}") to specify produced result content type and let browser recognize it properly.

Body:
I have a spring MVC config with the following:

       public class SpringConfiguration extends WebMvcConfigurerAdapter {
        public MappingJackson2HttpMessageConverter jacksonMessageConverter() {
            MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();

            ObjectMapper mapper = new ObjectMapper();
            //Registering Hibernate4Module to support lazy objects
            mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            mapper.registerModule(new Hibernate4Module());

            messageConverter.setObjectMapper(mapper);
            return messageConverter;
        }
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        //Here we add our custom-configured HttpMessageConverter
        converters.add(jacksonMessageConverter());
        super.configureMessageConverters(converters);
        }
      }

The previous method used to ignore all lazy relation without adding JsonIgnore in model
The problem is I have a route to steam mp3 file as an octet response as following

@GetMapping(value = "/audio/{id}")
public ResponseEntity<byte[]> streamMp3FileToAdmin(@PathVariable Integer id) {
    CorporateCampaign camp = corporateCampaignService.findById(id);
    final HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    return new ResponseEntity<byte[]>(Utilities.getFileAsBytes(camp.getVoiceUrl()),httpHeaders,HttpStatus.OK);
}

If I remove jackson message converter the steaming works fine but when I add jackson message converter the stream doesn't work any more

I read this question Spring MVC: How to return image in @ResponseBody?

and a lot but I didn't find a solution yet


问:
Unable to compile _ssl in python on solaris 10
I'm trying to compile python 2.7.9 on a Sparc Solaris 10 machine. I've managed to successfully install it, except for _ssl:

```<code>Python build finished, but the necessary bits to build these modules were not found:
_bsddb             _ssl               _tkinter
bsddb185           gdbm               linuxaudiodev
ossaudiodev
</code>```

OpenSSL is installed, and the libs and includes are here:

libs here:  /usr/sfw/lib and includes here: /usr/sfw/include/openssl

The libs are:

```<code>lrwxrwxrwx   1 root     root          17 May 16  2014 libssl.so -> ./libssl.so.0.9.7
-rwxr-xr-x   1 root     bin      1424312 Jun 27  2013 libssl.so.0.9.7
-rwxr-xr-x   1 root     bin       151540 Jun 27  2013 libssl_extra.so.0.9.7
-rw-r--r--   1 root     bin          293 Jan 22  2005 llib-lssl
-rw-r--r--   1 root     bin       279739 Jun 21  2013 llib-lssl.ln
</code>```

So, after some research it appears that python only checks for the existence of the libs in the standard paths:

e.g. /usr/local/ssl/lib & /usr/local/ssl/include

The process to resolve it is to (I believe) edit setup.py in the source tree and add the paths to these sections like:

```<code>    ssl_libs = find_library_file(self.compiler, 'ssl',lib_dirs,
                                 ['/usr/sfw/lib',
                                  '/usr/local/ssl/lib',
                                  '/usr/contrib/ssl/lib/'
                                 ] )
</code>```

...and...

```<code>    search_for_ssl_incs_in = [
                          '/usr/sfw/include/openssl',
                          '/usr/local/ssl/include',
                          '/usr/contrib/ssl/include/'
                         ]
</code>```

I am cleaning, then running this configure again:

```<code>./configure --prefix=/opt/python-2.7.9 --enable-shared
</code>```

...then re-compiling using dmake.

It is still unable to find the libs. Is my method for working-around this correct?

Much appreciated.

答:
In addition to Joey Wilhelm's response,

If you are compiling python 2.7.9 or any other version (like me on python 2.7.12).

Certain required dependencies should be present your machine :

In case of ubuntu :

apt-get install libreadline-gplv2-dev libncursesw5-dev libssl-dev libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev -y

the above command downloads required dependencies

In case of Solaris :

Equivalent dependencies should be present on your machine.
If they are not present, use the below link to download. (Make sure internet access is available)

/usr/sbin/pkgadd  -d http://get.opencsw.org/now
/opt/csw/bin/pkgutil -U

Load all dependencies which are present for (https://www.opencsw.org/package/python/) and other dependencies as mentioned above for ubuntu. These packages are available on (https://www.opencsw.org/get-it/packages/)

For openssl it is required that libssl.so should be available on path, if you do not have it you can install openssl at custom location.

My Custom Location for extra installation : /tmp/local

(You can also use standard /usr/local, but for me those locations are readonly)

curl https://www.openssl.org/source/openssl-1.0.2l.tar.gz | tar xz && cd openssl-1.0.2l && ./config shared --prefix=/tmp/local/ && make && make install

If you already have zlib (data compression) no need for below mentioned step, else follow :

Download zlib from https://zlib.net/fossils/zlib-1.2.11.tar.gz

```<code>    tar -xvf zlib-1.2.11.tar.gz
    cd zlib-1.2.11
    ./configure --prefix=/tmp/local
    make
    make install
</code>```

These dependencies should be present under appropriate path for the compiler at runtime :

Python install script

```<code>    export LDFLAGS="-L/tmp/local/lib/ -L/usr/local/lib/"

    # Path /opt/csw/lib/ makes sure that required libraries that we downloaded are available to the compiler
    export LD_LIBRARY_PATH="/tmp/local/lib/:/opt/csw/lib/:/usr/local/lib/"
    export CPPFLAGS="-I/tmp/local/include -I/tmp/local/include/openssl"
    export CFLAGS="-I/tmp/local/include -I/tmp/local/include/openssl"

    wget https://www.python.org/ftp/python/2.7.12/Python-2.7.12.tgz | tar xzf Python-2.7.12.tgz && cd Python-2.7.12
    ./configure --prefix=/tmp/python/
    make install
</code>```

Finally your python build would be available at /tmp/python (appropriate path can be chosen)

Default build will be 32bit python. Incase if you wish to build 64bit python you need to import corresponding 64bit libraries and keep them in path.

Note :

Important path's for 64 bit python build generation are

/opt/csw/lib/sparcv9

/opt/csw/lib/64

Setting of -m64 bit is also important in the flags

If you have /usr/sfw/lib/libssl.so file you would not need to build a custom openssl you can add /usr/sfw/lib/ and /usr/sfw/include path in the flags.

Make sure you build openssl with command :

```<code>cd openssl-1.0.1e
./Configure solaris64-sparcv9-cc --prefix=<path> shared
make
make install
</code>```

To verify 64 bit python install :

Python 2.7.12 (default, Jun  6 2017, 08:34:21)

GCC 4.5.2] on sunos5

import platform

platform.architecture()

('64bit', 'ELF')

Body:
I'm trying to compile python 2.7.9 on a Sparc Solaris 10 machine. I've managed to successfully install it, except for _ssl:

Python build finished, but the necessary bits to build these modules were not found:
_bsddb             _ssl               _tkinter
bsddb185           gdbm               linuxaudiodev
ossaudiodev

OpenSSL is installed, and the libs and includes are here:

libs here:  /usr/sfw/lib and includes here: /usr/sfw/include/openssl

The libs are:

lrwxrwxrwx   1 root     root          17 May 16  2014 libssl.so -> ./libssl.so.0.9.7
-rwxr-xr-x   1 root     bin      1424312 Jun 27  2013 libssl.so.0.9.7
-rwxr-xr-x   1 root     bin       151540 Jun 27  2013 libssl_extra.so.0.9.7
-rw-r--r--   1 root     bin          293 Jan 22  2005 llib-lssl
-rw-r--r--   1 root     bin       279739 Jun 21  2013 llib-lssl.ln

So, after some research it appears that python only checks for the existence of the libs in the standard paths:

e.g. /usr/local/ssl/lib & /usr/local/ssl/include

The process to resolve it is to (I believe) edit setup.py in the source tree and add the paths to these sections like:

    ssl_libs = find_library_file(self.compiler, 'ssl',lib_dirs,
                                 ['/usr/sfw/lib',
                                  '/usr/local/ssl/lib',
                                  '/usr/contrib/ssl/lib/'
                                 ] )

...and...

    search_for_ssl_incs_in = [
                          '/usr/sfw/include/openssl',
                          '/usr/local/ssl/include',
                          '/usr/contrib/ssl/include/'
                         ]

I am cleaning, then running this configure again:

./configure --prefix=/opt/python-2.7.9 --enable-shared

...then re-compiling using dmake.

It is still unable to find the libs. Is my method for working-around this correct?

Much appreciated.

Body:
In addition to Joey Wilhelm's response,

If you are compiling python 2.7.9 or any other version (like me on python 2.7.12).

Certain required dependencies should be present your machine :

In case of ubuntu :

apt-get install libreadline-gplv2-dev libncursesw5-dev libssl-dev libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev -y

the above command downloads required dependencies

In case of Solaris :

Equivalent dependencies should be present on your machine.
If they are not present, use the below link to download. (Make sure internet access is available)

/usr/sbin/pkgadd  -d http://get.opencsw.org/now
/opt/csw/bin/pkgutil -U

Load all dependencies which are present for (https://www.opencsw.org/package/python/) and other dependencies as mentioned above for ubuntu. These packages are available on (https://www.opencsw.org/get-it/packages/)

For openssl it is required that libssl.so should be available on path, if you do not have it you can install openssl at custom location.

My Custom Location for extra installation : /tmp/local

(You can also use standard /usr/local, but for me those locations are readonly)

curl https://www.openssl.org/source/openssl-1.0.2l.tar.gz | tar xz && cd openssl-1.0.2l && ./config shared --prefix=/tmp/local/ && make && make install

If you already have zlib (data compression) no need for below mentioned step, else follow :

Download zlib from https://zlib.net/fossils/zlib-1.2.11.tar.gz

    tar -xvf zlib-1.2.11.tar.gz
    cd zlib-1.2.11
    ./configure --prefix=/tmp/local
    make
    make install

These dependencies should be present under appropriate path for the compiler at runtime :

Python install script

    export LDFLAGS="-L/tmp/local/lib/ -L/usr/local/lib/"

    # Path /opt/csw/lib/ makes sure that required libraries that we downloaded are available to the compiler
    export LD_LIBRARY_PATH="/tmp/local/lib/:/opt/csw/lib/:/usr/local/lib/"
    export CPPFLAGS="-I/tmp/local/include -I/tmp/local/include/openssl"
    export CFLAGS="-I/tmp/local/include -I/tmp/local/include/openssl"

    wget https://www.python.org/ftp/python/2.7.12/Python-2.7.12.tgz | tar xzf Python-2.7.12.tgz && cd Python-2.7.12
    ./configure --prefix=/tmp/python/
    make install

Finally your python build would be available at /tmp/python (appropriate path can be chosen)

Default build will be 32bit python. Incase if you wish to build 64bit python you need to import corresponding 64bit libraries and keep them in path.

Note :

Important path's for 64 bit python build generation are

/opt/csw/lib/sparcv9

/opt/csw/lib/64

Setting of -m64 bit is also important in the flags

If you have /usr/sfw/lib/libssl.so file you would not need to build a custom openssl you can add /usr/sfw/lib/ and /usr/sfw/include path in the flags.

Make sure you build openssl with command :

cd openssl-1.0.1e
./Configure solaris64-sparcv9-cc --prefix=<path> shared
make
make install

To verify 64 bit python install :

Python 2.7.12 (default, Jun  6 2017, 08:34:21)

GCC 4.5.2] on sunos5

import platform

platform.architecture()

('64bit', 'ELF')