问:
Python: Google API if loop
I'm checking Google API response:

```<code>url = 'https://maps.googleapis.com/maps/api/place/textsearch/json?'
params = {'location': '-38.30000000,176.15000000',
          'radius': '5000',
          'type': 'movie_theater',
          'key': 'MY_KEY'}
response = requests.get(url = url, params=params)
# if response.status_code == 200:
response_data = response.json()

if 'results' in response_data:
    print ('There are results')
elif response_data['status'] == 'ZERO_RESULTS':
    print ('nothing')
</code>```

If you search with Postman for that specific location:

```<code>https://maps.googleapis.com/maps/api/place/textsearch/json?location=-38.30000000,176.15000000&radius=5000&type=movie_theater&key=MY_KEY
</code>```

there are no cinemas and Google API reports:

```<code>{
  "html_attributions": [],
  "results": [],
  "status": "ZERO_RESULTS"
}
</code>```

unfortunately my if, elif seems not working because it doesn't print nothing.
Where am I wrong?

答:
You should modify your code to:

```<code>if len(response_data['results']) in response_data:
    print ('There are results')

elif response_data['status'] == 'ZERO_RESULTS':
    print ('nothing')
</code>```

OR

Just change the order of the conditions:

```<code>if response_data['status'] == 'ZERO_RESULTS':
    print ('nothing')

elif 'results' in response_data:
    print ('There are results')
</code>```

Title: Python: Google API if loop

Body:
I'm checking Google API response:

url = 'https://maps.googleapis.com/maps/api/place/textsearch/json?'
params = {'location': '-38.30000000,176.15000000',
          'radius': '5000',
          'type': 'movie_theater',
          'key': 'MY_KEY'}
response = requests.get(url = url, params=params)
# if response.status_code == 200:
response_data = response.json()

if 'results' in response_data:
    print ('There are results')
elif response_data['status'] == 'ZERO_RESULTS':
    print ('nothing')

If you search with Postman for that specific location:

https://maps.googleapis.com/maps/api/place/textsearch/json?location=-38.30000000,176.15000000&radius=5000&type=movie_theater&key=MY_KEY

there are no cinemas and Google API reports:

{
  "html_attributions": [],
  "results": [],
  "status": "ZERO_RESULTS"
}

unfortunately my if, elif seems not working because it doesn't print nothing.
Where am I wrong?

Body:
You should modify your code to:

if len(response_data['results']) in response_data:
    print ('There are results')

elif response_data['status'] == 'ZERO_RESULTS':
    print ('nothing')

OR

Just change the order of the conditions:

if response_data['status'] == 'ZERO_RESULTS':
    print ('nothing')

elif 'results' in response_data:
    print ('There are results')


来源: stackexchange

问:
Rendering unicode font with pygame
I'm currently attempting to render text read from a file onto the screen using pygame. However, when I attempt to render a non-standard Unicode character (i.e. Japanese hirigana), it responds only with an assortment of random characters and boxes. I've searched through everything I could find and nothing works. Any ideas? The file is properly encoded and read in UTF-8, so the problem is during the rendering stage.

My text rendering code:

```<code>def text(screen, pos, text='', font=None, color=BLACK, halign='LEFT', valign='TOP'):
    if font == None: font = pygame.font.Font(None,16)
    draw = font.render(text.encode('utf8'), True, color)
    pos = list(pos)

    if halign.upper() == 'CENTER': pos[0] -= font.size(text)[0]/2
    if halign.upper() == 'RIGHT': pos[0] -= font.size(text)[0]

    if valign.upper() == 'CENTER': pos[1] -= font.size(text)[1]/2
    if valign.upper() == 'BOTTOM': pos[1] -= font.size(text)[1]

    screen.blit(draw, pos)
</code>```

The text I'm trying to render:

```<code>おはようございます、みんな！
</code>```

The result:
http://imgur.com/VDctx8N

EDIT: After some testing, it turns out that it was the font I was using... Along those lines, does anyone know of an alternative to Segoe UI Light that has kana support?

答:
On Debian, it's available setofont (fonts-seto)

```

    font_file = pygame.font.match_font("setofont")  # Select and
    font = pygame.font.Font(font_file, 30)          # open the font
    writing = font.render(u"おはようございます、みんな！", True, (0, 0, 0))

```

ContentLicense: CC BY-SA 3.0

Title: Rendering unicode font with pygame

Body:
I'm currently attempting to render text read from a file onto the screen using pygame. However, when I attempt to render a non-standard Unicode character (i.e. Japanese hirigana), it responds only with an assortment of random characters and boxes. I've searched through everything I could find and nothing works. Any ideas? The file is properly encoded and read in UTF-8, so the problem is during the rendering stage.

My text rendering code:

def text(screen, pos, text='', font=None, color=BLACK, halign='LEFT', valign='TOP'):
    if font == None: font = pygame.font.Font(None,16)
    draw = font.render(text.encode('utf8'), True, color)
    pos = list(pos)

    if halign.upper() == 'CENTER': pos[0] -= font.size(text)[0]/2
    if halign.upper() == 'RIGHT': pos[0] -= font.size(text)[0]

    if valign.upper() == 'CENTER': pos[1] -= font.size(text)[1]/2
    if valign.upper() == 'BOTTOM': pos[1] -= font.size(text)[1]

    screen.blit(draw, pos)

The text I'm trying to render:

おはようございます、みんな！

The result:
http://imgur.com/VDctx8N

EDIT: After some testing, it turns out that it was the font I was using... Along those lines, does anyone know of an alternative to Segoe UI Light that has kana support?

Body:
On Debian, it's available setofont (fonts-seto)

    font_file = pygame.font.match_font("setofont")  # Select and
    font = pygame.font.Font(font_file, 30)          # open the font
    writing = font.render(u"おはようございます、みんな！", True, (0, 0, 0))


问:
Remove first character from string if 0
I need to remove the first character from my UITextfield if it's a 0.

Unfortunately I don't know how to extract the value of the first character or extract the characters of the string after the first character.

Thanks

答:
Swift 3

hasPrefix("0") check if the first character is 0 in txtField
and remove it

```<code>if (self.txtField.text?.hasPrefix("0"))! {
    self.txtField.text?.remove(at(self.txtField.text?.startIndex)!)
}
</code>```

Title: Remove first character from string if 0

Body:
Swift 3

hasPrefix("0") check if the first character is 0 in txtField
and remove it

if (self.txtField.text?.hasPrefix("0"))! {
    self.txtField.text?.remove(at(self.txtField.text?.startIndex)!)
}


问:
How to check against a value range in a mapping table?
Inputs:

```<code>library(dplyr)
A <- data_frame(Type=c("A","A","B"),R=c(3, 7, 12), Value = c(120, 130,300))
A
   Type     R Value
  (chr) (dbl) (dbl)
1     A     3   120
2     A     7   130
3     B    12   300
</code>```

Mapping dataset:

```<code>Mapping <- data_frame(Type=c("A","A","A","B","B","B"), Rmin =     c(1,6,11,1,6,11), Rmax = c(5,10,15,5,10,15), Threshold = c(50,100,200,50,200,300))
Mapping

   Type  Rmin  Rmax Threshold
  (chr) (dbl) (dbl)     (dbl)
1     A     1     5        50
2     A     6    10       100
3     A    11    15       200
4     B     1     5        50
5     B     6    10       200
6     B    11    15       300
</code>```

Output are expected to get with following step.

With the same Type value among A and Mapping, find the threshold value for the entry that has R >= Rmin and R <= Rmax. For example, for row 1 table in A, the threhold should be 50 (1<=3<=5, and type A).

isAbove value is obtained by assigning isAbove <- 120>=50

As a result, the expected output is:

```<code>B <-  data_frame(Type=c("A","A","B"),R=c(3, 7, 12), Value = c(60, 90,250), isAbove = c(T,F,F))
 B

    Type     R Value isAbove
   (chr) (dbl) (dbl)   (lgl)
 1     A     3    120    TRUE
 2     A     7    130   TRUE
 3     B    12    300  FALSE
</code>```

答:
Using the non-equi join capability of data.table is perfectly suited for that. Using:

```<code>library(data.table)

setDT(A)
setDT(Mapping)

A[Mapping, on = .(Type, R > Rmin, R < Rmax), isAbove := Value > Threshold]
</code>```

gives you:

```<code>> A
   Type  R Value isAbove
1:    A  3   120    TRUE
2:    A  7   130    TRUE
3:    B 12   300   FALSE
</code>```

Body:
Inputs:

library(dplyr)
A <- data_frame(Type=c("A","A","B"),R=c(3, 7, 12), Value = c(120, 130,300))
A
   Type     R Value
  (chr) (dbl) (dbl)
1     A     3   120
2     A     7   130
3     B    12   300

Mapping dataset:

Mapping <- data_frame(Type=c("A","A","A","B","B","B"), Rmin =     c(1,6,11,1,6,11), Rmax = c(5,10,15,5,10,15), Threshold = c(50,100,200,50,200,300))
Mapping

   Type  Rmin  Rmax Threshold
  (chr) (dbl) (dbl)     (dbl)
1     A     1     5        50
2     A     6    10       100
3     A    11    15       200
4     B     1     5        50
5     B     6    10       200
6     B    11    15       300

Output are expected to get with following step.

With the same Type value among A and Mapping, find the threshold value for the entry that has R >= Rmin and R <= Rmax. For example, for row 1 table in A, the threhold should be 50 (1<=3<=5, and type A).

isAbove value is obtained by assigning isAbove <- 120>=50

As a result, the expected output is:

B <-  data_frame(Type=c("A","A","B"),R=c(3, 7, 12), Value = c(60, 90,250), isAbove = c(T,F,F))
 B

    Type     R Value isAbove
   (chr) (dbl) (dbl)   (lgl)
 1     A     3    120    TRUE
 2     A     7    130   TRUE
 3     B    12    300  FALSE

Body:
Using the non-equi join capability of data.table is perfectly suited for that. Using:

library(data.table)

setDT(A)
setDT(Mapping)

A[Mapping, on = .(Type, R > Rmin, R < Rmax), isAbove := Value > Threshold]

gives you:

> A
   Type  R Value isAbove
1:    A  3   120    TRUE
2:    A  7   130    TRUE
3:    B 12   300   FALSE


问:
How do I shuffle an array in Swift?
.shuffle() and .shuffled() are part of Swift

Original historic question:

How do I randomize or shuffle the elements within an array in Swift? For example, if my array consists of 52 playing cards, I want to shuffle the array in order to shuffle the deck.

答:
```<code>let shuffl = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: arrayObject)
</code>```

ContentLicense: CC BY-SA 4.0

Title: How do I shuffle an array in Swift?


问:
How to properly remove Timer instance
I am using Timer instance in my project.

I create and add an instance to RunLoop

```<code>timer = Timer(timeInterval: 0.1, repeats: true, block: { (timer) in
    print("Hello")
})

if let timer = timer {
    RunLoop.current.add(timer, forMode: .commonModes)
}
</code>```

Now I am thinking about how to properly stop and remove Timer:

Should I trust in ARC and don't care about it?

Maybe deinit implementation is need. If is it true, what should be inside

```<code>deinit {
    longPressTimer?.invalidate()
    longPressTimer = nil
}
</code>```

invalidate is nesseccery? = nil ?

I have read serval threads from Stack about it but answers are contradictory. Could someone tell me which way is properly and explain me why?

答:
You need both invalidate() and = nil. <s>Unlike other objects, a timer DOES NOT get deallocated when its retain count reaches zero unless it's stopped (invalidated). </s>

Say, if you have a repeating timer which is currently active. when you set timer = nil, it still persists in memory and keeps triggering the action (probably the iOS has some kinds of mechanism to keep it alive as long as it's still active). So the rule of thumb is: Always call invalidate() and  set the timer to nil when you want to get rid of it.

Title: How to properly remove Timer instance

Body:
I am using Timer instance in my project.

I create and add an instance to RunLoop

timer = Timer(timeInterval: 0.1, repeats: true, block: { (timer) in
    print("Hello")
})

if let timer = timer {
    RunLoop.current.add(timer, forMode: .commonModes)
}

Now I am thinking about how to properly stop and remove Timer:

Should I trust in ARC and don't care about it?

Maybe deinit implementation is need. If is it true, what should be inside

deinit {
    longPressTimer?.invalidate()
    longPressTimer = nil
}

invalidate is nesseccery? = nil ?

I have read serval threads from Stack about it but answers are contradictory. Could someone tell me which way is properly and explain me why?


问:
joins on multiple keys in linq
How to write this query in Linq?

```<code>SELECT e.STARTDATE,
       e.REASON,
       s.DESCRIPTION
  FROM E_JOURNAL j inner join
       E_ABSENCE e on j.JOURNALID = e.JOURNALID AND
               e.ABSENCEHISTORYID = (SELECT MAX(ABSENCEHISTORYID)
                                       FROM E_ABSENCE
                                      WHERE JOURNALID = j.JOURNALID) INNER JOIN
       E_STATUS s on j.CURRENTITEMSTATUSID = s.ITEMSTATUSID INNER JOIN
       E_NATURE n on j.ITEMNATUREID = n.ITEMNATUREID
 WHERE j.EMPLOYEEID = 113
</code>```

答:
Try code like this</p>

```<code>using System.Collections.ObjectModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication57
{
    class Program
    {
        static void Main(string[] args)
        {
            int employeeId = 113;

            List<E_JOURNAL> employee = E_JOURNAL.journals.Where(x => x.JOURNALID == employeeId).ToList();

            var results = (from j in employee
                           join s in E_ABSENCE.absenses on j.JOURNALID equals s.JOURNALID
                           orderby s.ABSENCEHISTORYID descending
                           select new {
                               startDate = s.STARTDATE,
                               reason = s.REASON,
                                description = E_STATUS.statuses.Where(x => x.CURRENTITEMSTATUSID == j.CURRENTITEMSTATUSID).Select(x => x.DESCRIPTION).FirstOrDefault()
                           }).FirstOrDefault();
        }

    }
    public class E_JOURNAL
    {
        public static List<E_JOURNAL> journals = new List<E_JOURNAL>();

        public int JOURNALID { get; set; }
        public int ITEMNATUREID { get; set; }
        public int EMPLOYEEID { get; set; }
        public int CURRENTITEMSTATUSID { get; set; }

    }
    public class E_STATUS
    {
        public static List<E_STATUS > statuses = new List<E_STATUS>();

        public string DESCRIPTION { get; set; }
        public int CURRENTITEMSTATUSID { get; set; }

    }
    public class E_ABSENCE
    {
        public static List<E_ABSENCE> absenses = new List<E_ABSENCE>();

        public int JOURNALID { get; set; }
        public DateTime STARTDATE { get; set; }
        public string REASON { get; set; }
        public int ABSENCEHISTORYID { get; set; }
    }
    public class E_NATURE
    {
        public static List<E_NATURE> natures = new List<E_NATURE>();

        public int ITEMNATUREID { get; set; }
    }

}
</code>```

Title: joins on multiple keys in linq

Body:
How to write this query in Linq?

SELECT e.STARTDATE,
       e.REASON,
       s.DESCRIPTION
  FROM E_JOURNAL j inner join
       E_ABSENCE e on j.JOURNALID = e.JOURNALID AND
               e.ABSENCEHISTORYID = (SELECT MAX(ABSENCEHISTORYID)
                                       FROM E_ABSENCE
                                      WHERE JOURNALID = j.JOURNALID) INNER JOIN
       E_STATUS s on j.CURRENTITEMSTATUSID = s.ITEMSTATUSID INNER JOIN
       E_NATURE n on j.ITEMNATUREID = n.ITEMNATUREID
 WHERE j.EMPLOYEEID = 113

Body:
Try code like this

using System.Collections.ObjectModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication57
{
    class Program
    {
        static void Main(string[] args)
        {
            int employeeId = 113;

            List<E_JOURNAL> employee = E_JOURNAL.journals.Where(x => x.JOURNALID == employeeId).ToList();

            var results = (from j in employee
                           join s in E_ABSENCE.absenses on j.JOURNALID equals s.JOURNALID
                           orderby s.ABSENCEHISTORYID descending
                           select new {
                               startDate = s.STARTDATE,
                               reason = s.REASON,
                                description = E_STATUS.statuses.Where(x => x.CURRENTITEMSTATUSID == j.CURRENTITEMSTATUSID).Select(x => x.DESCRIPTION).FirstOrDefault()
                           }).FirstOrDefault();
        }

    }
    public class E_JOURNAL
    {
        public static List<E_JOURNAL> journals = new List<E_JOURNAL>();

        public int JOURNALID { get; set; }
        public int ITEMNATUREID { get; set; }
        public int EMPLOYEEID { get; set; }
        public int CURRENTITEMSTATUSID { get; set; }

    }
    public class E_STATUS
    {
        public static List<E_STATUS > statuses = new List<E_STATUS>();

        public string DESCRIPTION { get; set; }
        public int CURRENTITEMSTATUSID { get; set; }

    }
    public class E_ABSENCE
    {
        public static List<E_ABSENCE> absenses = new List<E_ABSENCE>();

        public int JOURNALID { get; set; }
        public DateTime STARTDATE { get; set; }
        public string REASON { get; set; }
        public int ABSENCEHISTORYID { get; set; }
    }
    public class E_NATURE
    {
        public static List<E_NATURE> natures = new List<E_NATURE>();

        public int ITEMNATUREID { get; set; }
    }

}


问:
jHipster - Loading data
Is there a workflow for adding data with jHipster?

I want to add static data for the H2 database in the first instance, is this process different when using MySql, postgresql?

I note there is a users.csv which is loaded via liquibase, I'm guessing I create another csv and load that.

Cheers..

答:
It's the same for all SQL databases as it uses Liquibase, you must create a Liquibase changelog that uses loadData to load your CSV file from src/main/resources/config/liquibase/data and refer to it from master.xml.

Additionally, you can also tag your changelog so that this data is only loaded for H2 by setting a conditional dbms="h2" or use a condition on Liquibase context context="dev" that you can then set in application*.yml.

Title: jHipster - Loading data


问:
Sinatra and MacRuby not working
Can't seem to get Sinatra and MacRuby/control_tower to work together.

My sinatra server is pretty simple (main.rb):

```<code>require 'rubygems'
require 'sinatra'

get "/" do
  "Hello World!"
end
</code>```

With a very simple RackUp file (config.ru):

```<code>require 'main'
run Sinatra::Application
</code>```

running: control_tower looks like it's working but then blows up:

```<code>You are cleared for take-off!
Listening on 0.0.0.0:3000
NoMethodError - undefined method `GET /' for #<Sinatra::Application:0x20026c9e0>:
 /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/sinatra-1.1.0/lib/sinatra/base.rb:1033:in `block'
 /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/sinatra-1.1.0/lib/sinatra/base.rb:604:in `block'
 /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/sinatra-1.1.0/lib/sinatra/base.rb:654:in `block'
 /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/sinatra-1.1.0/lib/sinatra/base.rb:631:in `process_route:'
 /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/sinatra-1.1.0/lib/sinatra/base.rb:603:in `block'
 /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/sinatra-1.1.0/lib/sinatra/base.rb:600:in `route!'
 /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/sinatra-1.1.0/lib/sinatra/base.rb:739:in `dispatch!'
 /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/sinatra-1.1.0/lib/sinatra/base.rb:530:in `block'
 /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/sinatra-1.1.0/lib/sinatra/base.rb:706:in `block'
 /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/sinatra-1.1.0/lib/sinatra/base.rb:706:in `invoke'
 /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/sinatra-1.1.0/lib/sinatra/base.rb:523:in `call!:'
 /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/rack-1.2.1/lib/rack/showexceptions.rb:24:in `call:'
 /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/sinatra-1.1.0/lib/sinatra/base.rb:1142:in `block'
 /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/sinatra-1.1.0/lib/sinatra/base.rb:1142:in `call:'
 /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/control_tower-1.0/lib/control_tower/rack_socket.rb:46:in `block'
NoMethodError: undefined method `GET /' for #<Sinatra::Application:0x20026c9e0>
    /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/sinatra-1.1.0/lib/sinatra/base.rb:739:in `dispatch!'
    /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/sinatra-1.1.0/lib/sinatra/base.rb:530:in `block'
    /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/sinatra-1.1.0/lib/sinatra/base.rb:706:in `block'
    /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/sinatra-1.1.0/lib/sinatra/base.rb:706:in `invoke'
    /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/sinatra-1.1.0/lib/sinatra/base.rb:523:in `call!:'
    /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/rack-1.2.1/lib/rack/showexceptions.rb:24:in `call:'
    /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/sinatra-1.1.0/lib/sinatra/base.rb:1142:in `block'
    /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/sinatra-1.1.0/lib/sinatra/base.rb:1142:in `call:'
</code>```

答: Please report bugs to the MacRuby project instead of this website. http://www.macruby.org/contact-us.html</p>

ContentLicense: CC BY-SA 2.5

Title: Sinatra and MacRuby not working

Body:
Can't seem to get Sinatra and MacRuby/control_tower to work together.

My sinatra server is pretty simple (main.rb):

require 'rubygems'
require 'sinatra'

get "/" do
  "Hello World!"
end

With a very simple RackUp file (config.ru):

require 'main'
run Sinatra::Application

running: control_tower looks like it's working but then blows up:

You are cleared for take-off!
Listening on 0.0.0.0:3000
NoMethodError - undefined method `GET /' for #<Sinatra::Application:0x20026c9e0>:
 /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/sinatra-1.1.0/lib/sinatra/base.rb:1033:in `block'
 /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/sinatra-1.1.0/lib/sinatra/base.rb:604:in `block'
 /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/sinatra-1.1.0/lib/sinatra/base.rb:654:in `block'
 /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/sinatra-1.1.0/lib/sinatra/base.rb:631:in `process_route:'
 /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/sinatra-1.1.0/lib/sinatra/base.rb:603:in `block'
 /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/sinatra-1.1.0/lib/sinatra/base.rb:600:in `route!'
 /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/sinatra-1.1.0/lib/sinatra/base.rb:739:in `dispatch!'
 /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/sinatra-1.1.0/lib/sinatra/base.rb:530:in `block'
 /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/sinatra-1.1.0/lib/sinatra/base.rb:706:in `block'
 /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/sinatra-1.1.0/lib/sinatra/base.rb:706:in `invoke'
 /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/sinatra-1.1.0/lib/sinatra/base.rb:523:in `call!:'
 /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/rack-1.2.1/lib/rack/showexceptions.rb:24:in `call:'
 /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/sinatra-1.1.0/lib/sinatra/base.rb:1142:in `block'
 /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/sinatra-1.1.0/lib/sinatra/base.rb:1142:in `call:'
 /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/control_tower-1.0/lib/control_tower/rack_socket.rb:46:in `block'
NoMethodError: undefined method `GET /' for #<Sinatra::Application:0x20026c9e0>
    /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/sinatra-1.1.0/lib/sinatra/base.rb:739:in `dispatch!'
    /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/sinatra-1.1.0/lib/sinatra/base.rb:530:in `block'
    /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/sinatra-1.1.0/lib/sinatra/base.rb:706:in `block'
    /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/sinatra-1.1.0/lib/sinatra/base.rb:706:in `invoke'
    /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/sinatra-1.1.0/lib/sinatra/base.rb:523:in `call!:'
    /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/rack-1.2.1/lib/rack/showexceptions.rb:24:in `call:'
    /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/sinatra-1.1.0/lib/sinatra/base.rb:1142:in `block'
    /Users/jpoz/.rvm/gems/macruby-0.7.1/gems/sinatra-1.1.0/lib/sinatra/base.rb:1142:in `call:'


问:
Self join tree MYSQL
Here is my categories table

```<code>category_id | parent_id
 ____________________________
       27   |       25
       28   |       27
       29   |       25
       26   |       28
       25   |        0
       30   |        0
       31   |       26
    ..........
    ..........
</code>```

I want to show the records like this.

```<code>   category_id  | parent_id
 ____________________________
    25  |        0
    27  |       25
    28  |       27
    26  |       28
    31  |       26
    29  |       25
    30  |        0

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

I have seen lots of post on it but I find nothing for me.
Please let me know query for my categories table. Thanks.
Here are some links that i have looked already.
1:
enter link description here
2: enter link description here

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

CREATE TABLE my_table
(category_id INT NOT NULL
,parent_id INT NULL
);

INSERT INTO my_table VALUES
(27,25),
(28,27),
(29,25),
(26,28),
(25,NULL),
(30,NULL),
(31,26);

SELECT DISTINCT t1.*
  FROM my_table t1
  LEFT
  JOIN my_table t2
    ON t2.parent_id = t1.category_id
  LEFT
  JOIN my_table t3
    ON t3.parent_id = t2.category_id
  LEFT
  JOIN my_table t4
    ON t4.parent_id = t3.category_id
 ORDER
    BY t4.parent_id DESC
     , t3.parent_id DESC
     , t2.parent_id DESC
     , t1.parent_id DESC;

+-------------+-----------+
| category_id | parent_id |
+-------------+-----------+
|          25 |      NULL |
|          27 |        25 |
|          28 |        27 |
|          26 |        28 |
|          31 |        26 |
|          29 |        25 |
|          30 |      NULL |
+-------------+-----------+
</code>```

or something like that.

Because MySQL does not yet have native support for recursion†, this becomes a bit of mouthful, hence the popularity of alternative models, e.g. nested set...

```<code>DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(category_id INT NOT NULL
,lft INT NOT NULL
,rgt INT NOT NULL
);

INSERT INTO my_table VALUES
(0,1,16),
(25,2,13),
(27,3,10),
(28,4,9),
(26,5,8),
(31,6,7),
(29,11,12),
(30,14,15);

SELECT * FROM my_table ORDER BY lft;
+-------------+-----+-----+
| category_id | lft | rgt |
+-------------+-----+-----+
|           0 |   1 |  16 |
|          25 |   2 |  13 |
|          27 |   3 |  10 |
|          28 |   4 |   9 |
|          26 |   5 |   8 |
|          31 |   6 |   7 |
|          29 |  11 |  12 |
|          30 |  14 |  15 |
+-------------+-----+-----+
</code>```

† MySQL 8.0 will add support for recursive CTE syntax.

Title: Self join tree MYSQL

Body:
Here is my categories table

category_id | parent_id
 ____________________________
       27   |       25
       28   |       27
       29   |       25
       26   |       28
       25   |        0
       30   |        0
       31   |       26
    ..........
    ..........

I want to show the records like this.

   category_id  | parent_id
 ____________________________
    25  |        0
    27  |       25
    28  |       27
    26  |       28
    31  |       26
    29  |       25
    30  |        0

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

I have seen lots of post on it but I find nothing for me.
Please let me know query for my categories table. Thanks.
Here are some links that i have looked already.
1:
enter link description here
2: enter link description here

Body:
DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(category_id INT NOT NULL
,parent_id INT NULL
);

INSERT INTO my_table VALUES
(27,25),
(28,27),
(29,25),
(26,28),
(25,NULL),
(30,NULL),
(31,26);

SELECT DISTINCT t1.*
  FROM my_table t1
  LEFT
  JOIN my_table t2
    ON t2.parent_id = t1.category_id
  LEFT
  JOIN my_table t3
    ON t3.parent_id = t2.category_id
  LEFT
  JOIN my_table t4
    ON t4.parent_id = t3.category_id
 ORDER
    BY t4.parent_id DESC
     , t3.parent_id DESC
     , t2.parent_id DESC
     , t1.parent_id DESC;

+-------------+-----------+
| category_id | parent_id |
+-------------+-----------+
|          25 |      NULL |
|          27 |        25 |
|          28 |        27 |
|          26 |        28 |
|          31 |        26 |
|          29 |        25 |
|          30 |      NULL |
+-------------+-----------+

or something like that.

Because MySQL does not yet have native support for recursion†, this becomes a bit of mouthful, hence the popularity of alternative models, e.g. nested set...

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(category_id INT NOT NULL
,lft INT NOT NULL
,rgt INT NOT NULL
);

INSERT INTO my_table VALUES
(0,1,16),
(25,2,13),
(27,3,10),
(28,4,9),
(26,5,8),
(31,6,7),
(29,11,12),
(30,14,15);

SELECT * FROM my_table ORDER BY lft;
+-------------+-----+-----+
| category_id | lft | rgt |
+-------------+-----+-----+
|           0 |   1 |  16 |
|          25 |   2 |  13 |
|          27 |   3 |  10 |
|          28 |   4 |   9 |
|          26 |   5 |   8 |
|          31 |   6 |   7 |
|          29 |  11 |  12 |
|          30 |  14 |  15 |
+-------------+-----+-----+

† MySQL 8.0 will add support for recursive CTE syntax.


问:
My android studio shows graphic on opening activity_main.xml
My android studio shows graphically editing instead of the written xml codes. The online curse that i am studying requires me to write the xml codes so please tell me how can i switch to text editing of the visual of my app.</p>

答: After open the xml file you can view two button one is TEXT other is DESIGN on the bottom of xml file . using TEXT button u can wright xml file .</p>


问:
How to reach the nested child elements of same name and formats
Please suggest, how to reach the inner mrow/mo contains braces.

In given samples, first level braces are converted prpoerly to 'MFENCED' when mrow (if its first and last child should be 'MO' with braces signs). But unable modify the second-level brackets, where those are also having 'MFRAC' as descendant. Template match should from 'MROW' (as given).

XML input:

```<code><article>
<body>
<math id="m1">
    <mrow>
      <mo>(</mo><!--first level braces open-->
        <mi>u</mi>
        <mo>+</mo>
        <mi>g</mi>
        <mi>=</mi>
        <mrow>
            <mo>(</mo><!--second level braces open-->
            <mfrac>
                <mrow><mn>1</mn></mrow>
                <mrow><mn>2</mn></mrow>
            </mfrac>
            <mo>)</mo><!--second level braces close-->
        </mrow>
      <mo>)</mo><!--first level braces close-->
    </mrow>
</math>

<math id="m2">
    <mrow>
        <mo>(</mo>
            <mrow>
                <mfrac>
                    <mn>8</mn>
                    <mn>9</mn>
                </mfrac>
            </mrow>
        <mo>)</mo>
    </mrow>
</math>
</body>
</article>
</code>```

XSLT 2.0:

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">

<xsl:template match="node()|@*">
    <xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
</xsl:template>

<xsl:template match="mrow[matches(child::*[1][name()='mo'], '^(\(|\[|\{)$')]
                            [matches(child::*[position()=last()][name()='mo'], '^(\)|\]|\})$')]">
    <xsl:choose>
        <xsl:when test="descendant::mfrac">
            <xsl:copy>
                <xsl:element name="mfenced">
                    <xsl:attribute name="open"><xsl:value-of select="child::*[1][name()='mo']"/></xsl:attribute>
                    <xsl:attribute name="close"><xsl:value-of select="child::*[position()=last()][name()='mo']"/></xsl:attribute>
                        <xsl:for-each select="*">
                            <xsl:if test="position()=1"/>
                            <xsl:if test="not(position()=1) and not(position()=last())">
                                <xsl:copy><xsl:apply-templates select="@* | node()"/></xsl:copy>
                            </xsl:if>
                            <xsl:if test="position()=last()"/>
                        </xsl:for-each>
                </xsl:element>
            </xsl:copy>
        </xsl:when>
        <xsl:otherwise>
            <xsl:copy><xsl:apply-templates select="@* | node()"/></xsl:copy>
        </xsl:otherwise>
        </xsl:choose>
</xsl:template>
</xsl:stylesheet>
</code>```

Required Result:

```<code><article>
<body>
<math id="m1">
    <mrow>
        <mfenced open="(" close=")"><mi>u</mi><mo>+</mo><mi>g</mi><mi>=</mi>
            <mrow>
            <mfenced open="(" close=")"><!-- this node or modification required, because, within this MFRAC presents, then it should convert to 'MFENCED' -->
                <mfrac>
                    <mrow><mn>1</mn></mrow>
                    <mrow><mn>2</mn></mrow>
                </mfrac>
            </mfenced>
            </mrow>
        </mfenced>
    </mrow>
</math>

<math id="m2">
    <mrow>
        <mfenced open="(" close=")">
            <mrow>
                <mfrac>
                    <mn>8</mn>
                    <mn>9</mn>
                </mfrac>
            </mrow>
        </mfenced>
    </mrow>
</math>
</body>
</article>
</code>```

答:
I think you can use xsl:for-each-group group-starting-with/group-ending-with as follows:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">

    <xsl:output indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="mrow[mo = '(']">
        <xsl:copy>
            <xsl:for-each-group select="*" group-starting-with="mo[. = '(']">
                <xsl:choose>
                    <xsl:when test="self::mo[. =  '(']">
                        <xsl:for-each-group select="current-group() except ." group-ending-with="mo[. = ')']">
                            <xsl:choose>
                                <xsl:when test="current-group()[last()][self::mo[. = ')']]">
                                    <mfenced open="(" close=")">
                                        <xsl:apply-templates select="current-group()[not(position() eq last())]"/>
                                    </mfenced>
                                </xsl:when>
                                <xsl:otherwise>
                                    <xsl:apply-templates select="current-group()"/>
                                </xsl:otherwise>
                            </xsl:choose>
                        </xsl:for-each-group>
                    </xsl:when>
                    <xsl:otherwise>
                        <xsl:apply-templates select="current-group()"/>
                    </xsl:otherwise>
                </xsl:choose>
            </xsl:for-each-group>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>
</code>```

That gives

```<code><?xml version="1.0" encoding="UTF-8"?>
<article>
   <body>
      <math id="m1">
         <mrow>
            <mfenced open="(" close=")">
               <mi>u</mi>
               <mo>+</mo>
               <mi>g</mi>
               <mi>=</mi>
               <mrow>
                  <mfenced open="(" close=")">
                     <mfrac>
                        <mrow>
                           <mn>1</mn>
                        </mrow>
                        <mrow>
                           <mn>2</mn>
                        </mrow>
                     </mfrac>
                  </mfenced>
               </mrow>
            </mfenced>
         </mrow>
      </math>
      <math id="m2">
         <mrow>
            <mfenced open="(" close=")">
               <mrow>
                  <mfrac>
                     <mn>8</mn>
                     <mn>9</mn>
                  </mfrac>
               </mrow>
            </mfenced>
         </mrow>
      </math>
   </body>
</article>
</code>```

Body:
Please suggest, how to reach the inner mrow/mo contains braces.

In given samples, first level braces are converted prpoerly to 'MFENCED' when mrow (if its first and last child should be 'MO' with braces signs). But unable modify the second-level brackets, where those are also having 'MFRAC' as descendant. Template match should from 'MROW' (as given).

XML input:

<math id="m1">
    <mrow>
      <mo>(</mo>
        <mi>u</mi>
        <mo>+</mo>
        <mi>g</mi>
        <mi>=</mi>
        <mrow>
            <mo>(</mo>
            <mfrac>
                <mrow><mn>1</mn></mrow>
                <mrow><mn>2</mn></mrow>
            </mfrac>
            <mo>)</mo>
        </mrow>
      <mo>)</mo>
    </mrow>
</math>

<math id="m2">
    <mrow>
        <mo>(</mo>
            <mrow>
                <mfrac>
                    <mn>8</mn>
                    <mn>9</mn>
                </mfrac>
            </mrow>
        <mo>)</mo>
    </mrow>
</math>

XSLT 2.0:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">

<xsl:template match="node()|@*">
    <xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
</xsl:template>

<xsl:template match="mrow[matches(child::*[1][name()='mo'], '^(\(|\[|\{)$')]
                            [matches(child::*[position()=last()][name()='mo'], '^(\)|\]|\})$')]">
    <xsl:choose>
        <xsl:when test="descendant::mfrac">
            <xsl:copy>
                <xsl:element name="mfenced">
                    <xsl:attribute name="open"><xsl:value-of select="child::*[1][name()='mo']"/></xsl:attribute>
                    <xsl:attribute name="close"><xsl:value-of select="child::*[position()=last()][name()='mo']"/></xsl:attribute>
                        <xsl:for-each select="*">
                            <xsl:if test="position()=1"/>
                            <xsl:if test="not(position()=1) and not(position()=last())">
                                <xsl:copy><xsl:apply-templates select="@* | node()"/></xsl:copy>
                            </xsl:if>
                            <xsl:if test="position()=last()"/>
                        </xsl:for-each>
                </xsl:element>
            </xsl:copy>
        </xsl:when>
        <xsl:otherwise>
            <xsl:copy><xsl:apply-templates select="@* | node()"/></xsl:copy>
        </xsl:otherwise>
        </xsl:choose>
</xsl:template>
</xsl:stylesheet>

Required Result:

<math id="m1">
    <mrow>
        <mfenced open="(" close=")"><mi>u</mi><mo>+</mo><mi>g</mi><mi>=</mi>
            <mrow>
            <mfenced open="(" close=")">
                <mfrac>
                    <mrow><mn>1</mn></mrow>
                    <mrow><mn>2</mn></mrow>
                </mfrac>
            </mfenced>
            </mrow>
        </mfenced>
    </mrow>
</math>

<math id="m2">
    <mrow>
        <mfenced open="(" close=")">
            <mrow>
                <mfrac>
                    <mn>8</mn>
                    <mn>9</mn>
                </mfrac>
            </mrow>
        </mfenced>
    </mrow>
</math>

Body:
I think you can use xsl:for-each-group group-starting-with/group-ending-with as follows:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">

    <xsl:output indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="mrow[mo = '(']">
        <xsl:copy>
            <xsl:for-each-group select="*" group-starting-with="mo[. = '(']">
                <xsl:choose>
                    <xsl:when test="self::mo[. =  '(']">
                        <xsl:for-each-group select="current-group() except ." group-ending-with="mo[. = ')']">
                            <xsl:choose>
                                <xsl:when test="current-group()[last()][self::mo[. = ')']]">
                                    <mfenced open="(" close=")">
                                        <xsl:apply-templates select="current-group()[not(position() eq last())]"/>
                                    </mfenced>
                                </xsl:when>
                                <xsl:otherwise>
                                    <xsl:apply-templates select="current-group()"/>
                                </xsl:otherwise>
                            </xsl:choose>
                        </xsl:for-each-group>
                    </xsl:when>
                    <xsl:otherwise>
                        <xsl:apply-templates select="current-group()"/>
                    </xsl:otherwise>
                </xsl:choose>
            </xsl:for-each-group>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

That gives

<?xml version="1.0" encoding="UTF-8"?>
<article>
   <body>
      <math id="m1">
         <mrow>
            <mfenced open="(" close=")">
               <mi>u</mi>
               <mo>+</mo>
               <mi>g</mi>
               <mi>=</mi>
               <mrow>
                  <mfenced open="(" close=")">
                     <mfrac>
                        <mrow>
                           <mn>1</mn>
                        </mrow>
                        <mrow>
                           <mn>2</mn>
                        </mrow>
                     </mfrac>
                  </mfenced>
               </mrow>
            </mfenced>
         </mrow>
      </math>
      <math id="m2">
         <mrow>
            <mfenced open="(" close=")">
               <mrow>
                  <mfrac>
                     <mn>8</mn>
                     <mn>9</mn>
                  </mfrac>
               </mrow>
            </mfenced>
         </mrow>
      </math>
   </body>
</article>


问:
How to map an array object with key from different array set in javascript
I'm building a small application in VueJS where I'm getting a response in following format:

```<code>"meeting_summaries":[
    {
        "interaction_id":22,
        "nature":"1",
        "client_name":"Test Company 4",
    },
    {
        "interaction_id":22,
        "nature":"2",
        "client_name":"Test Company 5",
    }
]
</code>```

And I'm having a data set of nature as:

```<code>const nature = [
    {value: 1, label: "Demo 1"},
    {value: 2, label: "Demo 2"},
    {value: 3, label: "Demo 3"}
]
</code>```

I want to map my meeting_summaries with this data set were in meeting_summaries -> nature points to nature -> value so that my final output can look something like this:

```<code>"meeting_summaries":[
    {
        "interaction_id":22,
        "nature":"1",
        'nature_name": "Demo 1",
        "client_name":"Test Company 4",
    },
    {
        "interaction_id":22,
        "nature":"2",
        'nature_name": "Demo 2",
        "client_name":"Test Company 5",
    }
]
</code>```

答:
You can do Array.prototype.forEach() and add the nature_name property of the found element label:

const nature = [{value: 1, label: "Demo 1"},{value: 2, label: "Demo 2"},{value: 3, label: "Demo 3"}];
const obj = {meeting_summaries: [{"interaction_id":22,"nature":"1","client_name":"Test Company 4",},{"interaction_id":22,"nature":"2","client_name":"Test Company 5"}]};

obj.meeting_summaries.forEach(el => el.nature_name = nature.find(n => n.value == el.nature).label);

console.log(obj);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I'm building a small application in VueJS where I'm getting a response in following format:

"meeting_summaries":[
    {
        "interaction_id":22,
        "nature":"1",
        "client_name":"Test Company 4",
    },
    {
        "interaction_id":22,
        "nature":"2",
        "client_name":"Test Company 5",
    }
]

And I'm having a data set of nature as:

const nature = [
    {value: 1, label: "Demo 1"},
    {value: 2, label: "Demo 2"},
    {value: 3, label: "Demo 3"}
]

I want to map my meeting_summaries with this data set were in meeting_summaries -> nature points to nature -> value so that my final output can look something like this:

"meeting_summaries":[
    {
        "interaction_id":22,
        "nature":"1",
        'nature_name": "Demo 1",
        "client_name":"Test Company 4",
    },
    {
        "interaction_id":22,
        "nature":"2",
        'nature_name": "Demo 2",
        "client_name":"Test Company 5",
    }
]

Body:
You can do Array.prototype.forEach() and add the nature_name property of the found element label:

const nature = [{value: 1, label: "Demo 1"},{value: 2, label: "Demo 2"},{value: 3, label: "Demo 3"}];
const obj = {meeting_summaries: [{"interaction_id":22,"nature":"1","client_name":"Test Company 4",},{"interaction_id":22,"nature":"2","client_name":"Test Company 5"}]};

obj.meeting_summaries.forEach(el => el.nature_name = nature.find(n => n.value == el.nature).label);

console.log(obj);

.as-console-wrapper { max-height: 100% !important; top: 0; }


答:
Just map through array an add your property using Object.assing and Array.prototype.find:

const a = {
 "meeting_summaries":[
    {
        "id":1,
        "company_id":7,
        "interaction_id":22,
        "nature":"1",
        "user_id":1,
        "action":"Action Test 1",
        "feedback":"Comment Test 1",
        "created_at":"2017-06-04 10:15:02",
        "updated_at":"2017-06-04 10:15:02",
        "deleted_at":null,
        "client_name":"Test Company 4",
        "mention_name":"Analyst"
    },
    {
        "id":2,
        "company_id":8,
        "interaction_id":22,
        "nature":"2",
        "user_id":1,
        "action":"Action Test 2",
        "feedback":"Comment Test 2",
        "created_at":"2017-06-04 10:15:02",
        "updated_at":"2017-06-04 10:15:02",
        "deleted_at":null,
        "client_name":"Test Company 5","mention_name":"Analyst"
    }
  ]
};

const nature = [
    {value: 1, label: "Demo 1"},
    {value: 2, label: "Demo 2"},
    {value: 3, label: "Demo 3"},
    {value: 4, label: "Demo 4"},
    {value: 5, label: "Demo 5"}
]

const res = a.meeting_summaries.map(ms => Object.assign(ms,
  (nature.find(n => n.value == ms.nature)) // if corresponding object exists
    ? { nature_name: nature.find(n => n.value == ms.nature).label } : {}
))

console.log(res)```

Title: How to map an array object with key from different array set in javascript


答:
You can use overrides to specify how missing dates are handled. For example:

```<code>=BDH(name_of_commod,"PX_LAST","19/12/2015","2/5/2017","Days=W,Fill=N")
</code>```

will have one datapoint for each workday and if no data was available for a date will leave the "price" cell blank.

The possible values are for Days are:

N, W or Weekdays - All weekdays

C, A or All - All calendar days

T, Trading- Omits all non-trading days.

and for Fill:

C, P, or Previous - Carries over the last available data.

N, E, or Error - Returns an error message.

B or Blank - Returns a blank.

NA - Excel is not available

PNA - Previous value and Excel is #N/A when the previous value is not available

Any other value the client enters will be used literally as a filler.

You can find a more exhaustive list of valid overrides in the help for the function. (In Excel, go to the cell with the formula and click "More Functions..." and "Help on this function")

Title: Bloomberg drawing out multiple securities

Body:
The Bloomberg excel formumla =BDH() only retrieves the prices for 1 security. If I want to get other securities, I'll need to repeat the formula which is no issue as I've written a script for that.

The problem comes when the dates of the securities doesn't match up, either due to trading days or contract expiry.

E.g. =BDH(name_of_commod,"PX_LAST","19/12/2015","2/5/2017") for two separate tickers produces:

QWV8 Comdty         QWZ8 Comdty
#NAME?      495.2   #NAME?      479.7
14/2/2017   496.7   18/4/2017   462.2
15/2/2017   494.4   19/4/2017   457.1
16/2/2017   495.3   20/4/2017   456.6
17/2/2017   495     21/4/2017   457
20/2/2017   498.7   24/4/2017   454.9
21/2/2017   498.4   25/4/2017   453.5
22/2/2017   498.1   26/4/2017   445
23/2/2017   491.6   27/4/2017   439.9
24/2/2017   489.5   28/4/2017   450
27/2/2017   481.6   2/5/2017    448.4

The mismatch here is due to that QWZ8 is not available till 18th Apr, which kind of screws over my calculations as I've got about a hundred other securities in the data set.

Is there a way to output bloomberg data such that all the dates align to the same row?

Like such:

    QWV8 Comdty         QWZ8 Comdty
18/4/2017   461.3   18/4/2017   462.2
19/4/2017   456.2   19/4/2017   457.1
20/4/2017   455.7   20/4/2017   456.6
21/4/2017   456.1   21/4/2017   457
24/4/2017   454     24/4/2017   454.9
25/4/2017   452.6   25/4/2017   453.5
26/4/2017   444     26/4/2017   445
27/4/2017   438.9   27/4/2017   439.9
28/4/2017   449     28/4/2017   450
2/5/2017    447.4   2/5/2017    448.4

Body:
You can use overrides to specify how missing dates are handled. For example:

=BDH(name_of_commod,"PX_LAST","19/12/2015","2/5/2017","Days=W,Fill=N")

will have one datapoint for each workday and if no data was available for a date will leave the "price" cell blank.

The possible values are for Days are:

N, W or Weekdays - All weekdays

C, A or All - All calendar days

T, Trading- Omits all non-trading days.

and for Fill:

C, P, or Previous - Carries over the last available data.

N, E, or Error - Returns an error message.

B or Blank - Returns a blank.

NA - Excel is not available

PNA - Previous value and Excel is #N/A when the previous value is not available

Any other value the client enters will be used literally as a filler.

You can find a more exhaustive list of valid overrides in the help for the function. (In Excel, go to the cell with the formula and click "More Functions..." and "Help on this function")


问:
Adding The Date and Time to the File name
Hello I am trying to add the date and time to a file name in JAVA. I can get the date and time printed within the file, which I also want done, but when I place the toString in the FileWriter I get a Null Pointer. </p>

```<code>package com.mkyong;
import java.util.*;
import java.io.*;
import java.*;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

    public class Simplex {

        private static PrintWriter outFile;

        //Main Method
        public static void main(String[] args) throws IOException {

            // Instantiate a Date object
             Date date = new Date();

             // display time and date using toString()
             outFile.println(date.toString());
             outFile.println();
            //creates the new file to be saved

            outFile = new PrintWriter(new FileWriter("simplex" + (date.toString()) + ".txt"));
</code>```

答:
The below mentioned snippet can be used</p>

```<code> String logFileName = new SimpleDateFormat("yyyyMMddHHmm'.txt'").format(new Date());

 logFileName = "loggerFile_" + logFileName;
</code>```

Body:
Hello I am trying to add the date and time to a file name in JAVA. I can get the date and time printed within the file, which I also want done, but when I place the toString in the FileWriter I get a Null Pointer.

package com.mkyong;
import java.util.*;
import java.io.*;
import java.*;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

    public class Simplex {

        private static PrintWriter outFile;

        //Main Method
        public static void main(String[] args) throws IOException {

            // Instantiate a Date object
             Date date = new Date();

             // display time and date using toString()
             outFile.println(date.toString());
             outFile.println();
            //creates the new file to be saved

            outFile = new PrintWriter(new FileWriter("simplex" + (date.toString()) + ".txt"));

Body:
The below mentioned snippet can be used

 String logFileName = new SimpleDateFormat("yyyyMMddHHmm'.txt'").format(new Date());

 logFileName = "loggerFile_" + logFileName;


答:
You didn't provide full context, but let's assume that "meeting_summaries" is variable:

var meeting_summaries = [{
    "interaction_id": 22,
    "nature": "1",
    "client_name": "Test Company 4",
  },
  {
    "interaction_id": 22,
    "nature": "2",
    "client_name": "Test Company 5",
    "mention_name": "Analyst"
  }
]

const nature = [
  { value: 1, label: "Demo 1" },
  { value: 2, label: "Demo 2" },
  { value: 3, label: "Demo 3" }
]

var meeting_summaries = meeting_summaries.map(ms => {
  ms.nature_name = nature.find(n => ms.nature == n.value).label;
  return ms
})
console.log(meeting_summaries)```


问:
How to extract string from complex string?
My start string is:

```<code>$grp = DL-Test1-Test2-RW"
</code>```

My goal is to have

```<code>$grp = "Test1\Test2"
</code>```

So i need to keep string between first and last "-" character. And replace - by \

UPDATED
I tried this:

```<code>$grp = "DL-test1-test2-RW"
$Descritpion = $grp.Split("-") #Split - to have an array
$Descritpion = $Descritpion.Split($Descritpion[0]) #Cut first element
$Descritpion = $Descritpion.Split($Descritpion[-1]) # Cut last element
#Here replace ?
Write-Host "Description:"$Descritpion
</code>```

答:
You can also do it with regex

```<code>$grp = "DL-Test1-Test2-RW"
$regex = "-(.*)-(.*)-"
if ($grp -match $regex){
    $Matches[1] + "\" + $Matches[2]
}
</code>```

If your string can have more groups between start and end, try this

```<code>$grp = "DL-Test1-Test2-Test3-Test4-RW"
$regex = "-(.*-){1,999}(.*)-"
if ($grp -match $regex){
    $Matches[1].replace('-','\') + $matches[2]
}
</code>```

Body:
My start string is:

$grp = DL-Test1-Test2-RW"

My goal is to have

$grp = "Test1\Test2"

So i need to keep string between first and last "-" character. And replace - by \

UPDATED
I tried this:

$grp = "DL-test1-test2-RW"
$Descritpion = $grp.Split("-") #Split - to have an array
$Descritpion = $Descritpion.Split($Descritpion[0]) #Cut first element
$Descritpion = $Descritpion.Split($Descritpion[-1]) # Cut last element
#Here replace ?
Write-Host "Description:"$Descritpion

Body:
You can also do it with regex

$grp = "DL-Test1-Test2-RW"
$regex = "-(.*)-(.*)-"
if ($grp -match $regex){
    $Matches[1] + "\" + $Matches[2]
}

If your string can have more groups between start and end, try this

$grp = "DL-Test1-Test2-Test3-Test4-RW"
$regex = "-(.*-){1,999}(.*)-"
if ($grp -match $regex){
    $Matches[1].replace('-','\') + $matches[2]
}


问:
Is there a JQuery plugin for displaying default text in a text field?
When I hit the page, the text box says "Search...", in gray font.

Then, I click the textbox.  Then, the "search..." disappears. And I can type.

答:
This is typically called "default text" and yes, there's a plugin for it.

JQuery Default Text Plugin

I've tried rolling my own default text plugin before but there were a lot of edge cases to contend with.  For example, the plugin must know what its default text is in order to clear said default text if the text field is left "blank", otherwise the form will try to submit that default text.  Basically, what I'm saying is use the plugin as it should cover these edge cases for you.


问:
Why isn't arr[-2] equivalent to -2[arr]?
```<code>#include <iostream>
using namespace std;

int main()
{
    int arr[3] = { 10, 20, 30 };
    cout << arr[-2] << endl;
    cout << -2[arr] << endl;
    return 0;
}
</code>```

Output:

```<code>4196160
-30
</code>```

Here arr[-2] is out of range and invalid, causing undefined behavior.
But -2[arr] evaluates to -30. Why?

Isn't arr[-2] equivalent to -2[arr]?

答:
The compiler parses this expression

```<code>-2
</code>```

like

```<code>unary_minus decimal_integer_literal
</code>```

That is definitions of integer literals do not include signs.

In turn the expression

```<code>2[arr]
</code>```

is parsed by the compiler as a postfix expression.

Postfix expressions have higher precedence than unary expressions. Thus this expression

```<code>-2[arr]
</code>```

is equivalent to

```<code>- ( 2[arr] )
</code>```

So the unary minus is applied to the lvalue returned by the postfix expression 2[arr].

On the other hand if you wrote

```<code>int n = -2;
</code>```

and then

```<code>n[arr]
</code>```

then this expression would be equivalent to

```<code>arr[-2]
</code>```

Body:
#include <iostream>
using namespace std;

int main()
{
    int arr[3] = { 10, 20, 30 };
    cout << arr[-2] << endl;
    cout << -2[arr] << endl;
    return 0;
}

Output:

4196160
-30

Here arr[-2] is out of range and invalid, causing undefined behavior.
But -2[arr] evaluates to -30. Why?

Isn't arr[-2] equivalent to -2[arr]?

Body:
The compiler parses this expression

-2

like

unary_minus decimal_integer_literal

That is definitions of integer literals do not include signs.

In turn the expression

2[arr]

is parsed by the compiler as a postfix expression.

Postfix expressions have higher precedence than unary expressions. Thus this expression

-2[arr]

is equivalent to

- ( 2[arr] )

So the unary minus is applied to the lvalue returned by the postfix expression 2[arr].

On the other hand if you wrote

int n = -2;

and then

n[arr]

then this expression would be equivalent to

arr[-2]


问:
giving ftp user a random password
So I'm trying to create a new ftp user and directory and give him only permissions for that directory. But the problem is when setting a password for created user. It creates user but i get this when i try to set a password for him

Creating home directory /home/kwgazl69' ... Copying files from/etc/skel' ... Enter new UNIX password: passwd: user 'test123' does not exist

What am i doing wrong ? Here is the code

```<code>$src = $request->path;
$dest = "/home/$randomNum/serverFiles";

echo $ssh->exec("adduser --force-badname $randomNum");
echo $ssh->exec("passwd test123");

echo $ssh->exec("cp -r $src $dest");
echo $ssh->exec("usermod -d $dest $randomNum");

echo $ssh->exec("cd $dest && ./samp03svr");

$ssh->disconnect();
</code>```

Adding user ln2i78yt' ... Adding new groupln2i78yt' (1010) ... Adding new user ln2i78yt' (1010) with groupln2i78yt' ... Creating home directory /home/ln2i78yt' ... Copying files from/etc/skel' ... Enter new UNIX password: passwd: unrecognized option '--stdin' Usage: passwd [options] [LOGIN] Options: -a, --all report password status on all accounts -d, --delete delete the password for the named account -e, --expire force expire the password for the named account -h, --help display this help message and exit -k, --keep-tokens change password only if expired -i, --inactive INACTIVE set password inactive after expiration to INACTIVE -l, --lock lock the password of the named account -n, --mindays MIN_DAYS set minimum number of days before password change to MIN_DAYS -q, --quiet quiet mode -r, --repository REPOSITORY change password in REPOSITORY repository -R, --root CHROOT_DIR directory to chroot into -S, --status report password status on the named account -u, --unlock unlock the password of the named account -w, --warndays WARN_DAYS set expiration warning days to WARN_DAYS -x, --maxdays MAX_DAYS set maximum number of days before password change to MAX_DAYS

答:
You're actually trying to change the password for user 'test123', rather than set the password to 'test123'.

You need to pass the password into stdin, so do:

```<code>echo $ssh->exec('echo -e "test123\ntest123" | passwd ' . $randomNum);
</code>```

Title: giving ftp user a random password

Body:
So I'm trying to create a new ftp user and directory and give him only permissions for that directory. But the problem is when setting a password for created user. It creates user but i get this when i try to set a password for him

Creating home directory /home/kwgazl69' ... Copying files from/etc/skel' ... Enter new UNIX password: passwd: user 'test123' does not exist

What am i doing wrong ? Here is the code

$src = $request->path;
$dest = "/home/$randomNum/serverFiles";

echo $ssh->exec("adduser --force-badname $randomNum");
echo $ssh->exec("passwd test123");

echo $ssh->exec("cp -r $src $dest");
echo $ssh->exec("usermod -d $dest $randomNum");

echo $ssh->exec("cd $dest && ./samp03svr");

$ssh->disconnect();

Adding user ln2i78yt' ... Adding new groupln2i78yt' (1010) ... Adding new user ln2i78yt' (1010) with groupln2i78yt' ... Creating home directory /home/ln2i78yt' ... Copying files from/etc/skel' ... Enter new UNIX password: passwd: unrecognized option '--stdin' Usage: passwd [options] [LOGIN] Options: -a, --all report password status on all accounts -d, --delete delete the password for the named account -e, --expire force expire the password for the named account -h, --help display this help message and exit -k, --keep-tokens change password only if expired -i, --inactive INACTIVE set password inactive after expiration to INACTIVE -l, --lock lock the password of the named account -n, --mindays MIN_DAYS set minimum number of days before password change to MIN_DAYS -q, --quiet quiet mode -r, --repository REPOSITORY change password in REPOSITORY repository -R, --root CHROOT_DIR directory to chroot into -S, --status report password status on the named account -u, --unlock unlock the password of the named account -w, --warndays WARN_DAYS set expiration warning days to WARN_DAYS -x, --maxdays MAX_DAYS set maximum number of days before password change to MAX_DAYS

Body:
You're actually trying to change the password for user 'test123', rather than set the password to 'test123'.

You need to pass the password into stdin, so do:

echo $ssh->exec('echo -e "test123\ntest123" | passwd ' . $randomNum);


问:
How to access instance variable in static companion object in Kotlin
I am trying to make utils for performing network operations in kotlin. I have below code where the primary constructor is taking Command and Context.

I am unable to access command variable in command.execute(JSONObject(jsonObj)), getting below error. I am not sure what is causing an issue?

Unresolved reference: command

```<code>class AsyncService(val command: Command, val context: Context) {

    companion object {
        fun doGet(request: String) {
            doAsync {
                val jsonObj = java.net.URL(request).readText()
                command.execute(JSONObject(jsonObj))
            }
        }
    }
}
</code>```

答:
You should pass arguments directly to your companion object function:</p>

```<code>class AsyncService {

    companion object {
        fun doGet(command: Command, context: Context, request: String) {
            doAsync {
                val jsonObj = java.net.URL(request).readText()
                command.execute(JSONObject(jsonObj))
            }
        }
    }
}
</code>```

Body:
I am trying to make utils for performing network operations in kotlin. I have below code where the primary constructor is taking Command and Context.

I am unable to access command variable in command.execute(JSONObject(jsonObj)), getting below error. I am not sure what is causing an issue?

Unresolved reference: command

class AsyncService(val command: Command, val context: Context) {

    companion object {
        fun doGet(request: String) {
            doAsync {
                val jsonObj = java.net.URL(request).readText()
                command.execute(JSONObject(jsonObj))
            }
        }
    }
}

Body:
You should pass arguments directly to your companion object function:

class AsyncService {

    companion object {
        fun doGet(command: Command, context: Context, request: String) {
            doAsync {
                val jsonObj = java.net.URL(request).readText()
                command.execute(JSONObject(jsonObj))
            }
        }
    }
}


问:
How can a class be imported in swift code based on the ios version at compile time (without setting flags in Xcode or using weak linking)?
Based on the ios version, I want to import a particular class into my class. I have to do this purely through code only (Xcode and any other manual setting will not work in my situation). Any pointers on how this can be done?

For example

```<code>#import classA

//code to ensure if ios version > 3.0 then import classB

public class myClass{
...
}
</code>```

答:
It cannot be done. What is imported has to be determined at compile time, because importing is a compile-time action. The iOS version is unknown until runtime. At compile time you only know the deployment target and the SDK version.

I'd recommend using the usual Swift availability-checks (Apple docs) and weak linking where necessary. Or you could raise the deployment target, if that's an option. Or you find a library that solves the problem even for the lower iOS version.

Body:
Based on the ios version, I want to import a particular class into my class. I have to do this purely through code only (Xcode and any other manual setting will not work in my situation). Any pointers on how this can be done?

For example

#import classA

//code to ensure if ios version > 3.0 then import classB

public class myClass{
...
}


问:
List files in exited container
Is there an easy way to check what files were produced after container exits?

I saw recommendations to rewrite Dockerfile and add ls commands to it, but that's not the easy way for me.

UPDATE: I was using VOLUME directive inside Dockerfile and docker diff doesn't show changes there.

答:
You can use docker diff container_name. This inspect changes to files or directories on a container filesystem.

It shows something like this.

```<code>A /usr/local/lib/python2.7/email
C /usr/local/lib/python2.7/email/mime
D /usr/local/lib/python2.7/email/mime/audio.pyc
</code>```

A: A file or directory was added

C: A file or directory was changed

D: A file or directory was deleted

Hope this helps, good luck!

Title: List files in exited container

Body:
You can use docker diff container_name. This inspect changes to files or directories on a container filesystem.

It shows something like this.

A /usr/local/lib/python2.7/email
C /usr/local/lib/python2.7/email/mime
D /usr/local/lib/python2.7/email/mime/audio.pyc

A: A file or directory was added

C: A file or directory was changed

D: A file or directory was deleted

Hope this helps, good luck!


问:
Link within label in Swift
I would like to do that in my app :

The label is like : username comment

I don't know how to add the "button" within the label; I found this library but I'm not sure it will work? https://github.com/optonaut/ActiveLabel.swift

Maybe use it by creating a regex for the first word? What do you think?

答:
For such a case, instead of adding it as a UILabel component, I would rather use UITextView, because it has dataDetectorTypes property:

The types of data converted to tappable URLs in the text view.

You can use this property to specify the types of data (phone numbers,
  http links, and so on) that should be automatically converted to URLs
  in the text view. When tapped, the text view opens the application
  responsible for handling the URL type and passes it the URL. Note that
  data detection does not occur if the text view's isEditable property
  is set to true.

So, you can implement it as:

```<code>// as mentioned in the documentation, make sure to let it be uneditable:
textView.isEditable = false
textView.dataDetectorTypes = .link
</code>```

For your case, I assume that it shall be .link. I would also suggest to check the other options for the UIDataDetectorTypes.

Title: Link within label in Swift

Body:
For such a case, instead of adding it as a UILabel component, I would rather use UITextView, because it has dataDetectorTypes property:

The types of data converted to tappable URLs in the text view.

You can use this property to specify the types of data (phone numbers,
  http links, and so on) that should be automatically converted to URLs
  in the text view. When tapped, the text view opens the application
  responsible for handling the URL type and passes it the URL. Note that
  data detection does not occur if the text view's isEditable property
  is set to true.

So, you can implement it as:

// as mentioned in the documentation, make sure to let it be uneditable:
textView.isEditable = false
textView.dataDetectorTypes = .link

For your case, I assume that it shall be .link. I would also suggest to check the other options for the UIDataDetectorTypes.


问:
String.Format() to add commas in thousands place for a number not working
String.Format to add commas in thousands place just add space without comma.

I tried:

```<code> var total = string.Format("{0:n0}", 12345);
 // expect: total = 12,345
 // actual: total = 12 345
</code>```

Anything I'm missing?

答:
This is a culture thing. In your locale, space is the thousands specifier, apparently. I see commas. To see a specific locale's output, specify that explicitly. A very common option is "invariant":

```<code>var total = string.Format(CultureInfo.InvariantCulture, "{0:n0}", 12345);
</code>```

Body:
String.Format to add commas in thousands place just add space without comma.

I tried:

 var total = string.Format("{0:n0}", 12345);
 // expect: total = 12,345
 // actual: total = 12 345

Anything I'm missing?

Body:
This is a culture thing. In your locale, space is the thousands specifier, apparently. I see commas. To see a specific locale's output, specify that explicitly. A very common option is "invariant":

var total = string.Format(CultureInfo.InvariantCulture, "{0:n0}", 12345);


问:
bootstrap datetimepicker not working in DIV class
I am trying to put in a bootstrap datetimepicker in my customized table. But it just won't work. i understood that you can't placed a script in th, so i placed it in td, but it's still not working.

Simple and working datepicker.

```<code><tr>
<td>Date</td>
<td><!-- mktime(hour, minute, second, month, day, year) -->
<input type="text" name="call_date" value="<?php echo $adjdate;?>" id="datepicker" class="input-small">
</td>
</tr>
</code>```

When i tried to implement bootstrap date time picker, it just won't work. I think i've misplaced something in the code below here.

```<code><tr>
<td>Date</td>
<td>
<div class="container">
<div class="row">
    <div class='col-sm-6'>
        <div class="form-group">
            <div class='input-group date' id='datetimepicker1'>
                <input type='text' class="form-control" />
                <span class="input-group-addon">
                    <span class="glyphicon glyphicon-calendar"></span>
                </span>
            </div>
        </div>
    </div>
    <script type="text/javascript">
        $(function () {
            $('#datetimepicker1').datetimepicker();
        });
    </script>
</div>
</div>
</td>
</tr>
</code>```

Additional info:
i forgot to mention that i've added in

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
</code>```

But if i placed code outside instead of putting inside td, it will work

```<code><div class="container">
<div class="row">
   <div class='col-sm-6'>
    <div class="form-group">
        <div class='input-group date' id='datetimepicker1'>
            <input type='text' class="form-control" />
            <span class="input-group-addon">
                <span class="glyphicon glyphicon-calendar"></span>
            </span>
        </div>
    </div>
</div>
<script type="text/javascript">
    $(function () {
        $('#datetimepicker1').datetimepicker();
    });
</script>
</code>```

I just need advice regarding this, and thanks for showing me those examples, it helps a lot, thank you

答:
Load Jquery ,moment.js before datetimepicker.

$(function () {
        $('#datetimepicker1').datetimepicker();
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<tr>
<td>Date</td>
<td>
<div class="container">
<div class="row">
    <div class='col-sm-6'>
        <div class="form-group">
            <div class='input-group date' id='datetimepicker1'>
                <input type='text' class="form-control" />
                <span class="input-group-addon">
                    <span class="glyphicon glyphicon-calendar"></span>
                </span>
            </div>
        </div>
    </div>

</div>
</div>
</td>
</tr></code>```

Body:
I am trying to put in a bootstrap datetimepicker in my customized table. But it just won't work. i understood that you can't placed a script in th, so i placed it in td, but it's still not working.

Simple and working datepicker.

Date

<input type="text" name="call_date" value="<?php echo $adjdate;?>" id="datepicker" class="input-small">

When i tried to implement bootstrap date time picker, it just won't work. I think i've misplaced something in the code below here.

Date

                <input type='text' class="form-control" />

Additional info:
i forgot to mention that i've added in

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

But if i placed code outside instead of putting inside td, it will work

            <input type='text' class="form-control" />

I just need advice regarding this, and thanks for showing me those examples, it helps a lot, thank you

Body:
Load Jquery ,moment.js before datetimepicker.

$(function () {
        $('#datetimepicker1').datetimepicker();
  });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<tr>
<td>Date</td>
<td>
<div class="container">
<div class="row">
    <div class='col-sm-6'>
        <div class="form-group">
            <div class='input-group date' id='datetimepicker1'>
                <input type='text' class="form-control" />
                <span class="input-group-addon">
                    <span class="glyphicon glyphicon-calendar"></span>
                </span>
            </div>
        </div>
    </div>

</div>
</div>
</td>
</tr>


问:
Cutting value in vector by determine positions
Is there a function in R that I can cut a value in vector.

for example i got this vec:

```<code>40754831597
64278107602
64212163451
</code>```

and each vale in the vec i want to cut so from the number pos 3 to 6 for example and get a new vector look like this

```<code>7548
2781
2121
</code>```

and so on

答:
I don't really get why you would like to do this, but here you go:</p>

```<code># assuming it's a character vector
substring(vec,3,6)

# if it's numeric
substring(as.character(vec),3,6)

#output
#[1] "7548" "2781" "2121"
</code>```

Body:
Is there a function in R that I can cut a value in vector.

for example i got this vec:

40754831597
64278107602
64212163451

and each vale in the vec i want to cut so from the number pos 3 to 6 for example and get a new vector look like this

7548
2781
2121

and so on

Body:
I don't really get why you would like to do this, but here you go:

# assuming it's a character vector
substring(vec,3,6)

# if it's numeric
substring(as.character(vec),3,6)

#output
#[1] "7548" "2781" "2121"


问:
location href returns as undefined
I have this Ripple effect code:

```<code>(function (window, $) {

  $(function() {

    $('.ripple-white').on('click', function (event) {
      event.preventDefault();

      var $div = $('<div/>'),
          btnOffset = $(this).offset(),
            xPos = event.pageX - btnOffset.left,
            yPos = event.pageY - btnOffset.top;

      $div.addClass('ripple-effect');
      var $ripple = $(".ripple-effect");

      $ripple.css("height", $(this).height());
      $ripple.css("width", $(this).height());
      $div
        .css({
          top: yPos - ($ripple.height()/2),
          left: xPos - ($ripple.width()/2),
          background: $(this).data("ripple-color")
        })
        .appendTo($(this));

      window.setTimeout(function(){
        $div.remove();
        location.href = $(this).attr('href');
      }, 800);

    });

  });

})(window, jQuery);
</code>```

Which is dynamically used for Wordpress post listing:

```<code><?php $the_query = new WP_Query( 'posts_per_page=50' ); ?>
<?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?>
<div class="flex-3col"><a class="ripple-white" href="<?php the_permalink() ?>"><h3 class="single-menu"><?php the_title(); ?></h3></a></div>
<?php endwhile; wp_reset_postdata(); ?>
</code>```

For some reason I'm getting the location.href as UNDEFINED. I've also tried:

```<code>$('a', this).attr("href");
</code>```

Any advice what I'm doing wrong here?

答:
this doesn't refers to anchor in setTimeout, You can cache the output in a variable which can be used later.

```<code>var href = $(this).attr('href'); //Cached the output
window.setTimeout(function(){
  $div.remove();
  location.href = href ;
}, 800);
</code>```

Or, You can pass argument

```<code>window.setTimeout(function(href){
  $div.remove();
  location.href = href ;
}, 800, $(this).attr('href'));
</code>```

window.setTimeout(function(href) {
  console.log('href', href)
}, 800, window.location.href);```

Title: location href returns as undefined

Body:
I have this Ripple effect code:

(function (window, $) {

  $(function() {

    $('.ripple-white').on('click', function (event) {
      event.preventDefault();

      var $div = $('
'),
          btnOffset = $(this).offset(),
            xPos = event.pageX - btnOffset.left,
            yPos = event.pageY - btnOffset.top;

      $div.addClass('ripple-effect');
      var $ripple = $(".ripple-effect");

      $ripple.css("height", $(this).height());
      $ripple.css("width", $(this).height());
      $div
        .css({
          top: yPos - ($ripple.height()/2),
          left: xPos - ($ripple.width()/2),
          background: $(this).data("ripple-color")
        })
        .appendTo($(this));

      window.setTimeout(function(){
        $div.remove();
        location.href = $(this).attr('href');
      }, 800);

    });

  });

})(window, jQuery);

Which is dynamically used for Wordpress post listing:

<?php $the_query = new WP_Query( 'posts_per_page=50' ); ?>
<?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?>

<a class="ripple-white" href="<?php the_permalink() ?>">
<?php the_title(); ?>

<?php endwhile; wp_reset_postdata(); ?>

For some reason I'm getting the location.href as UNDEFINED. I've also tried:

$('a', this).attr("href");

Any advice what I'm doing wrong here?

Body:
this doesn't refers to anchor in setTimeout, You can cache the output in a variable which can be used later.

var href = $(this).attr('href'); //Cached the output
window.setTimeout(function(){
  $div.remove();
  location.href = href ;
}, 800);

Or, You can pass argument

window.setTimeout(function(href){
  $div.remove();
  location.href = href ;
}, 800, $(this).attr('href'));

window.setTimeout(function(href) {
  console.log('href', href)
}, 800, window.location.href);


问:
SPOJ Swift - NZEC
I have problem with SPOJ,
in all of my solution I had NZEC problem. I have read that is problem (non-zero exit code).

SPOJ link: http://www.spoj.com/problems/TEST/

And my code below:

```<code>for i in 1...100000{
    let number = Int(readLine()!)!

    if number != 42{
        print(number)
    }
    else
    {
        break
    }
}
</code>```

PS: In Xcode I have created command line project and in console I have information: Program ended with exit code: 0

That problem is in Swift.

答:
Here is the proper way of handling IO in the Spoj's TEST problem in Swift:

```<code>while let input = readLine(), Int(input) != 42 {
    if !input.isEmpty {
       print(input)
    } else {
       print("Input cannot be empty")
       continue
    }
}
</code>```

It reads IO data until there is something to read OR the number 42 appears in the input data.

This example is available as an example code for the Swift language on Ideone: http://ideone.com/samples#sample_lang_85. You can also see this code in action here: http://ideone.com/lH6iZS.

Title: SPOJ Swift - NZEC

Body:
I have problem with SPOJ,
in all of my solution I had NZEC problem. I have read that is problem (non-zero exit code).

SPOJ link: http://www.spoj.com/problems/TEST/

And my code below:

for i in 1...100000{
    let number = Int(readLine()!)!

    if number != 42{
        print(number)
    }
    else
    {
        break
    }
}

PS: In Xcode I have created command line project and in console I have information: Program ended with exit code: 0

That problem is in Swift.

Body:
Here is the proper way of handling IO in the Spoj's TEST problem in Swift:

while let input = readLine(), Int(input) != 42 {
    if !input.isEmpty {
       print(input)
    } else {
       print("Input cannot be empty")
       continue
    }
}

It reads IO data until there is something to read OR the number 42 appears in the input data.

This example is available as an example code for the Swift language on Ideone: http://ideone.com/samples#sample_lang_85. You can also see this code in action here: http://ideone.com/lH6iZS.


问:
What is a blade directive in Laravel?
In a blade template, you see @section, @content, @yield etc. What are blade directives? Are they comparable to PHP or HTML? There doesn't seem to be much explanation on Laravel syntax in the framework.</p>

答:
At a basic level Blade is a templating language that compiles down to PHP and HTML.

When you use @section, @content or @yield in a .blade template file it will be compiled down to PHP.

If you want to dive in exactly to how it works try looking through the tests in frameworks Github or taking a look at the API.

Title: What is a blade directive in Laravel?


问:
(Almost) adjacency postgres table that has mixed up relations
I have an (almost) adjacency list postgres table that uses relationships like so:

```<code> Id.A   Id.B
   1    4
   2    3
   1    5
   5    6
   7    8
   3    4
   5    7
</code>```

Giving:

```<code>    1
   / \
  5   4
 / \   \
6   7   3
     \   \
      8   2
</code>```

And I wish to find the node with the smallest value. It isn't necessarily the root, because that doesn't really exist. I need to somehow traverse the graph from any point and find the node with the smallest value. The problem is as things currently are, its not an adjacency table per say.

I am fairly sure this has to use a recursive CTE but dont quite know where to start.

And, as I think I may not have been too clear here, there are a bunch of these graphs all muddled up within the same table, not just one single graph, so for each row it would need to traverse its own graph to find its own smallest value node.

Any help would be much appreciated, thanks.

答:
The root nodes are the only nodes not showing up in id.b, so let's start from there recursively:

```<code>WITH RECURSIVE roots(root, child) AS (
      SELECT a, a FROM id
      EXCEPT
      SELECT b, b FROM id
   UNION ALL
      SELECT r.root, id.b
      FROM roots r
         JOIN id ON r.child = id.a
) SELECT root, child FROM roots;
</code>```

Body:
I have an (almost) adjacency list postgres table that uses relationships like so:

 Id.A   Id.B
   1    4
   2    3
   1    5
   5    6
   7    8
   3    4
   5    7

Giving:

    1
   / \
  5   4
 / \   \
6   7   3
     \   \
      8   2

And I wish to find the node with the smallest value. It isn't necessarily the root, because that doesn't really exist. I need to somehow traverse the graph from any point and find the node with the smallest value. The problem is as things currently are, its not an adjacency table per say.

I am fairly sure this has to use a recursive CTE but dont quite know where to start.

And, as I think I may not have been too clear here, there are a bunch of these graphs all muddled up within the same table, not just one single graph, so for each row it would need to traverse its own graph to find its own smallest value node.

Any help would be much appreciated, thanks.

Body:
The root nodes are the only nodes not showing up in id.b, so let's start from there recursively:

WITH RECURSIVE roots(root, child) AS (
      SELECT a, a FROM id
      EXCEPT
      SELECT b, b FROM id
   UNION ALL
      SELECT r.root, id.b
      FROM roots r
         JOIN id ON r.child = id.a
) SELECT root, child FROM roots;


问:
Error with ruby bundle install
When I try to running bundle install I see:

```<code>To see why this extension failed to compile, please check the mkmf.log which can
be found here:

C:/RailsInstaller/Ruby2.3.0/lib/ruby/gems/2.3.0/extensions/x86-
mingw32/2.3.0/nio4r-2.1.0/mkmf.log

extconf failed, exit code 1

Gem files will remain installed in
C:/RailsInstaller/Ruby2.3.0/lib/ruby/gems/2.3.0/gems/nio4r-2.1.0 for
inspection.
Results logged to
C:/RailsInstaller/Ruby2.3.0/lib/ruby/gems/2.3.0/extensions/x86-
mingw32/2.3.0/nio4r-2.1.0/gem_make.out

An error occurred while installing nio4r (2.1.0), and Bundler cannot continue.
Make sure that `gem install nio4r -v '2.1.0'` succeeds before bundling.
</code>```

I am using Windows 10, Ruby 2.3.3, Rails 5.0.2.

mkmf.log content is:

```<code>"gcc -o conftest.exe -IC:/RailsInstaller/Ruby2.3.0/include/ruby-2.3.0/i386-
mingw32 -IC:/RailsInstaller/Ruby2.3.0/include/ruby-2.3.0/ruby/backward -
IC:/RailsInstaller/Ruby2.3.0/include/ruby-2.3.0 -I. -DFD_SETSIZE=2048 -
D_WIN32_WINNT=0x0501 -D__MINGW_USE_VC2005_COMPAT -D_FILE_OFFSET_BITS=64   -
O3 -fno-omit-frame-pointer -fno-fast-math -g -Wall -Wextra -Wno-unused-
parameter -Wno-parentheses -Wno-long-long -Wno-missing-field-initializers -
Wunused-variable -Wpointer-arith -Wwrite-strings -Wdeclaration-after-
statement -Wimplicit-function-declaration -Wdeprecated-declarations -Wno-
packed-bitfield-compat conftest.c  -L. -LC:/RailsInstaller/Ruby2.3.0/lib -L.
-lmsvcrt-ruby230  -lshell32 -lws2_32 -liphlpapi -limagehlp -lshlwapi  "
</code>```

Checked program was:

```<code>#include "ruby.h"

#include <winsock2.h>
#include <windows.h>
int main(int argc, char **argv)
{
  return 0;
}
</code>```

答:
If other gems have same error (and it's initial bundle install), try to change in gemfile source 'https://rubygems.org' to source 'http://rubygems.org'.

I had this problem on windows in corporate network, and problem somewhere with ssl. That solution works for me, but i know, it isn't best solution.

But it's a bad recommendation, if any other gem installed with success.

Title: Error with ruby bundle install

Body:
When I try to running bundle install I see:

To see why this extension failed to compile, please check the mkmf.log which can
be found here:

C:/RailsInstaller/Ruby2.3.0/lib/ruby/gems/2.3.0/extensions/x86-
mingw32/2.3.0/nio4r-2.1.0/mkmf.log

extconf failed, exit code 1

Gem files will remain installed in
C:/RailsInstaller/Ruby2.3.0/lib/ruby/gems/2.3.0/gems/nio4r-2.1.0 for
inspection.
Results logged to
C:/RailsInstaller/Ruby2.3.0/lib/ruby/gems/2.3.0/extensions/x86-
mingw32/2.3.0/nio4r-2.1.0/gem_make.out

An error occurred while installing nio4r (2.1.0), and Bundler cannot continue.
Make sure that `gem install nio4r -v '2.1.0'` succeeds before bundling.

I am using Windows 10, Ruby 2.3.3, Rails 5.0.2.

mkmf.log content is:

"gcc -o conftest.exe -IC:/RailsInstaller/Ruby2.3.0/include/ruby-2.3.0/i386-
mingw32 -IC:/RailsInstaller/Ruby2.3.0/include/ruby-2.3.0/ruby/backward -
IC:/RailsInstaller/Ruby2.3.0/include/ruby-2.3.0 -I. -DFD_SETSIZE=2048 -
D_WIN32_WINNT=0x0501 -D__MINGW_USE_VC2005_COMPAT -D_FILE_OFFSET_BITS=64   -
O3 -fno-omit-frame-pointer -fno-fast-math -g -Wall -Wextra -Wno-unused-
parameter -Wno-parentheses -Wno-long-long -Wno-missing-field-initializers -
Wunused-variable -Wpointer-arith -Wwrite-strings -Wdeclaration-after-
statement -Wimplicit-function-declaration -Wdeprecated-declarations -Wno-
packed-bitfield-compat conftest.c  -L. -LC:/RailsInstaller/Ruby2.3.0/lib -L.
-lmsvcrt-ruby230  -lshell32 -lws2_32 -liphlpapi -limagehlp -lshlwapi  "

Checked program was:

#include "ruby.h"

#include <winsock2.h>
#include <windows.h>
int main(int argc, char **argv)
{
  return 0;
}