问:
Tooltip cutoff at the edge of the containing element
I have the following html:

```<code><div class="container">
  <span class="word-container" >
    <span tooltip-def="To sign or give formal approval to.">
      <span class="define-word highlight-word">ratifying</span>
    </span>
  </span>
</div>
</code>```

CSS:

```<code>.container {
  margin-top: 100px;
}
.word-container [tooltip-def] {
  display: inline-block;
  position: relative;
}
.word-container [tooltip-def]:before {
  left: 50%;
  position: absolute;
  transform: translateX(-50%);
  border-color: #323232 transparent transparent transparent;
  border-style: solid;
  border-width: 4px 6px 0 6px;
  content: "";
  display: none;
  top: -6px;
  z-index: 99;
}
.word-container [tooltip-def]:after {
  left: 50%;
  position: absolute;
  transform: translateX(-50%);
  content: attr(tooltip-def);
  background: #323232;
  border-radius: 5px;
  color: #fff;
  display: none;
  font-family: open sans;
  font-size: 12px;
  height: auto;
  min-width: 250px;
  padding: 5px;
  text-align: center;
  top: -6px;
  transform: translateX(-50%) translateY(-100%);
  width: auto;
  z-index: 99;
}
.word-container [tooltip-def]:hover:after,
.word-container [tooltip-def]:hover:before {
  display: inline-block;
}
</code>```

The tooltip is cut off on the left side. I tried overflow: visible and higher z-index on .word-container [tooltip-def]:after, but none of the working.

Here is the jsfiddle demo: https://jsfiddle.net/mddc/5dtwr6zc/10/

How can I make minimal CSS changes to make the tooltip visible? Move to the right side when the left side touches the browser edge?

答:
I've made the changes which can be viewed in the fiddle below

https://jsfiddle.net/5dtwr6zc/14/

```<code>.test{
 overflow: visible;
}
.container {
  margin-top: 100px;
}
.word-container [tooltip-def] {
  display: inline-block;
  position: relative;
}
.word-container [tooltip-def]:before {
  left: 50%;
  position: absolute;
  transform: translateX(-50%);
  border-color: #323232 transparent transparent transparent;
  border-style: solid;
  border-width: 4px 6px 0 6px;
  content: "";
  display: none;
  top: -6px;
  z-index: 99;
}
.word-container [tooltip-def]:after {
  left: 150%;
  position: absolute;
  transform: translateX(-47%);
  content: attr(tooltip-def);
  background: #323232;
  border-radius: 5px;
  color: #fff;
  display: none;
  font-family: open sans;
  font-size: 12px;
  height: auto;
  min-width: 250px;
  padding: 5px;
  text-align: center;
  top: -6px;
  transform: translateX(-50%) translateY(-100%);
  width: auto;
  z-index: 99;
}
.word-container [tooltip-def]:hover:after,
.word-container [tooltip-def]:hover:before {
  display: inline-block;
}
</code>```

The problem was the positioning of the after psuedo element. But I would strongly suggest to make the positioning dynamic as per the context using JavaScript

Body:
I have the following html:

      ratifying

CSS:

.container {
  margin-top: 100px;
}
.word-container [tooltip-def] {
  display: inline-block;
  position: relative;
}
.word-container [tooltip-def]:before {
  left: 50%;
  position: absolute;
  transform: translateX(-50%);
  border-color: #323232 transparent transparent transparent;
  border-style: solid;
  border-width: 4px 6px 0 6px;
  content: "";
  display: none;
  top: -6px;
  z-index: 99;
}
.word-container [tooltip-def]:after {
  left: 50%;
  position: absolute;
  transform: translateX(-50%);
  content: attr(tooltip-def);
  background: #323232;
  border-radius: 5px;
  color: #fff;
  display: none;
  font-family: open sans;
  font-size: 12px;
  height: auto;
  min-width: 250px;
  padding: 5px;
  text-align: center;
  top: -6px;
  transform: translateX(-50%) translateY(-100%);
  width: auto;
  z-index: 99;
}
.word-container [tooltip-def]:hover:after,
.word-container [tooltip-def]:hover:before {
  display: inline-block;
}

The tooltip is cut off on the left side. I tried overflow: visible and higher z-index on .word-container [tooltip-def]:after, but none of the working.

Here is the jsfiddle demo: https://jsfiddle.net/mddc/5dtwr6zc/10/

How can I make minimal CSS changes to make the tooltip visible? Move to the right side when the left side touches the browser edge?

Body:
I've made the changes which can be viewed in the fiddle below

https://jsfiddle.net/5dtwr6zc/14/

.test{
 overflow: visible;
}
.container {
  margin-top: 100px;
}
.word-container [tooltip-def] {
  display: inline-block;
  position: relative;
}
.word-container [tooltip-def]:before {
  left: 50%;
  position: absolute;
  transform: translateX(-50%);
  border-color: #323232 transparent transparent transparent;
  border-style: solid;
  border-width: 4px 6px 0 6px;
  content: "";
  display: none;
  top: -6px;
  z-index: 99;
}
.word-container [tooltip-def]:after {
  left: 150%;
  position: absolute;
  transform: translateX(-47%);
  content: attr(tooltip-def);
  background: #323232;
  border-radius: 5px;
  color: #fff;
  display: none;
  font-family: open sans;
  font-size: 12px;
  height: auto;
  min-width: 250px;
  padding: 5px;
  text-align: center;
  top: -6px;
  transform: translateX(-50%) translateY(-100%);
  width: auto;
  z-index: 99;
}
.word-container [tooltip-def]:hover:after,
.word-container [tooltip-def]:hover:before {
  display: inline-block;
}

The problem was the positioning of the after psuedo element. But I would strongly suggest to make the positioning dynamic as per the context using JavaScript


来源: stackexchange

问:
Chat bot-Can I display html content using node.js in Microsoft bot framework & bot builder
I'm developing a chatbot on azure using node.js. It's a data visualization bot which generates chart in html format using d3 library and display to user.
It seems that Microsoft bot builder doesn't support html format. But I have looked through this link:
https://blog.botframework.com/2017/09/07/html-not-supported-web-chat/
It says that there is a way to enable html content:
"If HTML rendering in Web Chat is a critical feature for your applications, you can clone or fork a copy of the Web Chat source code from GitHub, and enable it (on your own custom Web Chat client)."
I tried to clone the file and changed  ‘html : false’ to ‘html : true’. But it's not working.

Can anyone tell me what I can do? Really appreciate it!!!

答:
Depending on what data you are attempting to visualize, you might be able to use a service like Google Image Charts: https://developers.google.com/chart/image/docs/chart_playground

Using this service, with the following code:

```<code>// attach the card to the reply message
var msg = new builder.Message(session).addAttachment(createHeroCard(session));
session.send(msg);

function createHeroCard(session) {
            return new builder.HeroCard(session)
                .title('Months with Numbers Bar Chart')
                .subtitle('Using a Chart as Image service...')
                .text('Build and connect intelligent bots that have charts rendered as images.')
                .images([
                    builder.CardImage.create(session, 'http://chart.googleapis.com/chart?cht=bvg&chs=250x150&chd=s:Monkeys&chxt=x,y&chxl=0:|Jan|Feb|Mar|Apr|May|Jun|Jul')
                ])
                .buttons([
                    builder.CardAction.openUrl(session, 'https://learn.microsoft.com/bot-framework/', 'Get Started')
                ]);
        }
</code>```

Produces this hero card:

ContentLicense: CC BY-SA 3.0

Body:
Depending on what data you are attempting to visualize, you might be able to use a service like Google Image Charts: https://developers.google.com/chart/image/docs/chart_playground

Using this service, with the following code:

// attach the card to the reply message
var msg = new builder.Message(session).addAttachment(createHeroCard(session));
session.send(msg);

function createHeroCard(session) {
            return new builder.HeroCard(session)
                .title('Months with Numbers Bar Chart')
                .subtitle('Using a Chart as Image service...')
                .text('Build and connect intelligent bots that have charts rendered as images.')
                .images([
                    builder.CardImage.create(session, 'http://chart.googleapis.com/chart?cht=bvg&chs=250x150&chd=s:Monkeys&chxt=x,y&chxl=0:|Jan|Feb|Mar|Apr|May|Jun|Jul')
                ])
                .buttons([
                    builder.CardAction.openUrl(session, 'https://learn.microsoft.com/bot-framework/', 'Get Started')
                ]);
        }

Produces this hero card:


问:
Bubbling events in WPF? Simple Question
This is probably a really easy fix, but I am inexperienced in working with events so I am just going to ask it.

I have a ListBox with ListBoxItems in it. These ListBoxItems will be binded to a data source so they will change. I need a MouseDown event to be raised when a MouseDown action is performed on any of these ListBoxItem (because I am doing drag and drop). Since the values are changing, I cannot expect to wire the events together in the XAML like the following

```<code><ListBox Name="ListBox1">
    <ListBoxItem MouseDown="MouseDownEventName">Item A</ListBoxItem>
    <ListBoxItem MouseDown="MouseDownEventName">Item B</ListBoxItem>
    <ListBoxItem MouseDown="MouseDownEventName">Item C</ListBoxItem>
</ListBox>
</code>```

This would be easy if I had static values, but since the values in the ListBox will change, I would prefer to write the following XAML

```<code> <ListBox Name="ListBox1" MouseDown="MouseDownEventName">
     //Binded Values
</ListBox>
</code>```

Then, when the ListBoxItem is selected, it would Bubble the event up to this MouseDownEventName, and I can grab ListBox1.SelectedItem at that time, the problem is, I am trying this right now, but it is not working. I have the following Code to handle the MouseDown, which is only rewriting label content at the moment to signify that the item has been MouseDown'ed.

```<code>    public partial class UserControl1 : UserControl
    {
    public UserControl1()
    {
        InitializeComponent();
    }

    private void ListBox_MouseDown(object sender, RoutedEventArgs e)
    {
        ListBox box = (ListBox)sender;
        if (box != null && box.SelectedItem != null)
        {

            DragDrop.DoDragDrop(box, ItemListBox.SelectedItem, DragDropEffects.Move);
            label1.Content = "MouseDown Event Fired";
        }
    }
}
</code>```

答:
Using XAML, you can provide a template for different types contained within the form. For example, in this case, you can specify that ListBoxItem's fire off a certain event handler. This is the bulk of the XAML markup code (details found here: How to catch Click on ListboxItem when the item is templated?)

```<code><ListBox>
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <EventSetter Event="PreviewMouseLeftButtonDown" Handler="ListBoxItem_PreviewMouseLeftButtonDown"/>
        </Style>
    </ListBox.ItemContainerStyle>
...
</ListBox>
</code>```

Another thing to check before is to try and change your DragDrop.DoDragDrop() method call to something else to see if the issue has to do with that method. Since the Label's content is changing, I would imagine it has something to do with that method.

ContentLicense: CC BY-SA 2.5

Title: Bubbling events in WPF? Simple Question

Body:
This is probably a really easy fix, but I am inexperienced in working with events so I am just going to ask it.

I have a ListBox with ListBoxItems in it. These ListBoxItems will be binded to a data source so they will change. I need a MouseDown event to be raised when a MouseDown action is performed on any of these ListBoxItem (because I am doing drag and drop). Since the values are changing, I cannot expect to wire the events together in the XAML like the following

<ListBox Name="ListBox1">
    <ListBoxItem MouseDown="MouseDownEventName">Item A</ListBoxItem>
    <ListBoxItem MouseDown="MouseDownEventName">Item B</ListBoxItem>
    <ListBoxItem MouseDown="MouseDownEventName">Item C</ListBoxItem>
</ListBox>

This would be easy if I had static values, but since the values in the ListBox will change, I would prefer to write the following XAML

 <ListBox Name="ListBox1" MouseDown="MouseDownEventName">
     //Binded Values
</ListBox>

Then, when the ListBoxItem is selected, it would Bubble the event up to this MouseDownEventName, and I can grab ListBox1.SelectedItem at that time, the problem is, I am trying this right now, but it is not working. I have the following Code to handle the MouseDown, which is only rewriting label content at the moment to signify that the item has been MouseDown'ed.

    public partial class UserControl1 : UserControl
    {
    public UserControl1()
    {
        InitializeComponent();
    }

    private void ListBox_MouseDown(object sender, RoutedEventArgs e)
    {
        ListBox box = (ListBox)sender;
        if (box != null && box.SelectedItem != null)
        {

            DragDrop.DoDragDrop(box, ItemListBox.SelectedItem, DragDropEffects.Move);
            label1.Content = "MouseDown Event Fired";
        }
    }
}

Body:
Using XAML, you can provide a template for different types contained within the form. For example, in this case, you can specify that ListBoxItem's fire off a certain event handler. This is the bulk of the XAML markup code (details found here: How to catch Click on ListboxItem when the item is templated?)

<ListBox>
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <EventSetter Event="PreviewMouseLeftButtonDown" Handler="ListBoxItem_PreviewMouseLeftButtonDown"/>
        </Style>
    </ListBox.ItemContainerStyle>
...
</ListBox>

Another thing to check before is to try and change your DragDrop.DoDragDrop() method call to something else to see if the issue has to do with that method. Since the Label's content is changing, I would imagine it has something to do with that method.


问:
How can I determine if a codec / container combination is compatible with FFmpeg?
I'm looking at re-muxing some containers holding audio and video such that I extract the best, first audio stream, and store it in a new container where e.g. only the audio stream is present.

The output context for FFmpeg is created like so:

```<code>AVFormatContext* output_context = NULL;
avformat_alloc_output_context2( &output_context, NULL, "mp4", NULL );
</code>```

I have a shortlist of acceptable outputs, e.g. MP4, M4A, etc … essentially those that are readable by Apple's Audio File Services:

```<code>kAudioFileAIFFType              = 'AIFF',
kAudioFileAIFCType              = 'AIFC',
kAudioFileWAVEType              = 'WAVE',
kAudioFileSoundDesigner2Type    = 'Sd2f',
kAudioFileNextType              = 'NeXT',
kAudioFileMP3Type               = 'MPG3',   // mpeg layer 3
kAudioFileMP2Type               = 'MPG2',   // mpeg layer 2
kAudioFileMP1Type               = 'MPG1',   // mpeg layer 1
kAudioFileAC3Type               = 'ac-3',
kAudioFileAAC_ADTSType          = 'adts',
kAudioFileMPEG4Type             = 'mp4f',
kAudioFileM4AType               = 'm4af',
kAudioFileM4BType               = 'm4bf',
kAudioFileCAFType               = 'caff',
kAudioFile3GPType               = '3gpp',
kAudioFile3GP2Type              = '3gp2',
kAudioFileAMRType               = 'amrf'
</code>```

My question is this : is there an easy API in FFmpeg that can be leveraged to choose a compatible output container given the codec the audio stream is in?

答: For each individual muxer, there is usually a codec tag writing function.That function will check against a list in another source file or work through a switch statement in the same. There is no central roster or container-matching utility function. Your best bet is to identify the codec id in libavcodec/allcodecs.c and then grep in libavformat/ for that ID, particularly within files suffixed with enc e.g. matroskaenc.c.

Body:
I'm looking at re-muxing some containers holding audio and video such that I extract the best, first audio stream, and store it in a new container where e.g. only the audio stream is present.

The output context for FFmpeg is created like so:

AVFormatContext* output_context = NULL;
avformat_alloc_output_context2( &output_context, NULL, "mp4", NULL );

I have a shortlist of acceptable outputs, e.g. MP4, M4A, etc … essentially those that are readable by Apple's Audio File Services:

kAudioFileAIFFType              = 'AIFF',
kAudioFileAIFCType              = 'AIFC',
kAudioFileWAVEType              = 'WAVE',
kAudioFileSoundDesigner2Type    = 'Sd2f',
kAudioFileNextType              = 'NeXT',
kAudioFileMP3Type               = 'MPG3',   // mpeg layer 3
kAudioFileMP2Type               = 'MPG2',   // mpeg layer 2
kAudioFileMP1Type               = 'MPG1',   // mpeg layer 1
kAudioFileAC3Type               = 'ac-3',
kAudioFileAAC_ADTSType          = 'adts',
kAudioFileMPEG4Type             = 'mp4f',
kAudioFileM4AType               = 'm4af',
kAudioFileM4BType               = 'm4bf',
kAudioFileCAFType               = 'caff',
kAudioFile3GPType               = '3gpp',
kAudioFile3GP2Type              = '3gp2',
kAudioFileAMRType               = 'amrf'

My question is this : is there an easy API in FFmpeg that can be leveraged to choose a compatible output container given the codec the audio stream is in?


问:
How can I get android View kind programmatically?
I want to get View object programmatically.
But, not fixed View kind, like.. RadioButton..Button..
I only want to know View kind for View's properties.
Is it possible?

Please see this :

```<code>String idString = "view_from_xml_id";
int id = getResources().getIdentifier(idString, "id", getPackageName());
View iDontKnowWhat = findViewById(id);
</code>```

The [iDontKnowWhat] view object is Just View.
But, I want to cast this [iDontKnowWhat] view object to RadioButton, Button, EditText...Case by Case.

I want like this :

```<code>String idString = "view_from_xml_id";
int id = getResources().getIdentifier(idString, "id", getPackageName());
View iDontKnowWhat = findViewById(id);

if(iDontKnowWhat == RadioButton)
  // @Do something..
else if(iDontKnowWhat == EditText)
  // @Do Something..
</code>```

Can I implement it?
Please help me sir :)

答:
Do not use == (equals), that actually compares the values, not the objects. Use instanceof and check the view like this

if(view instanceof TextView){
      //TODO your logic
}elseif(....

Body:
I want to get View object programmatically.
But, not fixed View kind, like.. RadioButton..Button..
I only want to know View kind for View's properties.
Is it possible?

Please see this :

String idString = "view_from_xml_id";
int id = getResources().getIdentifier(idString, "id", getPackageName());
View iDontKnowWhat = findViewById(id);

The [iDontKnowWhat] view object is Just View.
But, I want to cast this [iDontKnowWhat] view object to RadioButton, Button, EditText...Case by Case.

I want like this :

String idString = "view_from_xml_id";
int id = getResources().getIdentifier(idString, "id", getPackageName());
View iDontKnowWhat = findViewById(id);

if(iDontKnowWhat == RadioButton)
  // @Do something..
else if(iDontKnowWhat == EditText)
  // @Do Something..

Can I implement it?
Please help me sir :)


问:
node --experimental-modules, requested module does not provide an export named
I've installed Node 8.9.1 (same problem happens in v10.5.0).

I'm trying to use named imports from npm packages in a file with the .mjs

```<code>import { throttle } from lodash;
</code>```

I run:

```<code>node --experimental-modules index.mjs
</code>```

and I get:

SyntaxError: The requested module 'lodash' does not provide an export named 'throttle'
      at ModuleJob._instantiate (internal/modules/esm/module_job.js:80:21)

--experimental-modules are supposed to stop being experimental in v10 LTS, so why haven't more module authors jumped on the bandwagon?

答:
You have to use .mjs extension.

Once this has been set, files ending with .mjs will be able to be loaded as ES Modules.

reference: https://nodejs.org/api/esm.html

Update:

Looks like you haven't export the method yet.

Suppose i have hello.mjs with content

```<code>export function sayHello() {
    console.log('hello')
}
</code>```

i can use it in index.mjs like this

```<code>import {sayHello} from './hello.mjs'
sayHello()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I've installed Node 8.9.1 (same problem happens in v10.5.0).

I'm trying to use named imports from npm packages in a file with the .mjs

import { throttle } from lodash;

I run:

node --experimental-modules index.mjs

and I get:

SyntaxError: The requested module 'lodash' does not provide an export named 'throttle'
      at ModuleJob._instantiate (internal/modules/esm/module_job.js:80:21)

--experimental-modules are supposed to stop being experimental in v10 LTS, so why haven't more module authors jumped on the bandwagon?

Body:
You have to use .mjs extension.

Once this has been set, files ending with .mjs will be able to be loaded as ES Modules.

reference: https://nodejs.org/api/esm.html

Update:

Looks like you haven't export the method yet.

Suppose i have hello.mjs with content

export function sayHello() {
    console.log('hello')
}

i can use it in index.mjs like this

import {sayHello} from './hello.mjs'
sayHello()


问:
Is there an analogue of this function in Python standard modules?
I'm looking for a standard function (operator, decorator) that would be equivalent to the following hand-written function:

```<code>def defaulted(func, defaultVal):
   try:
      result = func()
   except:
      result = defaultVal

   return result
</code>```

Thanks!

答:
There's nothing like that in the stdlib (to the best of my knowledge). For one thing, it's bad practice: you should never use a bare except. (Instead, specify the exceptions you want to catch; that way, you won't catch everything!)

Here's a decorator:

```<code>>>> def defaultval(error, value):
...     def decorator(func):
...             def defaulted(*args, **kwargs):
...                     try:
...                             return func(*args, **kwargs)
...                     except error:
...                             return value
...             return defaulted
...     return decorator
...
>>> @defaultval(NameError, "undefined")
... def get_var():
...     return name
...
>>> get_var()
'undefined'
</code>```

Body:
I'm looking for a standard function (operator, decorator) that would be equivalent to the following hand-written function:

def defaulted(func, defaultVal):
   try:
      result = func()
   except:
      result = defaultVal

   return result

Thanks!

Body:
There's nothing like that in the stdlib (to the best of my knowledge). For one thing, it's bad practice: you should never use a bare except. (Instead, specify the exceptions you want to catch; that way, you won't catch everything!)

Here's a decorator:

>>> def defaultval(error, value):
...     def decorator(func):
...             def defaulted(*args, **kwargs):
...                     try:
...                             return func(*args, **kwargs)
...                     except error:
...                             return value
...             return defaulted
...     return decorator
...
>>> @defaultval(NameError, "undefined")
... def get_var():
...     return name
...
>>> get_var()
'undefined'


问:
Specify which DNS servers to use to resolve hostnames in .NET
I'd like to know if there's any way to force the System.Net.Dns class to resolve hostnames using a set of custom DNS servers instead of using the ones that are associated with the main network connection.

I suspect that this is only possible using a custom library like DnDns (http://dndns.codeplex.com), but I was hoping this could be done from within .NET.

答:
Tested in .net standard:</p>

```<code>    public static async Task<IPHostEntry> GetHostEntryAsync(string host, string dns = null)
    {
        if (string.IsNullOrEmpty(host))
        {
            return null;
        }

        //Check if any cached result exists
        Tuple<string, string> key = new Tuple<string, string>(host, dns);
        if (NetHelper._dnsCache.TryGetValue(key, out Tuple<IPHostEntry, DateTime> record) && record.Item2 > DateTime.Now)
        {
            return record.Item1;
        }

        //Check dns server's address or port
        IPHostEntry result = null;
        int dnsPort;
        if (dns != null)
        {
            string[] blocks = dns.Split(':');
            if (blocks.Length == 2 && int.TryParse(blocks[1], out dnsPort))//dns is ip v4
            {
                dns = blocks[0];
            }
            else if (blocks.Length == 9 && int.TryParse(blocks[8], out dnsPort))//dns is ip v6
            {
                blocks[0] = blocks[0].TrimStart('[');
                blocks[7] = blocks[7].TrimStart(']');
                dns = string.Format("{0}:{1}:{2}:{3}:{4}:{5}:{6}:{7}", blocks);
            }
            else
            {
                dnsPort = 53;
            }
        }
        else
        {
            dnsPort = 53;
        }

        //Check if host is ip address
        if (host[0] == '[' && host[host.Length - 1] == ']')//IPV6 address
        {
            host = host.Substring(1, host.Length - 2);
        }
        if (IPAddress.TryParse(host, out IPAddress address))
        {
            result = new IPHostEntry { AddressList = new IPAddress[] { address } };
        }
        else if (string.IsNullOrEmpty(dns))
        {
            result = await Dns.GetHostEntryAsync(host);
        }
        else
        {
            #region Resolve with customized dns server
            IPAddress dnsAddr;
            if (!IPAddress.TryParse(dns, out dnsAddr))
            {
                throw new ArgumentException("The dns host must be ip address.", nameof(dns));
            }
            using (MemoryStream ms = new MemoryStream())
            {
                Random rnd = new Random();
                //About the dns message:http://www.ietf.org/rfc/rfc1035.txt

                //Write message header.
                ms.Write(new byte[] {
                    (byte)rnd.Next(0, 0xFF),(byte)rnd.Next(0, 0xFF),
                    0x01,
                    0x00,
                    0x00,0x01,
                    0x00,0x00,
                    0x00,0x00,
                    0x00,0x00
                }, 0, 12);

                //Write the host to query.
                foreach (string block in host.Split('.'))
                {
                    byte[] data = Encoding.UTF8.GetBytes(block);
                    ms.WriteByte((byte)data.Length);
                    ms.Write(data, 0, data.Length);
                }
                ms.WriteByte(0);//The end of query, muest 0(null string)

                //Query type:A
                ms.WriteByte(0x00);
                ms.WriteByte(0x01);

                //Query class:IN
                ms.WriteByte(0x00);
                ms.WriteByte(0x01);

                Socket socket = new Socket(SocketType.Dgram, ProtocolType.Udp);
                try
                {
                    //send to dns server
                    byte[] buffer = ms.ToArray();
                    while (socket.SendTo(buffer, 0, buffer.Length, SocketFlags.None, new IPEndPoint(dnsAddr, dnsPort)) < buffer.Length) ;
                    buffer = new byte[0x100];
                    EndPoint ep = socket.LocalEndPoint;
                    int num = socket.ReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref ep);

                    //The response message has the same header and question structure, so we move index to the answer part directly.
                    int index = (int)ms.Length;
                    //Parse response records.
                    void SkipName()
                    {
                        while (index < num)
                        {
                            int length = buffer[index++];
                            if (length == 0)
                            {
                                return;
                            }
                            else if (length > 191)
                            {
                                return;
                            }
                            index += length;
                        }
                    }

                    List<IPAddress> addresses = new List<IPAddress>();
                    while (index < num)
                    {
                        SkipName();//Seems the name of record is useless in this scense, so we just needs to get the next index after name.
                        byte type = buffer[index += 2];
                        index += 7;//Skip class and ttl

                        int length = buffer[index++] << 8 | buffer[index++];//Get record data's length

                        if (type == 0x01)//A record
                        {
                            if (length == 4)//Parse record data to ip v4, this is what we need.
                            {
                                addresses.Add(new IPAddress(new byte[] { buffer[index], buffer[index + 1], buffer[index + 2], buffer[index + 3] }));
                            }
                        }
                        index += length;
                    }
                    result = new IPHostEntry { AddressList = addresses.ToArray() };
                }
                finally
                {
                    socket.Dispose();
                }
            }
            #endregion
        }

        //Cache and return result
        NetHelper._dnsCache[key] = new Tuple<IPHostEntry, DateTime>(result, DateTime.Now.AddMinutes(15));

        #pragma warning disable CS4014
        Task.Run(async () =>
        {
            await Task.Delay((int)TimeSpan.FromMinutes(15).TotalMilliseconds);
            NetHelper._dnsCache.Remove(key);
        });
        #pragma warning restore CS4014
        return result;

    }
</code>```

Body:
Tested in .net standard:

    public static async Task<IPHostEntry> GetHostEntryAsync(string host, string dns = null)
    {
        if (string.IsNullOrEmpty(host))
        {
            return null;
        }

        //Check if any cached result exists
        Tuple<string, string> key = new Tuple<string, string>(host, dns);
        if (NetHelper._dnsCache.TryGetValue(key, out Tuple<IPHostEntry, DateTime> record) && record.Item2 > DateTime.Now)
        {
            return record.Item1;
        }

        //Check dns server's address or port
        IPHostEntry result = null;
        int dnsPort;
        if (dns != null)
        {
            string[] blocks = dns.Split(':');
            if (blocks.Length == 2 && int.TryParse(blocks[1], out dnsPort))//dns is ip v4
            {
                dns = blocks[0];
            }
            else if (blocks.Length == 9 && int.TryParse(blocks[8], out dnsPort))//dns is ip v6
            {
                blocks[0] = blocks[0].TrimStart('[');
                blocks[7] = blocks[7].TrimStart(']');
                dns = string.Format("{0}:{1}:{2}:{3}:{4}:{5}:{6}:{7}", blocks);
            }
            else
            {
                dnsPort = 53;
            }
        }
        else
        {
            dnsPort = 53;
        }

        //Check if host is ip address
        if (host[0] == '[' && host[host.Length - 1] == ']')//IPV6 address
        {
            host = host.Substring(1, host.Length - 2);
        }
        if (IPAddress.TryParse(host, out IPAddress address))
        {
            result = new IPHostEntry { AddressList = new IPAddress[] { address } };
        }
        else if (string.IsNullOrEmpty(dns))
        {
            result = await Dns.GetHostEntryAsync(host);
        }
        else
        {
            #region Resolve with customized dns server
            IPAddress dnsAddr;
            if (!IPAddress.TryParse(dns, out dnsAddr))
            {
                throw new ArgumentException("The dns host must be ip address.", nameof(dns));
            }
            using (MemoryStream ms = new MemoryStream())
            {
                Random rnd = new Random();
                //About the dns message:http://www.ietf.org/rfc/rfc1035.txt

                //Write message header.
                ms.Write(new byte[] {
                    (byte)rnd.Next(0, 0xFF),(byte)rnd.Next(0, 0xFF),
                    0x01,
                    0x00,
                    0x00,0x01,
                    0x00,0x00,
                    0x00,0x00,
                    0x00,0x00
                }, 0, 12);

                //Write the host to query.
                foreach (string block in host.Split('.'))
                {
                    byte[] data = Encoding.UTF8.GetBytes(block);
                    ms.WriteByte((byte)data.Length);
                    ms.Write(data, 0, data.Length);
                }
                ms.WriteByte(0);//The end of query, muest 0(null string)

                //Query type:A
                ms.WriteByte(0x00);
                ms.WriteByte(0x01);

                //Query class:IN
                ms.WriteByte(0x00);
                ms.WriteByte(0x01);

                Socket socket = new Socket(SocketType.Dgram, ProtocolType.Udp);
                try
                {
                    //send to dns server
                    byte[] buffer = ms.ToArray();
                    while (socket.SendTo(buffer, 0, buffer.Length, SocketFlags.None, new IPEndPoint(dnsAddr, dnsPort)) < buffer.Length) ;
                    buffer = new byte[0x100];
                    EndPoint ep = socket.LocalEndPoint;
                    int num = socket.ReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref ep);

                    //The response message has the same header and question structure, so we move index to the answer part directly.
                    int index = (int)ms.Length;
                    //Parse response records.
                    void SkipName()
                    {
                        while (index < num)
                        {
                            int length = buffer[index++];
                            if (length == 0)
                            {
                                return;
                            }
                            else if (length > 191)
                            {
                                return;
                            }
                            index += length;
                        }
                    }

                    List<IPAddress> addresses = new List<IPAddress>();
                    while (index < num)
                    {
                        SkipName();//Seems the name of record is useless in this scense, so we just needs to get the next index after name.
                        byte type = buffer[index += 2];
                        index += 7;//Skip class and ttl

                        int length = buffer[index++] << 8 | buffer[index++];//Get record data's length

                        if (type == 0x01)//A record
                        {
                            if (length == 4)//Parse record data to ip v4, this is what we need.
                            {
                                addresses.Add(new IPAddress(new byte[] { buffer[index], buffer[index + 1], buffer[index + 2], buffer[index + 3] }));
                            }
                        }
                        index += length;
                    }
                    result = new IPHostEntry { AddressList = addresses.ToArray() };
                }
                finally
                {
                    socket.Dispose();
                }
            }
            #endregion
        }

        //Cache and return result
        NetHelper._dnsCache[key] = new Tuple<IPHostEntry, DateTime>(result, DateTime.Now.AddMinutes(15));

        #pragma warning disable CS4014
        Task.Run(async () =>
        {
            await Task.Delay((int)TimeSpan.FromMinutes(15).TotalMilliseconds);
            NetHelper._dnsCache.Remove(key);
        });
        #pragma warning restore CS4014
        return result;

    }


问:
How to return a single FirebaseObjectObservable from a FirebaseListObservable query
I'm building a game using Angular 4 and Firebase Realtime DB.  I have a Firebase DB layout like this:

```<code>FB -> player_list-> -KyagqWEM-cqUoppGe_x
                        id:33061
                        name:Joe
                   -KyadrWSD-aqUeedBv_w
                        id:22037
                        name:Cara
</code>```

In my app I'd like to create a FirebaseObjectObservable on a specific player, Joe in this example.  In my Ng Database Service I've created a method that looks like this:

```<code>getPlayerFromId(playerId: number): FirebaseListObservable<Player[]> {
  this.player = this.database.list(this.playerBasePath, {
    query: {
      orderByChild: 'id',
      equalTo: playerId,
      limitToFirst: 1
    }
  })
  return this.player;
}
</code>```

A query seems to be the best way to find a specific node in my Firebase database, unfortunately queries seem to only return a list, even if that list is only one item in length.  In my component It's fairly easy to get the one player object, with code like this:

```<code>  getPlayer(playerId: number){
    this.studentService.getPlayerFromId(playerId)
    .subscribe(data => {
      this.player = data[0];
    })
  }
</code>```

Is there a more elegant way to return one FirebaseObjectObservable from a list query?  I've tried map and filter, but apparently those are not supported by FirebaseListObservable.

答:
Because the returned result is a list you need to loop through to get the object

```<code>getPlayer(playerId: number){
this.studentService.getPlayerFromId(playerId)
.subscribe(data => {
  data.forEach(player => {
    this.player = player;
  })

 })
}
</code>```

Check this answer

Body:
I'm building a game using Angular 4 and Firebase Realtime DB.  I have a Firebase DB layout like this:

FB -> player_list-> -KyagqWEM-cqUoppGe_x
                        id:33061
                        name:Joe
                   -KyadrWSD-aqUeedBv_w
                        id:22037
                        name:Cara

In my app I'd like to create a FirebaseObjectObservable on a specific player, Joe in this example.  In my Ng Database Service I've created a method that looks like this:

getPlayerFromId(playerId: number): FirebaseListObservable<Player[]> {
  this.player = this.database.list(this.playerBasePath, {
    query: {
      orderByChild: 'id',
      equalTo: playerId,
      limitToFirst: 1
    }
  })
  return this.player;
}

A query seems to be the best way to find a specific node in my Firebase database, unfortunately queries seem to only return a list, even if that list is only one item in length.  In my component It's fairly easy to get the one player object, with code like this:

  getPlayer(playerId: number){
    this.studentService.getPlayerFromId(playerId)
    .subscribe(data => {
      this.player = data[0];
    })
  }

Is there a more elegant way to return one FirebaseObjectObservable from a list query?  I've tried map and filter, but apparently those are not supported by FirebaseListObservable.

Body:
Because the returned result is a list you need to loop through to get the object

getPlayer(playerId: number){
this.studentService.getPlayerFromId(playerId)
.subscribe(data => {
  data.forEach(player => {
    this.player = player;
  })

 })
}

Check this answer


问:
Javascript setter function with prototyping
I am learning Javascript. When I try to use setters with prototyping I am getting an error

TypeError: cir1.radiusToCircle is not a function

```<code>var Circle = function(radius){
    this._radius = radius;
}

//prototype

Circle.prototype ={
    set radiusToCircle(rad) { this._radius = rad; },
    get radiusFromCircle() { return this._radius;},

    get area() { return (Math.PI * (this._radius * this._radius));}
};

var cir1 = new Circle(5);

cir1.radiusToCircle(14);
</code>```

What am I missing here?

Thanks in advance.

答:
To use a setter you need to set the property directly, not pass it through like a function argument. Setter MDN Docs</p>

```<code>cir1.radiusToCircle = 14;
</code>```

Body:
I am learning Javascript. When I try to use setters with prototyping I am getting an error

TypeError: cir1.radiusToCircle is not a function

var Circle = function(radius){
    this._radius = radius;
}

//prototype

Circle.prototype ={
    set radiusToCircle(rad) { this._radius = rad; },
    get radiusFromCircle() { return this._radius;},

    get area() { return (Math.PI * (this._radius * this._radius));}
};

var cir1 = new Circle(5);

cir1.radiusToCircle(14);

What am I missing here?

Thanks in advance.

Body:
To use a setter you need to set the property directly, not pass it through like a function argument. Setter MDN Docs

cir1.radiusToCircle = 14;


答:
It sounds like you want to use the match() function, for example:

```<code>target<-c(the values of your target order)
df<-df[match(target, df$column_to_reorder),]
</code>```

Title: How can I organise and move row of data based on label matches?

Body:
I have raw data shown below. I'm trying to move a row of data that corresponds to a label it matches to a new location in the dataframe.

dat<-read.table(text='RowLabels col1    col2    col3    col4    col5    col6
L   24363.7 25944.9 25646.1 25335.4 23564.2 25411.5
             610    411.4   439 437.3   436.9   420.7   516.9
             1  86.4    113.9   103.5   113.5   80.3    129
             2  102.1   99.5    96.3    100.4   99.5    86
             3  109.7   102.2   100.2   112.9   92.3    123.8
             4  88.9    87.1    103.6   102.5   93.6    134.1
             5  -50.3   -40.2   -72.3   -61.4   -27 -22.7
             6  -35.3   -9.3    25.3    -0.3    15.6    -27.3
             7  109.9   85.8    80.7    69.3    66.4    94
             181920 652.9   729.2   652.1   689.1   612.5   738.4
             1  104.3   107.3   103.5   104.2   98.3    110.1
             2  103.6   102.6   100.1   103.2   88.8    117.7
             3  53.5    99.1    46.7    70.3    53.9    32.5
             4  93.5    107.2   98.3    99.3    97.3    121.1
             5  96.8    109.3   104 102.2   98.7    112.9
             6  103.6   96.9    104.7   104.4   91.5    137.7
             7  97.6    106.8   94.8    105.5   84  106.4
             181930 732.1   709.6   725.8   729.5   554.5   873.1
             1  118.4   98.8    102.3   102 101.9   115.8
             2  96.7    103.3   104.6   105.2   81.9    128.7
             3  96  98.2    99.4    97.9    69.8    120.6
             4  100.7   101 103.6   106.6   59.6    136.2
             5  106.1   103.4   104.7   104.8   76.1    131.8
             6  105 102.1   103 108.3   81  124.7
             7  109.2   102.8   108.2   104.7   84.2    115.3
             N  3836.4  4395.8  4227.3  4567.4  4009.9  4434.6
             610    88.1    96.3    99.6    92  90  137.6
             1  88.1    96.3    99.6    92  90  137.6
             181920 113.1   100.6   106.5   104.2   87.3    108.2
             1  113.1   100.6   106.5   104.2   87.3    108.2
             181930 111.3   99.1    104.5   115.5   103.6   118.8
             1  111.3   99.1    104.5   115.5   103.6   118.8
             ',header=TRUE)

I want to match the values of the three N-prefix labels: 610, 181920 and 181930 with its corresponding L-prefix labels. Basically move that row of data into the L-prefix as a new row, labeled 0 or 8 for example. So, the result for label, 610 would look like:

RowLabels col1    col2    col3    col4    col5    col6
610    411.4   439 437.3   436.9   420.7   516.9
         1  86.4    113.9   103.5   113.5   80.3    129
         2  102.1   99.5    96.3    100.4   99.5    86
         3  109.7   102.2   100.2   112.9   92.3    123.8
         4  88.9    87.1    103.6   102.5   93.6    134.1
         5  -50.3   -40.2   -72.3   -61.4   -27 -22.7
         6  -35.3   -9.3    25.3    -0.3    15.6    -27.3
         7  109.9   85.8    80.7    69.3    66.4    94
         8  88.1    96.3    99.6    92  90  137.6

Is this possible? I tried searching and I found some resources pointing toward dplyr or tidyr  or aggregate. But I can't find a good example that matches my case. How to combine rows based on unique values in R? and
Aggregate rows by shared values in a variable

Body:
It sounds like you want to use the match() function, for example:

target<-c(the values of your target order)
df<-df[match(target, df$column_to_reorder),]


问:
Dagger2- Retrofit is not injecting in ApiHelperImpl
Hi I am trying to inject retrofit in ApiHelperImpl.kt class. I have below module and component.

AppComponent.kt

```<code>@Component(modules = arrayOf(AndroidInjectionModule::class, AppModule::class, ActivityBuilder::class))
@Singleton
interface AppComponent {
    fun inject(app: PartnerApplication)
}
</code>```

AppModule.kt

```<code>@Module
class AppModule {

    @Provides
    @Singleton
    fun providesPartnerApplication(application: Application): Application = application

    @Provides
    @Singleton
    fun providesSharedPreferences(application: Application): SharedPreferences {
        return PreferenceManager.getDefaultSharedPreferences(application)
    }

    @Provides
    @Singleton
    fun provideOkHttpCache(application: Application): Cache {
        val cacheSize = 10 * 1024 * 1024L // 10 MiB
        return Cache(application.cacheDir, cacheSize)
    }

    @Provides
    @Singleton
    fun provideMoshi(): Moshi = Moshi.Builder().build()

    @Provides
    @Singleton
    fun provideOkHttpClient(cache: Cache): OkHttpClient {
        val okHttpClient = OkHttpClient()
        okHttpClient.newBuilder()
                .cache(cache)
                .build()
        return okHttpClient
    }

    @Provides
    @Singleton
    fun provideRetrofit(moshi: Moshi, okHttpClient: OkHttpClient): Retrofit {
        return Retrofit.Builder()
                .addConverterFactory(MoshiConverterFactory.create(moshi))
                .baseUrl(BuildConfig.BASE_URL)
                .client(okHttpClient)
                .build()
    }

}
</code>```

PartnerApplication.kt

```<code>class PartnerApplication : Application(), AnkoLogger, HasActivityInjector {

    @Inject lateinit var activityInjector: DispatchingAndroidInjector<Activity>

    override fun activityInjector(): AndroidInjector<Activity> {
        return activityInjector
    }

    override fun onCreate() {
        super.onCreate()
        DaggerAppComponent.create().inject(this)
    }

    override protected fun attachBaseContext(base: Context) {
        super.attachBaseContext(base)
        MultiDex.install(this)
    }

}
</code>```

ApiHelper.kt

```<code>interface ApiHelper {
    fun doServerLoginApiCall(email: String, password: String): Observable<LoginResponse>
    fun doServerRegistrationApiCall(): Observable<RegistrationResponse>
}
</code>```

ApiHelperImpl.kt

```<code>class ApiHelperImpl : ApiHelper {

    @Inject
    lateinit var retrofit: Retrofit

    override fun doServerLoginApiCall(email: String, password: String): Observable<LoginResponse> {
        return retrofit.create(RestApi::class.java).login(email, password)
    }

    override fun doServerRegistrationApiCall(): Observable<RegistrationResponse> {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }
}
</code>```

LoginActivity.kt

```<code>class LoginActivity : BaseActivity() {

    @Inject
    lateinit var loginViewModel: LoginViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        performDependencyInjection()
        super.onCreate(savedInstanceState)
        val activityLoginBinding: ActivityLoginBinding = DataBindingUtil.setContentView<ActivityLoginBinding>(this, R.layout.activity_login)
        activityLoginBinding.loginViewModel = loginViewModel
    }
}
</code>```

LoginViewModel.kt

```<code>class LoginViewModel : ViewModel(), AnkoLogger {

    val emailField = ObservableField<String>()

    private val email: String
        get() = emailField.get()

    val passwordField = ObservableField<String>()

    private val password: String
        get() = passwordField.get()

    val progressVisibility: ObservableInt = ObservableInt(View.GONE)

    @Suppress("PARAMETER_NAME_CHANGED_ON_OVERRIDE")
    fun login(view: View) {
        if (isEmailAndPasswordValid(email, password))
            ApiHelperImpl().doServerLoginApiCall(email, password)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeWith(object : CallbackWrapper<LoginResponse>() {

                        override fun onSuccess(loginResponse: LoginResponse) {
                        }
                    })

    }

    /**
     * Validate email and password. It checks email and password is empty or not
     * and validate email address is correct or not
     * @param email email address for login
     * @param password password for login
     * @return true if email and password pass all conditions else false
     */
    private fun isEmailAndPasswordValid(email: String, password: String): Boolean {

        if (email.isEmpty()) return false

        if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) return false

        if (password.isEmpty()) return false

        return true
    }

}
</code>```

LoginActivityModule.kt

```<code>@Module
class LoginActivityModule {

    @Provides
    fun providesLoginActivityViewModel(): LoginViewModel {
        return LoginViewModel()
    }
}
</code>```

ActivityBuilder.kt

```<code>@Module
abstract class ActivityBuilder {

    @ContributesAndroidInjector(modules = arrayOf(LoginActivityModule::class))
    abstract fun bindLoginActivity(): LoginActivity

}
</code>```

I am getting an error

```<code>Process: com.partner.android, PID: 9697
kotlin.UninitializedPropertyAccessException: lateinit property retrofit has not been initialized
    at com.partner.android.data.remote.ApiHelperImpl.doServerLoginApiCall(ApiHelperImpl.kt:32)
    at com.partner.android.login.LoginViewModel.login(LoginViewModel.kt:45)
    at com.partner.android.databinding.ActivityLoginBinding$OnClickListenerImpl.onClick(ActivityLoginBinding.java:298)
    at android.view.View.performClick(View.java:5637)
    at android.view.View$PerformClick.run(View.java:22429)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6119)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
</code>```

Why retrofit is not injecting in ApiHelperImpl class.

答:
You can implement the same using module

```<code>@Module
class ApiModule {

@Provides
@Singleton
fun apiService(context: Context): WebService {
    val mBaseUrl = context.getString(if (BuildConfig.DEBUG) R.string.local_url else R.string.live_url)

    val loggingInterceptor = HttpLoggingInterceptor()
    loggingInterceptor.level = if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE

    val okHttpClient = OkHttpClient.Builder()
            .readTimeout(120, TimeUnit.SECONDS)
            .writeTimeout(120, TimeUnit.SECONDS)
            .connectTimeout(120, TimeUnit.SECONDS)
            .addInterceptor(loggingInterceptor)
            //.addNetworkInterceptor(networkInterceptor)
            .build()

    return Retrofit.Builder().baseUrl(mBaseUrl)
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build().create(WebService::class.java)

}

}
</code>```

Also change in AppComponent

```<code>@Singleton
@Component(modules = arrayOf(ApplicationModule::class, ApiModule::class))
interface AppComponent {
...

fun apiService(): WebService

...
}
</code>```

your changes

```<code>@Component(modules = arrayOf(AndroidInjectionModule::class, AppModule::class, ApiModule ::class))
</code>```

add APIModule in relevant sub modules also

UPDATE

```<code>@Component(modules = arrayOf(AndroidInjectionModule::class, AppModule::class, ActivityBuilder::class))
@Singleton
interface AppComponent {
fun inject(app: PartnerApplication)
fun apiService(): ApiHelper
}
</code>```

and then inject whenever you want to use.

```<code>@Inject
var webService: WebService? = null
</code>```

Body:
Hi I am trying to inject retrofit in ApiHelperImpl.kt class. I have below module and component.

AppComponent.kt

@Component(modules = arrayOf(AndroidInjectionModule::class, AppModule::class, ActivityBuilder::class))
@Singleton
interface AppComponent {
    fun inject(app: PartnerApplication)
}

AppModule.kt

@Module
class AppModule {

    @Provides
    @Singleton
    fun providesPartnerApplication(application: Application): Application = application

    @Provides
    @Singleton
    fun providesSharedPreferences(application: Application): SharedPreferences {
        return PreferenceManager.getDefaultSharedPreferences(application)
    }

    @Provides
    @Singleton
    fun provideOkHttpCache(application: Application): Cache {
        val cacheSize = 10 * 1024 * 1024L // 10 MiB
        return Cache(application.cacheDir, cacheSize)
    }

    @Provides
    @Singleton
    fun provideMoshi(): Moshi = Moshi.Builder().build()

    @Provides
    @Singleton
    fun provideOkHttpClient(cache: Cache): OkHttpClient {
        val okHttpClient = OkHttpClient()
        okHttpClient.newBuilder()
                .cache(cache)
                .build()
        return okHttpClient
    }

    @Provides
    @Singleton
    fun provideRetrofit(moshi: Moshi, okHttpClient: OkHttpClient): Retrofit {
        return Retrofit.Builder()
                .addConverterFactory(MoshiConverterFactory.create(moshi))
                .baseUrl(BuildConfig.BASE_URL)
                .client(okHttpClient)
                .build()
    }

}

PartnerApplication.kt

class PartnerApplication : Application(), AnkoLogger, HasActivityInjector {

    @Inject lateinit var activityInjector: DispatchingAndroidInjector<Activity>

    override fun activityInjector(): AndroidInjector<Activity> {
        return activityInjector
    }

    override fun onCreate() {
        super.onCreate()
        DaggerAppComponent.create().inject(this)
    }

    override protected fun attachBaseContext(base: Context) {
        super.attachBaseContext(base)
        MultiDex.install(this)
    }

}

ApiHelper.kt

interface ApiHelper {
    fun doServerLoginApiCall(email: String, password: String): Observable<LoginResponse>
    fun doServerRegistrationApiCall(): Observable<RegistrationResponse>
}

ApiHelperImpl.kt

class ApiHelperImpl : ApiHelper {

    @Inject
    lateinit var retrofit: Retrofit

    override fun doServerLoginApiCall(email: String, password: String): Observable<LoginResponse> {
        return retrofit.create(RestApi::class.java).login(email, password)
    }

    override fun doServerRegistrationApiCall(): Observable<RegistrationResponse> {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }
}

LoginActivity.kt

class LoginActivity : BaseActivity() {

    @Inject
    lateinit var loginViewModel: LoginViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        performDependencyInjection()
        super.onCreate(savedInstanceState)
        val activityLoginBinding: ActivityLoginBinding = DataBindingUtil.setContentView<ActivityLoginBinding>(this, R.layout.activity_login)
        activityLoginBinding.loginViewModel = loginViewModel
    }
}

LoginViewModel.kt

class LoginViewModel : ViewModel(), AnkoLogger {

    val emailField = ObservableField<String>()

    private val email: String
        get() = emailField.get()

    val passwordField = ObservableField<String>()

    private val password: String
        get() = passwordField.get()

    val progressVisibility: ObservableInt = ObservableInt(View.GONE)

    @Suppress("PARAMETER_NAME_CHANGED_ON_OVERRIDE")
    fun login(view: View) {
        if (isEmailAndPasswordValid(email, password))
            ApiHelperImpl().doServerLoginApiCall(email, password)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeWith(object : CallbackWrapper<LoginResponse>() {

                        override fun onSuccess(loginResponse: LoginResponse) {
                        }
                    })

    }

    /**
     * Validate email and password. It checks email and password is empty or not
     * and validate email address is correct or not
     * @param email email address for login
     * @param password password for login
     * @return true if email and password pass all conditions else false
     */
    private fun isEmailAndPasswordValid(email: String, password: String): Boolean {

        if (email.isEmpty()) return false

        if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) return false

        if (password.isEmpty()) return false

        return true
    }

}

LoginActivityModule.kt

@Module
class LoginActivityModule {

    @Provides
    fun providesLoginActivityViewModel(): LoginViewModel {
        return LoginViewModel()
    }
}

ActivityBuilder.kt

@Module
abstract class ActivityBuilder {

    @ContributesAndroidInjector(modules = arrayOf(LoginActivityModule::class))
    abstract fun bindLoginActivity(): LoginActivity

}

I am getting an error

Process: com.partner.android, PID: 9697
kotlin.UninitializedPropertyAccessException: lateinit property retrofit has not been initialized
    at com.partner.android.data.remote.ApiHelperImpl.doServerLoginApiCall(ApiHelperImpl.kt:32)
    at com.partner.android.login.LoginViewModel.login(LoginViewModel.kt:45)
    at com.partner.android.databinding.ActivityLoginBinding$OnClickListenerImpl.onClick(ActivityLoginBinding.java:298)
    at android.view.View.performClick(View.java:5637)
    at android.view.View$PerformClick.run(View.java:22429)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6119)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

Why retrofit is not injecting in ApiHelperImpl class.

Body:
You can implement the same using module

@Module
class ApiModule {

@Provides
@Singleton
fun apiService(context: Context): WebService {
    val mBaseUrl = context.getString(if (BuildConfig.DEBUG) R.string.local_url else R.string.live_url)

    val loggingInterceptor = HttpLoggingInterceptor()
    loggingInterceptor.level = if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE

    val okHttpClient = OkHttpClient.Builder()
            .readTimeout(120, TimeUnit.SECONDS)
            .writeTimeout(120, TimeUnit.SECONDS)
            .connectTimeout(120, TimeUnit.SECONDS)
            .addInterceptor(loggingInterceptor)
            //.addNetworkInterceptor(networkInterceptor)
            .build()

    return Retrofit.Builder().baseUrl(mBaseUrl)
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build().create(WebService::class.java)

}

}

Also change in AppComponent

@Singleton
@Component(modules = arrayOf(ApplicationModule::class, ApiModule::class))
interface AppComponent {
...

fun apiService(): WebService

...
}

your changes

@Component(modules = arrayOf(AndroidInjectionModule::class, AppModule::class, ApiModule ::class))

add APIModule in relevant sub modules also

UPDATE

@Component(modules = arrayOf(AndroidInjectionModule::class, AppModule::class, ActivityBuilder::class))
@Singleton
interface AppComponent {
fun inject(app: PartnerApplication)
fun apiService(): ApiHelper
}

and then inject whenever you want to use.

@Inject
var webService: WebService? = null


问:
Align div to bottom of the page in bootstrap
I tried to use methods from stack questions, but nothing works for me, despite project is very simple.

```<code><div class="fluid-container">
    <div id="app-row" class="row">
        <div id="app" class="col-xs-5">
            <div class="top-navbar">
            Top
            </div>
            <div class="bottom-navbar">
            Bottom
            </div>
        </div>
        <div id="map-container" class="col-xs-7">
            <div id="map"></div>
        </div>
    </div>
</div>
</code>```

style.css

```<code>.fluid-container {
    margin: 0 0 0 0 !important;
    padding: 0 0 0 0 !important;
    width: 100%;
}

.row {
    margin: 0 0 0 0 !important;
    padding: 0 0 0 0 !important;
    width: 100%;
}

html, body, .fluid-container, #app-row, #map-container {
    height: 100%
}

#app-row {
    margin: 0 0 0 0 !important;
    padding: 0 0 0 0 !important;
}

#map-container {
    margin: 0 0 0 0 !important;
    padding: 0 0 0 0 !important;
}

#map {
    height: 100%;
    width: 100%;
}
</code>```

What I want to achieve:

Bottom is bottom of the page and Top is on the top of the page.

答:
You can do this using bootstrap 4 flexbox. </p>

```<code><div class="d-flex flex-column justify-content-between">
   <div></div>
   <div>bottom content</div>
</div>
</code>```

Body:
I tried to use methods from stack questions, but nothing works for me, despite project is very simple.

            Top

            Bottom

style.css

.fluid-container {
    margin: 0 0 0 0 !important;
    padding: 0 0 0 0 !important;
    width: 100%;
}

.row {
    margin: 0 0 0 0 !important;
    padding: 0 0 0 0 !important;
    width: 100%;
}

html, body, .fluid-container, #app-row, #map-container {
    height: 100%
}

#app-row {
    margin: 0 0 0 0 !important;
    padding: 0 0 0 0 !important;
}

#map-container {
    margin: 0 0 0 0 !important;
    padding: 0 0 0 0 !important;
}

#map {
    height: 100%;
    width: 100%;
}

What I want to achieve:

Bottom is bottom of the page and Top is on the top of the page.

Body:
You can do this using bootstrap 4 flexbox.

<div class="d-flex flex-column justify-content-between">
   <div></div>
   <div>bottom content</div>
</div>


问:
Exactly one of whitelist/blacklist/topic is required
I am trying to start Kafka consumer but it is showing below error:</p>

```<code>$ bin/kafka-console-consumer.sh --zookeeper localhost:2181 —topic Hello-Kafka
Exactly one of whitelist/blacklist/topic is required.
Option                                  Description
------                                  -----------
--blacklist <blacklist>                 Blacklist of topics to exclude from
                                          consumption.
--bootstrap-server <server to connect
  to>
--consumer.config <config file>         Consumer config properties file.
--csv-reporter-enabled                  If set, the CSV metrics reporter will
                                          be enabled
--delete-consumer-offsets               If specified, the consumer path in
                                          zookeeper is deleted when starting up

............
............
</code>```

答: bin/kafka-console-consumer.sh --zookeeper localhost:2181 —topic Hello-Kafka --from-beginning --whitelist Hello-Kafka</p>

Body:
I am trying to start Kafka consumer but it is showing below error:

$ bin/kafka-console-consumer.sh --zookeeper localhost:2181 —topic Hello-Kafka
Exactly one of whitelist/blacklist/topic is required.
Option                                  Description
------                                  -----------
--blacklist <blacklist>                 Blacklist of topics to exclude from
                                          consumption.
--bootstrap-server <server to connect
  to>
--consumer.config <config file>         Consumer config properties file.
--csv-reporter-enabled                  If set, the CSV metrics reporter will
                                          be enabled
--delete-consumer-offsets               If specified, the consumer path in
                                          zookeeper is deleted when starting up

............
............


问:
Unable to add drawable start with SVG to TextView for Android API lowers that 21
I'm trying to use drawable in textView like this

```<code><TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:drawableLeft="@drawable/svg_ic_profile_logout"
    android:drawablePadding="20dp"
    android:drawableStart="@drawable/svg_ic_profile_logout"
    android:gravity="center_vertical"
    android:onClick="@{viewModel.onLogoutClick}"
    android:text="@string/profile_logout"/>
</code>```

but the icon I using is SVG, it works perfectly fine for API > 21 but got a crash for API level lower than 21.

答:
Add  vectorDrawables.useSupportLibrary = true in you app level  build.gradle as follows:

```<code>  //For Gradle Plugin 2.0+
 android {
   defaultConfig {
     vectorDrawables.useSupportLibrary = true
    }
 }
</code>```

Refer to this guide.

Body:
I'm trying to use drawable in textView like this

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:drawableLeft="@drawable/svg_ic_profile_logout"
    android:drawablePadding="20dp"
    android:drawableStart="@drawable/svg_ic_profile_logout"
    android:gravity="center_vertical"
    android:onClick="@{viewModel.onLogoutClick}"
    android:text="@string/profile_logout"/>

but the icon I using is SVG, it works perfectly fine for API > 21 but got a crash for API level lower than 21.

Body:
Add  vectorDrawables.useSupportLibrary = true in you app level  build.gradle as follows:

  //For Gradle Plugin 2.0+
 android {
   defaultConfig {
     vectorDrawables.useSupportLibrary = true
    }
 }

Refer to this guide.


问:
Why does location matching change when using proxy_pass in nginx?

Simple nginx config

```<code>server {
  listen 0.0.0.0:80;

  server_name localhost 127.0.0.1;

  location /en-us/ {
    return 301 http://www.lego.com;
  }
}
</code>```

Here's what happens when I curl that config without a trailing slash on /en-us.

```<code>curl -v http://127.0.0.1/en-us -o /dev/null
# HTTP/1.1 404 Not Found
</code>```

I expect that 404. The location block is using a prefix match, and so it makes sense to me that /en-us is not matching that block.

Here's where I get confused...

Same config, but with a proxy_pass

Here I use the same config, but instead of returning a 301 I do a proxy_pass.

```<code>server {
  listen 0.0.0.0:80;

  server_name localhost 127.0.0.1;

  location /en-us/ {
    proxy_pass http://www.lego.com;
  }
}
</code>```

Now watch what happens when I run the same curl.

```<code>curl -v http://127.0.0.1/en-us -o /dev/null
# HTTP/1.1 301 Moved Permanently
</code>```

That 301 on /en-us makes no sense to me. It's redirecting to Location: http://127.0.0.1/en-us/.

In the first config, /en-us seemed to not match my location block (404). In the second config, /en-us did (301).

Why do the same location rules seem to match differently between my two configs?

Why would that second config result in a 301 to add a trailing slash?

I'm using nginx version: nginx/1.4.6 (Ubuntu)

答:
The documentation explains things clearly, as is pointed out in the comments.

If a location is defined by a prefix string that ends with the slash character, and requests are processed by one of proxy_pass, fastcgi_pass, ... then the special processing is performed ... a permanent redirect with the code 301 will be returned to the requested URI with the slash appended ...

Special processing is done for trailing slashes on a proxy_pass

Body:
Simple nginx config

server {
  listen 0.0.0.0:80;

  server_name localhost 127.0.0.1;

  location /en-us/ {
    return 301 http://www.lego.com;
  }
}

Here's what happens when I curl that config without a trailing slash on /en-us.

curl -v http://127.0.0.1/en-us -o /dev/null
# HTTP/1.1 404 Not Found

I expect that 404. The location block is using a prefix match, and so it makes sense to me that /en-us is not matching that block.

Here's where I get confused...

Same config, but with a proxy_pass

Here I use the same config, but instead of returning a 301 I do a proxy_pass.

server {
  listen 0.0.0.0:80;

  server_name localhost 127.0.0.1;

  location /en-us/ {
    proxy_pass http://www.lego.com;
  }
}

Now watch what happens when I run the same curl.

curl -v http://127.0.0.1/en-us -o /dev/null
# HTTP/1.1 301 Moved Permanently

That 301 on /en-us makes no sense to me. It's redirecting to Location: http://127.0.0.1/en-us/.

In the first config, /en-us seemed to not match my location block (404). In the second config, /en-us did (301).

Why do the same location rules seem to match differently between my two configs?

Why would that second config result in a 301 to add a trailing slash?

I'm using nginx version: nginx/1.4.6 (Ubuntu)


问:
Fix SVG height but allow horizontal scaling
I have an SVG image where I need keep a consistent height but allow it to grow horizontally with the view window. I've looked into the preserveAspectRatio attribute but cannot get it to do anything. I have a feeling there are other issues with my SVG attributes that are preventing this, but I'm very new to SVG and have yet to figure out what is causing the issue and/or conflict. I've also tried multiple different settings with the CSS with no success.

https://jsfiddle.net/cdsLb0wd/2/

.scoop__wrapper {
  background-color: black;
  overflow: hidden;
  top: 674px;
  //height: 382px;
  //width: 100%;
}

.combined-shape__scoop {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  width: 100%;
  z-index: 2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="scoop__wrapper">
  <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100%" height="392" viewBox="0 0 1440 392">
        <defs>
            <path id="b" d="M1440 .826V620H0V.826v22.826C241.31 82.55 481.31 112 720 112s478.69-29.45 720-88.348V.826z"/>
            <filter id="a" width="106.9%" height="116%" x="-3.4%" y="-8.5%" filterUnits="objectBoundingBox">
                <feOffset dy="-3" in="SourceAlpha" result="shadowOffsetOuter1"/>
                <feGaussianBlur in="shadowOffsetOuter1" result="shadowBlurOuter1" stdDeviation="16"/>
                <feColorMatrix in="shadowBlurOuter1" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0"/>
            </filter>
        </defs>
        <g fill="none" fill-rule="evenodd" transform="translate(-1 9)">
            <use fill="#000" filter="url(#a)" xlink:href="#b"/>
            <use fill="#FFF" xlink:href="#b"/>
        </g>
    </svg></code>```

答:
It's not clear exactly what effect you are after, but perhaps

```<code>preserveAspectRatio="none"
</code>```

gives the effect you want?

.scoop__wrapper {
    background-color: black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="scoop__wrapper">
<svg width="100%" height="392" viewBox="0 0 1440 392" preserveAspectRatio="none">
    <defs>
        <path id="b" d="M1440 .826V620H0V.826v22.826C241.31 82.55 481.31 112 720 112s478.69-29.45 720-88.348V.826z"/>
        <filter id="a" width="106.9%" height="116%" x="-3.4%" y="-8.5%" filterUnits="objectBoundingBox">
            <feOffset dy="-3" in="SourceAlpha" result="shadowOffsetOuter1"/>
            <feGaussianBlur in="shadowOffsetOuter1" result="shadowBlurOuter1" stdDeviation="16"/>
            <feColorMatrix in="shadowBlurOuter1" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0"/>
        </filter>
    </defs>
    <g fill="none" fill-rule="evenodd" transform="translate(-1 9)">
        <use fill="#000" filter="url(#a)" xlink:href="#b"/>
        <use fill="#FFF" xlink:href="#b"/>
    </g>
</svg>
</div></code>```

Demo: https://jsfiddle.net/cdsLb0wd/3/

Or perhaps you wanted the aspect ratio of the SVG to stay the same, and the SVG occupies the whole width. Then we should just view a portion of it based on the width.  In which case, you should use:

```<code>preserveAspectRatio="xMidYMin slice"
</code>```

.scoop__wrapper {
    background-color: black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="scoop__wrapper">
<svg width="100%" height="392" viewBox="0 0 1440 392" preserveAspectRatio="xMidYMin slice">
    <defs>
        <path id="b" d="M1440 .826V620H0V.826v22.826C241.31 82.55 481.31 112 720 112s478.69-29.45 720-88.348V.826z"/>
        <filter id="a" width="106.9%" height="116%" x="-3.4%" y="-8.5%" filterUnits="objectBoundingBox">
            <feOffset dy="-3" in="SourceAlpha" result="shadowOffsetOuter1"/>
            <feGaussianBlur in="shadowOffsetOuter1" result="shadowBlurOuter1" stdDeviation="16"/>
            <feColorMatrix in="shadowBlurOuter1" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0"/>
        </filter>
    </defs>
    <g fill="none" fill-rule="evenodd" transform="translate(-1 9)">
        <use fill="#000" filter="url(#a)" xlink:href="#b"/>
        <use fill="#FFF" xlink:href="#b"/>
    </g>
</svg>
</div></code>```

Demo: https://jsfiddle.net/cdsLb0wd/4/

Body:
I have an SVG image where I need keep a consistent height but allow it to grow horizontally with the view window. I've looked into the preserveAspectRatio attribute but cannot get it to do anything. I have a feeling there are other issues with my SVG attributes that are preventing this, but I'm very new to SVG and have yet to figure out what is causing the issue and/or conflict. I've also tried multiple different settings with the CSS with no success.

https://jsfiddle.net/cdsLb0wd/2/

.scoop__wrapper {
  background-color: black;
  overflow: hidden;
  top: 674px;
  //height: 382px;
  //width: 100%;
}

.combined-shape__scoop {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  width: 100%;
  z-index: 2;
}

  <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100%" height="392" viewBox="0 0 1440 392">
        <defs>
            <path id="b" d="M1440 .826V620H0V.826v22.826C241.31 82.55 481.31 112 720 112s478.69-29.45 720-88.348V.826z"/>
            <filter id="a" width="106.9%" height="116%" x="-3.4%" y="-8.5%" filterUnits="objectBoundingBox">
                <feOffset dy="-3" in="SourceAlpha" result="shadowOffsetOuter1"/>
                <feGaussianBlur in="shadowOffsetOuter1" result="shadowBlurOuter1" stdDeviation="16"/>
                <feColorMatrix in="shadowBlurOuter1" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0"/>
            </filter>
        </defs>
        <g fill="none" fill-rule="evenodd" transform="translate(-1 9)">
            <use fill="#000" filter="url(#a)" xlink:href="#b"/>
            <use fill="#FFF" xlink:href="#b"/>
        </g>
    </svg>

Body:
It's not clear exactly what effect you are after, but perhaps

preserveAspectRatio="none"

gives the effect you want?

.scoop__wrapper {
    background-color: black;
}

<div class="scoop__wrapper">
<svg width="100%" height="392" viewBox="0 0 1440 392" preserveAspectRatio="none">
    <defs>
        <path id="b" d="M1440 .826V620H0V.826v22.826C241.31 82.55 481.31 112 720 112s478.69-29.45 720-88.348V.826z"/>
        <filter id="a" width="106.9%" height="116%" x="-3.4%" y="-8.5%" filterUnits="objectBoundingBox">
            <feOffset dy="-3" in="SourceAlpha" result="shadowOffsetOuter1"/>
            <feGaussianBlur in="shadowOffsetOuter1" result="shadowBlurOuter1" stdDeviation="16"/>
            <feColorMatrix in="shadowBlurOuter1" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0"/>
        </filter>
    </defs>
    <g fill="none" fill-rule="evenodd" transform="translate(-1 9)">
        <use fill="#000" filter="url(#a)" xlink:href="#b"/>
        <use fill="#FFF" xlink:href="#b"/>
    </g>
</svg>
</div>

Demo: https://jsfiddle.net/cdsLb0wd/3/

Or perhaps you wanted the aspect ratio of the SVG to stay the same, and the SVG occupies the whole width. Then we should just view a portion of it based on the width.  In which case, you should use:

preserveAspectRatio="xMidYMin slice"

.scoop__wrapper {
    background-color: black;
}

<div class="scoop__wrapper">
<svg width="100%" height="392" viewBox="0 0 1440 392" preserveAspectRatio="xMidYMin slice">
    <defs>
        <path id="b" d="M1440 .826V620H0V.826v22.826C241.31 82.55 481.31 112 720 112s478.69-29.45 720-88.348V.826z"/>
        <filter id="a" width="106.9%" height="116%" x="-3.4%" y="-8.5%" filterUnits="objectBoundingBox">
            <feOffset dy="-3" in="SourceAlpha" result="shadowOffsetOuter1"/>
            <feGaussianBlur in="shadowOffsetOuter1" result="shadowBlurOuter1" stdDeviation="16"/>
            <feColorMatrix in="shadowBlurOuter1" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0"/>
        </filter>
    </defs>
    <g fill="none" fill-rule="evenodd" transform="translate(-1 9)">
        <use fill="#000" filter="url(#a)" xlink:href="#b"/>
        <use fill="#FFF" xlink:href="#b"/>
    </g>
</svg>
</div>

Demo: https://jsfiddle.net/cdsLb0wd/4/


问:
Cannot find package "api/handlers"
Ok so this question has been asked before and I believe I have looked through all of them to and tested the answers but I will explain how each one doesn't match my case. I might have missed the answer in one of those but I read each one and attempted to see if it could fit my case

How to import local packages in go? I believe my imports follow the structure of the answer

Go build: "Cannot find package" (even though GOPATH is set) I'm not sure if this one is fully pertinent but I don't think it's the same error.

Golang - Why can't I import local package in GOPATH/src/project but can in home directory? My import path isn't relative so this question isn't pertinent.

My error is simple:

```<code>cannot find package "api/handlers" in any of:
C:\Go\src\api\handlers (from $GOROOT)
C:\Projects\Go\src\api\handlers (from $GOPATH)`
</code>```

My project structure is as follows:

```<code>src
|
 --api
   |
    -- index.go
    -- repo.go
   |
   github.com
   |
   main.go
</code>```

Environment variables:

```<code>$GOPATH : C:\Projects\Go
$GOROOT : C:\Go\
</code>```

index and repo.go both have the same package name, imports, and just an empty function:

```<code>package handlers

import (
    "net/http"
)

func indexHandler(w http.ResponseWriter, r *http.Request) {
}
</code>```

My main.go:

```<code>package main

import (
    "fmt"
    "log"
    "net/http"
    "api/handlers"
)

func main() {
    http.HandleFunc("/api/index", handlers.indexHandler)
    http.HandleFunc("/api/repo", handlers.repoHandler)

    log.Fatal(http.ListenAndServer("localhost:8080", nil))
}
</code>```

答:
What's happening is that import api/handlers is looking for the folder handlers in the folder api, and then looking in the contents for the package name. Add a handlers folder inside api and move index.go and repo.go into that folder. Or just change the package name to api in those files and just do import api.

About your comment:

cannot refer to unexported name handlers.indexHandler

In order for you to be able to use function indexHandler from your main package, you should rename it to IndexHandler. In go, for things to be able to be accessed by other packages, the name needs to start with a capital letter.

Title: Cannot find package "api/handlers"

Body:
Ok so this question has been asked before and I believe I have looked through all of them to and tested the answers but I will explain how each one doesn't match my case. I might have missed the answer in one of those but I read each one and attempted to see if it could fit my case

How to import local packages in go? I believe my imports follow the structure of the answer

Go build: "Cannot find package" (even though GOPATH is set) I'm not sure if this one is fully pertinent but I don't think it's the same error.

Golang - Why can't I import local package in GOPATH/src/project but can in home directory? My import path isn't relative so this question isn't pertinent.

My error is simple:

cannot find package "api/handlers" in any of:
C:\Go\src\api\handlers (from $GOROOT)
C:\Projects\Go\src\api\handlers (from $GOPATH)`

My project structure is as follows:

src
|
 --api
   |
    -- index.go
    -- repo.go
   |
   github.com
   |
   main.go

Environment variables:

$GOPATH : C:\Projects\Go
$GOROOT : C:\Go\

index and repo.go both have the same package name, imports, and just an empty function:

package handlers

import (
    "net/http"
)

func indexHandler(w http.ResponseWriter, r *http.Request) {
}

My main.go:

package main

import (
    "fmt"
    "log"
    "net/http"
    "api/handlers"
)

func main() {
    http.HandleFunc("/api/index", handlers.indexHandler)
    http.HandleFunc("/api/repo", handlers.repoHandler)

    log.Fatal(http.ListenAndServer("localhost:8080", nil))
}


问:
How to remove border right form last child div?

How do i remove border right form the last div?

.process {
  border-right: 1px solid #e0e0e0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="job-posting">
  <div class="row">
    <div class="col-md-4">
      <div class="process">
        <header>STEP 1</header>
        <div class="process-content">
          <i class="fa fa-user-plus icon" aria-hidden="true"></i>
          <h1>Signup</h1>
          <p>Sign Up as a Company or an Individual</p>
        </div>
      </div>
    </div>
    <div class="col-md-4">
      <div class="process">
        <header>STEP 2</header>
        <div class="process-content">
          <i class="fa fa-upload icon" aria-hidden="true"></i>
          <h1>Upload Resume</h1>
          <p>Upload your resume and provide us with details of you experience and skills</p>
        </div>
      </div>
    </div>
    <div class="col-md-4">
      <div class="process">
        <header>STEP 3</header>
        <div class="process-content">
          <i class="fa fa-smile-o icon" aria-hidden="true"></i>
          <h1>Get Hired</h1>
          <p>Browse the available job postings and get hired according to your skills</p>
        </div>
      </div>
    </div>
  </div>
</div></code>```

I'm having trouble removing the right border form the last div I tried using the :last-child:border:remove;

答:
Get the last child using CSS :last-child pseudo-class selector. Apply the selector to the parent and get nested child since the parents are siblings.

.process {
  border-right: 1px solid #e0e0e0;
}

.col-md-4:last-child .process {
  border-right: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="job-posting">
  <div class="row">
    <div class="col-md-4">
      <div class="process">
        <header>STEP 1</header>
        <div class="process-content">
          <i class="fa fa-user-plus icon" aria-hidden="true"></i>
          <h1>Signup</h1>
          <p>Sign Up as a Company or an Individual</p>
        </div>
      </div>
    </div>
    <div class="col-md-4">
      <div class="process">
        <header>STEP 2</header>
        <div class="process-content">
          <i class="fa fa-upload icon" aria-hidden="true"></i>
          <h1>Upload Resume</h1>
          <p>Upload your resume and provide us with details of you experience and skills</p>
        </div>
      </div>
    </div>
    <div class="col-md-4">
      <div class="process">
        <header>STEP 3</header>
        <div class="process-content">
          <i class="fa fa-smile-o icon" aria-hidden="true"></i>
          <h1>Get Hired</h1>
          <p>Browse the available job postings and get hired according to your skills</p>
        </div>
      </div>
    </div>
  </div>
</div></code>```

Body:
How do i remove border right form the last div?

.process {
  border-right: 1px solid #e0e0e0;
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

        STEP 1

Signup

Sign Up as a Company or an Individual

        STEP 2

Upload Resume

Upload your resume and provide us with details of you experience and skills

        STEP 3

Get Hired

Browse the available job postings and get hired according to your skills

I'm having trouble removing the right border form the last div I tried using the :last-child:border:remove;

Body:
Get the last child using CSS :last-child pseudo-class selector. Apply the selector to the parent and get nested child since the parents are siblings.

.process {
  border-right: 1px solid #e0e0e0;
}

.col-md-4:last-child .process {
  border-right: none;
}

<div class="job-posting">
  <div class="row">
    <div class="col-md-4">
      <div class="process">
        <header>STEP 1</header>
        <div class="process-content">
          <i class="fa fa-user-plus icon" aria-hidden="true"></i>
          <h1>Signup</h1>
          <p>Sign Up as a Company or an Individual</p>
        </div>
      </div>
    </div>
    <div class="col-md-4">
      <div class="process">
        <header>STEP 2</header>
        <div class="process-content">
          <i class="fa fa-upload icon" aria-hidden="true"></i>
          <h1>Upload Resume</h1>
          <p>Upload your resume and provide us with details of you experience and skills</p>
        </div>
      </div>
    </div>
    <div class="col-md-4">
      <div class="process">
        <header>STEP 3</header>
        <div class="process-content">
          <i class="fa fa-smile-o icon" aria-hidden="true"></i>
          <h1>Get Hired</h1>
          <p>Browse the available job postings and get hired according to your skills</p>
        </div>
      </div>
    </div>
  </div>
</div>


问:
Longitude / Latitude to quaternion
I've got a longitude and latitude and want to convert this to a quaternion and wondering how I can do this? I want to use this, because I've got an app which projects the earth on a sphere and I want to rotate from one location to another one.

Best!

答:
There's a way to go about this without using matrices or vectors, similar to this numpy implementation. We can think of longitude/latitude as two quaternion rotations composed together.

Let's work with a Z-up right-handed coordinate system. Let's call longitude φ and latitude θ, and the point represented by the two as (φ, θ). For visualization, the red axis corresponds to X, green to Y, and blue to Z.

We want to find the quaternion representing the rotation from (0, 0), in red, to (a, b), in green:

We can represent this rotation as a combination first of the longitudinal rotation, then of the latitudinal rotation, like so:

First, we rotated by a along the Z axis, which transforms the X and Y axes. Then, we rotated by b along the new local Y axis. Thus, we know two sets of axis/angle information for this rotation.

Luckily, the conversion from axis/angle to quaternions is already known. Given an angle α and an axis vector ω, the resulting quaternion is:

```<code>(cos(α/2), ω.x*sin(α/2), ω.y*sin(α/2), ω.z*sin(α/2))
</code>```

So the first rotation is represented by a rotation of a degrees along the world (0, 0, 1) axis, giving us:

```<code>q1 = (cos(a/2), 0, 0, sin(a/2))
</code>```

The second rotation is represented by a rotation of b degrees along the transformed/local (0, 1, 0) axis, giving us:

```<code>q2 = (cos(b/2), 0, sin(b/2), 0)
</code>```

We can multiply these two quaternions to give us a single quaternion representing this compound rotation from (0, 0) to (a, b). The formula for quaternion multiplication is a bit lengthy, but you can find it here. The result:

```<code>q2*q1 = (cos(a/2)cos(b/2), -sin(a/2)sin(b/2), cos(a/2)sin(b/2), sin(a/2)cos(b/2))
</code>```

Not that it means much, but we can confirm that this formula is the same as the numpy implementation mentioned before.

JCooper mentioned a great point that one degree of freedom is still left, along the X axis in this case. If θ stays within ±90 degrees, we can imagine that the Z axis always pointing upwards. This has the effect of constraining the X axis rotation and is hopefully what you want.

Hope this helps!

edit: Notice that this is essentially the same thing as working with 2 Euler angles. So to reverse this conversion, you can use any quaternion to Euler angle conversion, provided that the rotation order is the same.

Title: Longitude / Latitude to quaternion

Body:
There's a way to go about this without using matrices or vectors, similar to this numpy implementation. We can think of longitude/latitude as two quaternion rotations composed together.

Let's work with a Z-up right-handed coordinate system. Let's call longitude φ and latitude θ, and the point represented by the two as (φ, θ). For visualization, the red axis corresponds to X, green to Y, and blue to Z.

We want to find the quaternion representing the rotation from (0, 0), in red, to (a, b), in green:

We can represent this rotation as a combination first of the longitudinal rotation, then of the latitudinal rotation, like so:

First, we rotated by a along the Z axis, which transforms the X and Y axes. Then, we rotated by b along the new local Y axis. Thus, we know two sets of axis/angle information for this rotation.

Luckily, the conversion from axis/angle to quaternions is already known. Given an angle α and an axis vector ω, the resulting quaternion is:

(cos(α/2), ω.x*sin(α/2), ω.y*sin(α/2), ω.z*sin(α/2))

So the first rotation is represented by a rotation of a degrees along the world (0, 0, 1) axis, giving us:

q1 = (cos(a/2), 0, 0, sin(a/2))

The second rotation is represented by a rotation of b degrees along the transformed/local (0, 1, 0) axis, giving us:

q2 = (cos(b/2), 0, sin(b/2), 0)

We can multiply these two quaternions to give us a single quaternion representing this compound rotation from (0, 0) to (a, b). The formula for quaternion multiplication is a bit lengthy, but you can find it here. The result:

q2*q1 = (cos(a/2)cos(b/2), -sin(a/2)sin(b/2), cos(a/2)sin(b/2), sin(a/2)cos(b/2))

Not that it means much, but we can confirm that this formula is the same as the numpy implementation mentioned before.

JCooper mentioned a great point that one degree of freedom is still left, along the X axis in this case. If θ stays within ±90 degrees, we can imagine that the Z axis always pointing upwards. This has the effect of constraining the X axis rotation and is hopefully what you want.

Hope this helps!

edit: Notice that this is essentially the same thing as working with 2 Euler angles. So to reverse this conversion, you can use any quaternion to Euler angle conversion, provided that the rotation order is the same.


答:
The CSS class name is process and all the div's that you have used has the same class name as in CSS...

Which means all the DIV with same class name will have the same property, in this case, a right border line..

So one thing you can do is change the class name...

Title: How to remove border right form last child div?


问:
What's the ugliest code you were forced to write by outside limitations?
What is the ugliest code that you wrote - not because you didn't know better, but because of limitations of the software, the hardware or the company policy?

Because of unusual choices in database layouts and programming languages, I once built a C program that read in a SQL database structure and generated another C program that'd read that database and back it up into a file, or copy it into a second database that shared more or less the same columns. It was a monster clunky code generator.

答:
In the late 90s I had to write several web sites in Informix Universal Server web blade (aka Illustra web blade)

For anyone who doesn't know anything about this execrable environment, it forced you to use the most bizarre language I have ever come across. As Joel Spolsky described it

When it did run, it proved to have the only programming language I've ever seen that wasn't Turing-equivalent, if you can imagine that.

More on it here http://philip.greenspun.com/wtr/illustra-tips.html

And an example of a 'simple' if condition:

```<code>cond=$(OR,$(NXST,$email),$(NXST,$name),$(NXST,$subject))
</code>```

One example of it's dire nature was the fact that it had no loops. Of any kind. It was possible to hack looping functionality by creating a query and iterating through its rows, but that is so wrong it makes me feel sick.

edit: I've managed to find a complete code sample. Behold:

```<code><HTML>
<HEAD><TITLE>WINSTART bug</TITLE></HEAD>
<BODY>
<!--- Initialization --->
<?MIVAR NAME=WINSIZE DEFAULT=4>$WINSIZE<?/MIVAR>
<?MIVAR NAME=BEGIN DEFAULT=1>$START<?/MIVAR>

<!--- Definition of Ranges ---->
<?MIVAR NAME=BEGIN>$(IF,$(<,$BEGIN,1),1,$BEGIN)<?/MIVAR>
<?MIVAR NAME=END>$(+,$BEGIN,$WINSIZE)<?/MIVAR>
<!--- Execution --->
<TABLE BORDER>
<?MISQL WINSTART=$BEGIN WINSIZE=$WINSIZE
    SQL="select tabname from systables where tabname like 'web%'
        order by tabname;">
    <TR><TD>$1</TD></TR>
<?/MISQL>
</TABLE>
<BR>
<?MIBLOCK COND="$(>,$BEGIN,1)">
    <?MIVAR>
    <A HREF=$WEB_HOME?MIval=WINWALK&START=$(-,$BEGIN,$WINSIZE)&WINSIZE=$WINSIZE>
    Previous $WINSIZE Rows </A> $(IF,$(<,$MI_ROWCOUNT,$WINSIZE), No More Rows,  )
    <?/MIVAR>
<?/MIBLOCK>
<?MIBLOCK COND="$(AND,$(>,$END,$WINSIZE),$(>=,$MI_ROWCOUNT,$WINSIZE))">
    <?MIVAR>
    <A HREF=$WEB_HOME?MIval=WINWALK&START=$END&WINSIZE=$WINSIZE>
    Next $WINSIZE Rows  </A>
    <?/MIVAR>
<?/MIBLOCK>
</BODY>
</code>```

Body:
In the late 90s I had to write several web sites in Informix Universal Server web blade (aka Illustra web blade)

For anyone who doesn't know anything about this execrable environment, it forced you to use the most bizarre language I have ever come across. As Joel Spolsky described it

When it did run, it proved to have the only programming language I've ever seen that wasn't Turing-equivalent, if you can imagine that.

More on it here http://philip.greenspun.com/wtr/illustra-tips.html

And an example of a 'simple' if condition:

cond=$(OR,$(NXST,$email),$(NXST,$name),$(NXST,$subject))

One example of it's dire nature was the fact that it had no loops. Of any kind. It was possible to hack looping functionality by creating a query and iterating through its rows, but that is so wrong it makes me feel sick.

edit: I've managed to find a complete code sample. Behold:

<HTML>
<HEAD><TITLE>WINSTART bug</TITLE></HEAD>
<BODY>
<!--- Initialization --->
<?MIVAR NAME=WINSIZE DEFAULT=4>$WINSIZE<?/MIVAR>
<?MIVAR NAME=BEGIN DEFAULT=1>$START<?/MIVAR>

<!--- Definition of Ranges ---->
<?MIVAR NAME=BEGIN>$(IF,$(<,$BEGIN,1),1,$BEGIN)<?/MIVAR>
<?MIVAR NAME=END>$(+,$BEGIN,$WINSIZE)<?/MIVAR>
<!--- Execution --->
<TABLE BORDER>
<?MISQL WINSTART=$BEGIN WINSIZE=$WINSIZE
    SQL="select tabname from systables where tabname like 'web%'
        order by tabname;">
    <TR><TD>$1</TD></TR>
<?/MISQL>
</TABLE>
<BR>
<?MIBLOCK COND="$(>,$BEGIN,1)">
    <?MIVAR>
    <A HREF=$WEB_HOME?MIval=WINWALK&START=$(-,$BEGIN,$WINSIZE)&WINSIZE=$WINSIZE>
    Previous $WINSIZE Rows </A> $(IF,$(<,$MI_ROWCOUNT,$WINSIZE), No More Rows,  )
    <?/MIVAR>
<?/MIBLOCK>
<?MIBLOCK COND="$(AND,$(>,$END,$WINSIZE),$(>=,$MI_ROWCOUNT,$WINSIZE))">
    <?MIVAR>
    <A HREF=$WEB_HOME?MIval=WINWALK&START=$END&WINSIZE=$WINSIZE>
    Next $WINSIZE Rows  </A>
    <?/MIVAR>
<?/MIBLOCK>
</BODY>

OwnerDisplayName: HermanD

LastEditorDisplayName: HermanD


问:
Apply different class to table tr based on image title
```<code><table id='xhtmlgrid'>
<tbody>
<tr class='bgwhite'>
<td>
<table>
<tbody>
<tr>
<td>
<span>
<img src="./secured_off1.png">
</span>
</td>
<td>
<span>
<img src="./secured_off2.png">
</span>
</td>
<td>
<span>
<img src="./secured_off3.png" title="Locked">
</span>
</td>
<td>
<span>
<img src="./secured_off4.png">
</span>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</code>```

i have code like this,based on image title,i have multiple images in that tr, i want to change the tr class from bgwhite to bggreen,how can i do that,any help appreciated.

so far i'm using this code to find the image title

```<code>$("#xhtml_grid table > tbody > tr").each(function () {
        var hdnLock = $(this).find('td:eq(2)').find('img').attr('title');
        if (hdnLock == 'Locked') {
        }

    });
</code>```

for reference i'm adding the image of html

答:
Your code is mostly correct. I had to change the table id in the first selector. And I removed the td:eq(2). It wasn't correct. You can select image directly instead assuming there is only one image in the row.

$("#xhtmlgrid tbody > tr").each(function () {
  var hdnLock = $(this).find('img').attr('title');
  if (hdnLock == 'Locked') {
    $(this).addClass('bggreen').removeClass('bgwhite');
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.bgwhite {
  background: red;
}

.bggreen {
  background: green;
}</code>```

```

Body:
i have code like this,based on image title,i have multiple images in that tr, i want to change the tr class from bgwhite to bggreen,how can i do that,any help appreciated.

so far i'm using this code to find the image title

$("#xhtml_grid table > tbody > tr").each(function () {
        var hdnLock = $(this).find('td:eq(2)').find('img').attr('title');
        if (hdnLock == 'Locked') {
        }

    });

for reference i'm adding the image of html

Body:
Your code is mostly correct. I had to change the table id in the first selector. And I removed the td:eq(2). It wasn't correct. You can select image directly instead assuming there is only one image in the row.

$("#xhtmlgrid tbody > tr").each(function () {
  var hdnLock = $(this).find('img').attr('title');
  if (hdnLock == 'Locked') {
    $(this).addClass('bggreen').removeClass('bgwhite');
  }
});

.bgwhite {
  background: red;
}

.bggreen {
  background: green;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='xhtmlgrid'>
  <tbody>
  <tr class='bgwhite'>
    <td>
    <table>
      <tbody>
        <tr>
          <td>
            <img src="./secured_off.png" title="Locked">
          </td>
        </tr>
      </tbody>
    </table>
    </td>
  </tr>
  </tbody>
</table>