问:
How to use SQL Server to email an Excel workbook containing the results of a query
I need to send an email that has the results of a query formatted as an Excel spreadsheet using SQL Server.

For example, every Monday, run a query such as:

```<code>SELECT * FROM dbo.Table
</code>```

Save the results in an xlsx Excel workbook and email it.

答:
You have three choices:

Use SSIS to create the xlsx file and email it out.

Send a CSV File
as an attachment using sp_send_dbmail
(https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-send-dbmail-transact-sql)

Write a .Net based CLR procedure to create the xlsx file - for
example see this link where someone had issues and a solution with
this:
(Create an SQL CLR UDF with C#)

As it is, your question is way too broad for Stack Overflow and all of these solutions require not only a lot more input from yourself but will be subject to opinion as well.

Body:
I need to send an email that has the results of a query formatted as an Excel spreadsheet using SQL Server.

For example, every Monday, run a query such as:

SELECT * FROM dbo.Table

Save the results in an xlsx Excel workbook and email it.


来源: stackexchange

问:
Problem with jQuery ajax parameters
I'm sending a date to my webservice in this format: 12/14/2010 but the "/" character is causing the posted value to be something like 0.0323483238432834. How do I literally send the date in that format? Heres the ajax code I use:

```<code>function createNewPromo() {
            var a = $("#txtDateStart").val();
            var b = $("#txtDateEnd").val();
            $.ajax({
                type: "POST",
                url: "/WebService_VehicleDisplay.asmx/createNewPromo",
                data: "{startDate:" + a + "," + "endDate:" + b + "}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    var response = msg.d;

                },
                failure: function (msg) {
                    alert('failure');
                }
            });
        }
</code>```

Edit: here is what firebug says. endDate/startDate are my parameters.(this is what is being posted to my web service.).

```<code>    JSON

endDate
    0.00021321961620469082

startDate
    0.00028429282160625445
Source
{startDate:12/21/2010,endDate:12/28/2010}
</code>```

答:
I figured it out, there needs to be a single quote on each side of the parameter value like so:

```<code>data: "{startDate:'"+ a +"',endDate:'"+ b +"'}"
</code>```

I included a great article in my comment below about this issue. Here is a snippet from it:

"Again, remember that a Content-Type of application/json is a requirement when working with ASMX ScriptServices. By setting that Content-Type on the request, you’ve committed to sending JSON serialized parameters, and a URL encoded string is far from valid JSON."

ContentLicense: CC BY-SA 2.5

Title: Problem with jQuery ajax parameters

Body:
I'm sending a date to my webservice in this format: 12/14/2010 but the "/" character is causing the posted value to be something like 0.0323483238432834. How do I literally send the date in that format? Heres the ajax code I use:

function createNewPromo() {
            var a = $("#txtDateStart").val();
            var b = $("#txtDateEnd").val();
            $.ajax({
                type: "POST",
                url: "/WebService_VehicleDisplay.asmx/createNewPromo",
                data: "{startDate:" + a + "," + "endDate:" + b + "}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    var response = msg.d;

                },
                failure: function (msg) {
                    alert('failure');
                }
            });
        }

Edit: here is what firebug says. endDate/startDate are my parameters.(this is what is being posted to my web service.).

    JSON

endDate
    0.00021321961620469082

startDate
    0.00028429282160625445
Source
{startDate:12/21/2010,endDate:12/28/2010}

Body:
I figured it out, there needs to be a single quote on each side of the parameter value like so:

data: "{startDate:'"+ a +"',endDate:'"+ b +"'}"

I included a great article in my comment below about this issue. Here is a snippet from it:

"Again, remember that a Content-Type of application/json is a requirement when working with ASMX ScriptServices. By setting that Content-Type on the request, you’ve committed to sending JSON serialized parameters, and a URL encoded string is far from valid JSON."


问:
Login to the site through scrapy
I do an official video lesson authorization on the site.
If the username and password are incorrect, then the transition to the callback method is successful, if the login and password are correct, then the transition to the method is not feasible.
My code:
import scrapy

```<code>class QuotesSpider(scrapy.Spider):
    name = "quotes"
    start_urls = ["https://www.darkorbit.com"]

    def parse(self, response):
        login_url = response.css('form[name="bgcdw_login_form"]::attr(action)').extract_first()
        data = {
            'username': 'testscrapy',
            'password': 'testtest',
        }
        yield scrapy.FormRequest(url=login_url, formdata=data, callback=self.after_login)

    def after_login(self, response):
        print('----------------------------------------')
</code>```

With the correct input data, a log is obtained(Long fragments are cut):

```<code>2017-06-03 22:04:40 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.darkorbit.com/robots.txt> (referer: None)
2017-06-03 22:04:41 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.darkorbit.com> (referer: None)
2017-06-03 22:04:42 [scrapy.core.engine] DEBUG: Crawled (403) <GET https://auth3.bpsecure.com/robots.txt> (referer: None)
2017-06-03 22:04:42 [scrapy.downloadermiddlewares.redirect] DEBUG: Redirecting (302) to <GET https://www.darkorbit.com/ProjectAp........>
2017-06-03 22:04:42 [scrapy.downloadermiddlewares.redirect] DEBUG: Redirecting (302) to <GET https://ru4.darkorbit.com/Pro..........>
2017-06-03 22:04:43 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://ru4.darkorbit.com/robots.txt> (referer: None)
2017-06-03 22:04:43 [scrapy.downloadermiddlewares.robotstxt] DEBUG: Forbidden by robots.txt: <GET https://ru4.darkorbit.com/Pro......>
</code>```

答:
From this line of your logs:

```<code>2017-06-03 22:04:43 [scrapy.downloadermiddlewares.robotstxt] DEBUG: Forbidden by robots.txt: <GET https://ru4.darkorbit.com/Pro......>
</code>```

I can tell that you need to change a setting in you settings.py file.

The variable ROBOTSTXT_OBEY needs to be set at False

```<code>ROBOTSTXT_OBEY=False
</code>```

ContentLicense: CC BY-SA 3.0

Title: Login to the site through scrapy

Body:
I do an official video lesson authorization on the site.
If the username and password are incorrect, then the transition to the callback method is successful, if the login and password are correct, then the transition to the method is not feasible.
My code:
import scrapy

class QuotesSpider(scrapy.Spider):
    name = "quotes"
    start_urls = ["https://www.darkorbit.com"]

    def parse(self, response):
        login_url = response.css('form[name="bgcdw_login_form"]::attr(action)').extract_first()
        data = {
            'username': 'testscrapy',
            'password': 'testtest',
        }
        yield scrapy.FormRequest(url=login_url, formdata=data, callback=self.after_login)

    def after_login(self, response):
        print('----------------------------------------')

With the correct input data, a log is obtained(Long fragments are cut):

2017-06-03 22:04:40 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.darkorbit.com/robots.txt> (referer: None)
2017-06-03 22:04:41 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.darkorbit.com> (referer: None)
2017-06-03 22:04:42 [scrapy.core.engine] DEBUG: Crawled (403) <GET https://auth3.bpsecure.com/robots.txt> (referer: None)
2017-06-03 22:04:42 [scrapy.downloadermiddlewares.redirect] DEBUG: Redirecting (302) to <GET https://www.darkorbit.com/ProjectAp........>
2017-06-03 22:04:42 [scrapy.downloadermiddlewares.redirect] DEBUG: Redirecting (302) to <GET https://ru4.darkorbit.com/Pro..........>
2017-06-03 22:04:43 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://ru4.darkorbit.com/robots.txt> (referer: None)
2017-06-03 22:04:43 [scrapy.downloadermiddlewares.robotstxt] DEBUG: Forbidden by robots.txt: <GET https://ru4.darkorbit.com/Pro......>

Body:
From this line of your logs:

2017-06-03 22:04:43 [scrapy.downloadermiddlewares.robotstxt] DEBUG: Forbidden by robots.txt: <GET https://ru4.darkorbit.com/Pro......>

I can tell that you need to change a setting in you settings.py file.

The variable ROBOTSTXT_OBEY needs to be set at False

ROBOTSTXT_OBEY=False


问:
How to convert Protobuf ByteString to an octal-escaped String in java?
Could anyone please let me know how to convert protobuf's ByteString to  an octal escape sequence String in java?

In my case, I am getting the ByteString value as \376\024\367 so,  when I print the string value in console using System.out.println(), I should get "\376\024\367".

Many thanks.

答:
I have used http://doc.akka.io/japi/akka/2.3.7/akka/util/ByteString.ByteStrings.html
You will see to method decodeString(java.lang.String charset)

else see to https://github.com/akka/akka/issues/18738

ContentLicense: CC BY-SA 4.0


问:
PHP framework to build Workflow Management system
I am looking for PHP framework to build a Workflow Management system.
While searching on net i got RADICORE which is quite best one. Just looking for more option so that I can compare them and go with one of them

My requirement is as:
I need framework that can define a workflow as we do in RADICORE and then play around it.
Playing means that if there 4 steps in my workflow, i can drop one and see How the workflow proceeds.
There are many frameworks through which you can generate a graph of your existing flow.
So i am basically interested in defining a workflow rather than generating the graph for existing framework.

And i should be an open source framework (basically PHP).

答:
I can suggest formapro/pvm library.

The library provides us with a frame to build a workflow or business processes such as BPMN.
It works like this: you build a process, create nodes and transitions, link them up. Then you can do:

Save process and execute later.

Clone and execute several processes.

Pause & continue execution.

Supports async transition. Execute tasks in parallel.

Supports fork-join, conditions, cycles and so on.

It is backed up by workflow nets (WF-nets) and graphs theories. . Here's a good post on how Petri Nets works

It's very powerful and at the same easy to use (thanks to Petri Nets theory).


问:
scala Future processing depth-first not breadth-first
I have a large computation roughly based on the following pattern :

```<code>def f1(i:Int):Int = ???
def f2(i:Int):Int = ???

def processA(l: List[Int]) =
  l.map(i => Future(f1(i)))

def processB(l: List[Int]) = {
  val p = processA(l)
  p.map(fut => fut.map(f2))
}

def main() = {
  val items = List( /* 1k to 10k items here */ )
  val results = processB(items)
  results.map(_.onComplete ( ... ))
}
</code>```

The problem I encounter, if my understanding is correct, is that the processing is breadth-first. ProcessA starts thousands of Futures, and processB will then enqueue thousands of new Futures that will be processed after those of processA are finished. The onComplete callback will start to be fired very late...

I would like to turn this depth-first : few Futures of processA starts, and then, processB continues from there instead of switching to something else in queues.

Can it be done in vanilla scala ? Should I turn to some lib with an alternative to Futures() and ThreadPools ?

EDIT: a bit more detail. Rewriting into f1 andThen f2, as it has been suggested in answers, is not practicable at this time. Actually, processA and B are doing a bunch of other things (incl. side effect). And the fact that processB relies on ProcessA is private. It would break SoC if it's exposed.

EDIT 2: I think I'm going to relax a bit the "vanilla" constraint. Someone suggested Akka streams that would help. I'm currently having a look at scalaz.Task: an opinion anyone ?

答:
It is not clear from the question if, from a asynchronous computation point of view, there is a requirement that f1 and f2 are separated into processA and processB - results from f1 are always and only passed to f2, which can be done simpler as part of a single computation "f1 andThen f2", and in a single Future.

If that is the case, then the problem is reduced to "how can a asynchronous computation be run on a potentially large input, limiting the in-flight, spawned Futures":

```<code>import scala.concurrent.Future
import java.util.concurrent.Semaphore
import scala.concurrent.ExecutionContext.Implicits.global

val f: (Int) => Int = i => f2(f1(i))

def process(concurrency: Int, input: List[Int], f: Int => Int): Future[List[Int]] = {
  val semaphore = new Semaphore(concurrency)
  Future.traverse(input) { i =>
    semaphore.acquire()
    Future(f(i)).andThen { case _ => semaphore.release() }
  }
}
</code>```

Body:
I have a large computation roughly based on the following pattern :

def f1(i:Int):Int = ???
def f2(i:Int):Int = ???

def processA(l: List[Int]) =
  l.map(i => Future(f1(i)))

def processB(l: List[Int]) = {
  val p = processA(l)
  p.map(fut => fut.map(f2))
}

def main() = {
  val items = List( /* 1k to 10k items here */ )
  val results = processB(items)
  results.map(_.onComplete ( ... ))
}

The problem I encounter, if my understanding is correct, is that the processing is breadth-first. ProcessA starts thousands of Futures, and processB will then enqueue thousands of new Futures that will be processed after those of processA are finished. The onComplete callback will start to be fired very late...

I would like to turn this depth-first : few Futures of processA starts, and then, processB continues from there instead of switching to something else in queues.

Can it be done in vanilla scala ? Should I turn to some lib with an alternative to Futures() and ThreadPools ?

EDIT: a bit more detail. Rewriting into f1 andThen f2, as it has been suggested in answers, is not practicable at this time. Actually, processA and B are doing a bunch of other things (incl. side effect). And the fact that processB relies on ProcessA is private. It would break SoC if it's exposed.

EDIT 2: I think I'm going to relax a bit the "vanilla" constraint. Someone suggested Akka streams that would help. I'm currently having a look at scalaz.Task: an opinion anyone ?

Body:
It is not clear from the question if, from a asynchronous computation point of view, there is a requirement that f1 and f2 are separated into processA and processB - results from f1 are always and only passed to f2, which can be done simpler as part of a single computation "f1 andThen f2", and in a single Future.

If that is the case, then the problem is reduced to "how can a asynchronous computation be run on a potentially large input, limiting the in-flight, spawned Futures":

import scala.concurrent.Future
import java.util.concurrent.Semaphore
import scala.concurrent.ExecutionContext.Implicits.global

val f: (Int) => Int = i => f2(f1(i))

def process(concurrency: Int, input: List[Int], f: Int => Int): Future[List[Int]] = {
  val semaphore = new Semaphore(concurrency)
  Future.traverse(input) { i =>
    semaphore.acquire()
    Future(f(i)).andThen { case _ => semaphore.release() }
  }
}


问:
Replace first column on csv file based on their value
I have a csv file structured like this:

```<code>01 - FOO_1,value2,value3,...
01 - FOO_1,value2,value3,...
07 - FOO_7,value2,value3,...
...
</code>```

How do i change the first column so it keeps only the number and looks like this:

```<code>01,value2,value3,...
01,value2,value3,...
07,value2,value3,...
</code>```

Body:
I have a csv file structured like this:

01 - FOO_1,value2,value3,...
01 - FOO_1,value2,value3,...
07 - FOO_7,value2,value3,...
...

How do i change the first column so it keeps only the number and looks like this:

01,value2,value3,...
01,value2,value3,...
07,value2,value3,...

Body:
with sed:

sed 's/^\([0-9]*\)\([^,]*\)\(.*\)/\1\3/g' file


问:
initctl: Unknown instance: error after Rstudio conf change
I have a new version of R installed on an aws-machine (which always come with an old version for some reason and it's near impossible to just have yum or apt-get to work). I want rstudio to point to this new version which I've built from source without throwing the old version away. I therefore go to /etc/rstudio/rserver.conf (documentation) and change the contents to:

```<code># Server Configuration File
rsession-which-r=/root/R-3.2.1/bin/R
</code>```

I can confirm that at this location a new version of R is installed but then I get an error after rstudio-server restarts.

```<code>root@ip-172-31-40-49 rstudio]$ rstudio-server restart
initctl: Unknown instance:
</code>```

What am I to do?

答: It happened for me on my Cento-7.x machine while I upgraded from old RStudio server to the new version. Rebooting the machine seems to have fixed the problem.</p>

Body:
I have a new version of R installed on an aws-machine (which always come with an old version for some reason and it's near impossible to just have yum or apt-get to work). I want rstudio to point to this new version which I've built from source without throwing the old version away. I therefore go to /etc/rstudio/rserver.conf (documentation) and change the contents to:

# Server Configuration File
rsession-which-r=/root/R-3.2.1/bin/R

I can confirm that at this location a new version of R is installed but then I get an error after rstudio-server restarts.

root@ip-172-31-40-49 rstudio]$ rstudio-server restart
initctl: Unknown instance:

What am I to do?


问:
How to write a double recursive function in R
I want tot write a program in R to compute a value, the program is below .

```<code>     options( expressions = 5e5 )
     P_n_m=function(r,n,m) {
       if(r >0 & n==1 & m==0 | r >=0 & n==0 & m==1) return(1)
       else if(r >= 0 & n >= 0 | r >= 0 & m >= 0){
         return(n/(n+m)*P_n_m(r-n-m,n-1,m)+m/(n+m)*P_n_m(r,n,m-1))
       }
       else return(0)
     }
</code>```

But it always give me error. I also try to adjust system setting,
but it still didn't work. I want to compute P_n_m(49,7,7), and I don't know
which part in program is wrong. Can any one help me to solve this problem?

答:
Your function has an infinite recursion in it.

When you compute P_n_m(r,n,m),  you must compute both
P_n_m(r-n-m,n-1,m) and P_n_m(r,n,m-1).  Notice that
the second term only reduces m but leaves r and n unchanged.
That causes the infinite recursion.

Let's track your example,  P_n_m(49,7,7). It will have to compute
(among other things)

P_n_m(49,7,6) which has to compute

P_n_m(49,7,5) which has to compute

P_n_m(49,7,4) which has to compute

P_n_m(49,7,3) which has to compute

P_n_m(49,7,2) which has to compute

P_n_m(49,7,1) we have m==1 but not n==0, both r & n > 0 so we need

P_n_m(49,7,0) we have m==0 but not n==1, both r & n > 0 so we need

P_n_m(49,7,-1) and now we need

P_n_m(49,7,m)  down to negative infinity.

You need to rethink the definition of your function.

Body:
I want tot write a program in R to compute a value, the program is below .

     options( expressions = 5e5 )
     P_n_m=function(r,n,m) {
       if(r >0 & n==1 & m==0 | r >=0 & n==0 & m==1) return(1)
       else if(r >= 0 & n >= 0 | r >= 0 & m >= 0){
         return(n/(n+m)*P_n_m(r-n-m,n-1,m)+m/(n+m)*P_n_m(r,n,m-1))
       }
       else return(0)
     }

But it always give me error. I also try to adjust system setting,
but it still didn't work. I want to compute P_n_m(49,7,7), and I don't know
which part in program is wrong. Can any one help me to solve this problem?


问:
trying to auto populate fields using django views
my question is similar to this question em using geoip to find the latitide and longitude of a user through IP address. i am doing something like this in my views

```<code>g=Geoip()
lat,lon=g.lat_lon(some ip)
</code>```

here i want  the forms fields to be filled in automatically
something like

```<code> latitude=lat
 longitude=lon
 userform.save()
</code>```

and dont want to overwrite the save method as i am  fairly new to django and no idea about how they work. i tried the above link code but unable to make it work for me.
how can i autopopulate the latitude and longitude fields in views.py

答:
Ah, just dive right in. Unless you do something really stupid you're not going to hurt anything. BTW, "stupid" includes doing this on your production site with an un-backed up database.

An important point to remember is that you're not overwriting the save() method, you're supplying a class-specific version of it which can, in turn, call the parent's save() method. E.g.

```<code>class MyModel(models.Model):
   ...
   def save(self):
      # whatever you need to do to the object before the save
      super(MyModel, self).save() # replace MyModel with *your* class name
</code>```

Alternatively, you can call super() first and then do stuff afterward. If all your routine did was call super() you would have a correct (but useless) save() method.

See the Python docs for more insight/info.

Body:
my question is similar to this question em using geoip to find the latitide and longitude of a user through IP address. i am doing something like this in my views

g=Geoip()
lat,lon=g.lat_lon(some ip)

here i want  the forms fields to be filled in automatically
something like

 latitude=lat
 longitude=lon
 userform.save()

and dont want to overwrite the save method as i am  fairly new to django and no idea about how they work. i tried the above link code but unable to make it work for me.
how can i autopopulate the latitude and longitude fields in views.py

Body:
Ah, just dive right in. Unless you do something really stupid you're not going to hurt anything. BTW, "stupid" includes doing this on your production site with an un-backed up database.

An important point to remember is that you're not overwriting the save() method, you're supplying a class-specific version of it which can, in turn, call the parent's save() method. E.g.

class MyModel(models.Model):
   ...
   def save(self):
      # whatever you need to do to the object before the save
      super(MyModel, self).save() # replace MyModel with *your* class name

Alternatively, you can call super() first and then do stuff afterward. If all your routine did was call super() you would have a correct (but useless) save() method.

See the Python docs for more insight/info.


问:
Which format is better for list in JSON API design, flat array or nested object?
For list API, such as Users, I find that there are two common formats. Arrays:

```<code>// flat array
[
  {
    "login": "octocat",
    "id": 1
    ...
  },
  ...
]
</code>```

GitHub, Heroku  and Twitter use this format

VS Objects:

```<code>{
  "results": [
    {
      "login": "octocat",
      "id": 1
      ...
    },
    ...
  ]
}
</code>```

Parse and Slack and instagram use this format.

Which one is better? How to compare these two formats?

答:
Array-oriented data has the following advantages:

Client-side JavaScript has more methods for arrays than objects

No need for root node to simulate a tree structure for a tabular structure

and disadvantages:

No namespacing since indexes are numeric

JSON.parse fails in client-side JavaScript

Key/Value-oriented data has the following advantages:

JSON.parse works in client-side JavaScript

Namespacing makes duplicate values easier to disambiguate

JSON.stringify works to make simple transformations easier compared to array methods

and disadvantages:

It can be hard to iterate nested hierarchies without a library in client-side code

JSON.parse in client-side code removes duplicate key names on the same level

References

Want to return and array from the Restful Web services?

Read local file text (tab separated values) with d3 or ajax cause syntax error in firefox development console

Query JSON/XML/CSV using SQL | Joe Conley

Body:
For list API, such as Users, I find that there are two common formats. Arrays:

// flat array
[
  {
    "login": "octocat",
    "id": 1
    ...
  },
  ...
]

GitHub, Heroku  and Twitter use this format

VS Objects:

{
  "results": [
    {
      "login": "octocat",
      "id": 1
      ...
    },
    ...
  ]
}

Parse and Slack and instagram use this format.

Which one is better? How to compare these two formats?


问:
Iterating and modifying dataframe using Pandas groupby
I am working with a large array of 1's and need to systematically remove 0's from sections of the array. The large array is comprised of many smaller arrays, for each smaller array I need to replace its upper and lower triangles with 0's systematically. For example we have an array with 5 sub arrays indicated by the index value (all sub-arrays have the same number of columns):

```<code>     0    1    2
0  1.0  1.0  1.0
1  1.0  1.0  1.0
1  1.0  1.0  1.0
2  1.0  1.0  1.0
2  1.0  1.0  1.0
2  1.0  1.0  1.0
3  1.0  1.0  1.0
3  1.0  1.0  1.0
3  1.0  1.0  1.0
3  1.0  1.0  1.0
4  1.0  1.0  1.0
4  1.0  1.0  1.0
4  1.0  1.0  1.0
4  1.0  1.0  1.0
4  1.0  1.0  1.0
</code>```

I want each group of rows to be modified in its upper and lower triangle such that the resulting matrix is:

```<code>      0    1    2
0  1.0  1.0  1.0
1  1.0  1.0  0.0
1  0.0  1.0  1.0
2  1.0  0.0  0.0
2  0.0  1.0  0.0
2  0.0  0.0  1.0
3  1.0  0.0  0.0
3  1.0  1.0  0.0
3  0.0  1.0  1.0
3  0.0  0.0  1.0
4  1.0  0.0  0.0
4  1.0  1.0  0.0
4  1.0  1.0  1.0
4  0.0  1.0  1.0
4  0.0  0.0  1.0
</code>```

At the moment I am using only numpy to achieve this resulting array, but I think I can speed it up using Pandas grouping. In reality my dataset is very large almost 500,000 rows long. The numpy code is below:

```<code>import numpy as np

candidateLengths = np.array([1,2,3,4,5])
centroidLength =3

smallPaths = [min(l,centroidLength) for l in candidateLengths]

# This is the k_values of zeros to delete. To be used in np.tri
k_vals = list(map(lambda smallPath: centroidLength - (smallPath), smallPaths))
maskArray = np.ones((np.sum(candidateLengths), centroidLength))

startPos = 0
endPos = 0
for canNo, canLen in enumerate(candidateLengths):
    a = np.ones((canLen, centroidLength))
    a *= np.tri(*a.shape, dtype=np.bool, k=k_vals[canNo])
    b = np.fliplr(np.flipud(a))
    c = a*b

    endPos = startPos + canLen

    maskArray[startPos:endPos, :] = c

    startPos = endPos

print(maskArray)
</code>```

When I run this on my real dataset it takes nearly 5-7secs to execute. I think this is down to this massive for loop. How can I use pandas groupings to achieve  a higher speed? Thanks

Body:
I am working with a large array of 1's and need to systematically remove 0's from sections of the array. The large array is comprised of many smaller arrays, for each smaller array I need to replace its upper and lower triangles with 0's systematically. For example we have an array with 5 sub arrays indicated by the index value (all sub-arrays have the same number of columns):

     0    1    2
0  1.0  1.0  1.0
1  1.0  1.0  1.0
1  1.0  1.0  1.0
2  1.0  1.0  1.0
2  1.0  1.0  1.0
2  1.0  1.0  1.0
3  1.0  1.0  1.0
3  1.0  1.0  1.0
3  1.0  1.0  1.0
3  1.0  1.0  1.0
4  1.0  1.0  1.0
4  1.0  1.0  1.0
4  1.0  1.0  1.0
4  1.0  1.0  1.0
4  1.0  1.0  1.0

I want each group of rows to be modified in its upper and lower triangle such that the resulting matrix is:

      0    1    2
0  1.0  1.0  1.0
1  1.0  1.0  0.0
1  0.0  1.0  1.0
2  1.0  0.0  0.0
2  0.0  1.0  0.0
2  0.0  0.0  1.0
3  1.0  0.0  0.0
3  1.0  1.0  0.0
3  0.0  1.0  1.0
3  0.0  0.0  1.0
4  1.0  0.0  0.0
4  1.0  1.0  0.0
4  1.0  1.0  1.0
4  0.0  1.0  1.0
4  0.0  0.0  1.0

At the moment I am using only numpy to achieve this resulting array, but I think I can speed it up using Pandas grouping. In reality my dataset is very large almost 500,000 rows long. The numpy code is below:

import numpy as np

candidateLengths = np.array([1,2,3,4,5])
centroidLength =3

smallPaths = [min(l,centroidLength) for l in candidateLengths]

# This is the k_values of zeros to delete. To be used in np.tri
k_vals = list(map(lambda smallPath: centroidLength - (smallPath), smallPaths))
maskArray = np.ones((np.sum(candidateLengths), centroidLength))

startPos = 0
endPos = 0
for canNo, canLen in enumerate(candidateLengths):
    a = np.ones((canLen, centroidLength))
    a *= np.tri(*a.shape, dtype=np.bool, k=k_vals[canNo])
    b = np.fliplr(np.flipud(a))
    c = a*b

    endPos = startPos + canLen

    maskArray[startPos:endPos, :] = c

    startPos = endPos

print(maskArray)

When I run this on my real dataset it takes nearly 5-7secs to execute. I think this is down to this massive for loop. How can I use pandas groupings to achieve  a higher speed? Thanks

Body:
New Answer

def tris(n, m):
    if n < m:
        a = np.tri(m, n, dtype=int).T
    else:
        a = np.tri(n, m, dtype=int)
    return a * a[::-1, ::-1]

idx = np.append(df.index.values, -1)
w = np.append(-1, np.flatnonzero(idx[:-1] != idx[1:]))
c = np.diff(w)
df * np.vstack([tris(n, 3) for n in c])

     0    1    2
0  1.0  1.0  1.0
1  1.0  1.0  0.0
1  0.0  1.0  1.0
2  1.0  0.0  0.0
2  0.0  1.0  0.0
2  0.0  0.0  1.0
3  1.0  0.0  0.0
3  1.0  1.0  0.0
3  0.0  1.0  1.0
3  0.0  0.0  1.0
4  1.0  0.0  0.0
4  1.0  1.0  0.0
4  1.0  1.0  1.0
4  0.0  1.0  1.0
4  0.0  0.0  1.0

Old Answer

I define some helper triangle functions

def tris(n, m):
    if n < m:
        a = np.tri(m, n, dtype=int).T
    else:
        a = np.tri(n, m, dtype=int)
    return a * a[::-1, ::-1]

def tris_df(df):
    n, m = df.shape
    return pd.DataFrame(tris(n, m), df.index, df.columns)

Then

df * df.groupby(level=0, group_keys=False).apply(tris_df)

     0    1    2
0  1.0  1.0  1.0
1  1.0  1.0  0.0
1  0.0  1.0  1.0
2  1.0  0.0  0.0
2  0.0  1.0  0.0
2  0.0  0.0  1.0
3  1.0  0.0  0.0
3  1.0  1.0  0.0
3  0.0  1.0  1.0
3  0.0  0.0  1.0
4  1.0  0.0  0.0
4  1.0  1.0  0.0
4  1.0  1.0  1.0
4  0.0  1.0  1.0
4  0.0  0.0  1.0


问:
How to implement a method with an unknown number of arguments?
I have 1 interface and 3 class. I would like the class to be able to both implement the interface which need a transform method. This method must exist but there can't be more than one per class. I don't know the number of parameters taken by this class.

Example :

```<code>public interface A{
    public void transform(Object ... args);
}

public class B implements A{
    public void transform(String a){
        System.out.println(a);
    }
}

public class C implements A{
    public void transform(Integer a, Character b){
        System.out.println(a+b);
    }
}

// super generic case if possible with Objects + primitive
public class D implements A{
    public void transform(int a, String b){
        System.out.println(a+b);
    }
}
</code>```

This doesn't work. But I hope you got the idea. Is something like this possible in java ? How should I call them in a generic way ? Let's say if I have an other method like :

```<code>void callTransf(A a, Object ... objs){
    Method m = a.getClass().getMethods()[0];
    m.invoke(a, objs)
}
</code>```

答:
What you are asking isn't possible.
If interface method uses Varargs then others must too. So one solution would be to have both classes use this interface. Here is general idea:

```<code>public interface A{
    public void transform(char ... args);
}

public class B implements A{
    public void transform(char ... args){
        String s = "";
        for(char c : args){
        s += c;
        }
        System.out.println(s);
    }
}

public class C implements A{
    public void transform(char ... args){
        System.out.println(args[0] + args[1]);
    }
}
</code>```

Now when you are calling method in B then you must convert string to char array:

```<code>String str = "example";
char[] charArray = str.toCharArray();
</code>```

When calling method in A you make sure to convert integer to char:

```<code>int i = 5;
transform((char)Character.forDigit(i, 10), 'a'); // 10 stands for number radix which is probably 10
</code>```

This isn't perfect solution but it is working one.

But a bit simpler solution without varargs is using just char array, but again you need to convert inputs to char array.

```<code>public interface A{
    public void transform(char[]);
}

public class B implements A{
        public void transform(char[] args){
            String s = "";
            for(char c : args){
            s += c;
            }
            System.out.println(s);
        }
    }

    public class C implements A{
        public void transform(char[] args){
            System.out.println(args[0] + args[1]);
        }
    }
</code>```

Anyway you do it, you will end up with a bit complicated code, even if using generics you must remember that 1 method takes 1 parameter and other one 2. I actually think that it would be best to simply make this methods separate.

Body:
I have 1 interface and 3 class. I would like the class to be able to both implement the interface which need a transform method. This method must exist but there can't be more than one per class. I don't know the number of parameters taken by this class.

Example :

public interface A{
    public void transform(Object ... args);
}

public class B implements A{
    public void transform(String a){
        System.out.println(a);
    }
}

public class C implements A{
    public void transform(Integer a, Character b){
        System.out.println(a+b);
    }
}

// super generic case if possible with Objects + primitive
public class D implements A{
    public void transform(int a, String b){
        System.out.println(a+b);
    }
}

This doesn't work. But I hope you got the idea. Is something like this possible in java ? How should I call them in a generic way ? Let's say if I have an other method like :

void callTransf(A a, Object ... objs){
    Method m = a.getClass().getMethods()[0];
    m.invoke(a, objs)
}

Body:
What you are asking isn't possible.
If interface method uses Varargs then others must too. So one solution would be to have both classes use this interface. Here is general idea:

public interface A{
    public void transform(char ... args);
}

public class B implements A{
    public void transform(char ... args){
        String s = "";
        for(char c : args){
        s += c;
        }
        System.out.println(s);
    }
}

public class C implements A{
    public void transform(char ... args){
        System.out.println(args[0] + args[1]);
    }
}

Now when you are calling method in B then you must convert string to char array:

String str = "example";
char[] charArray = str.toCharArray();

When calling method in A you make sure to convert integer to char:

int i = 5;
transform((char)Character.forDigit(i, 10), 'a'); // 10 stands for number radix which is probably 10

This isn't perfect solution but it is working one.

But a bit simpler solution without varargs is using just char array, but again you need to convert inputs to char array.

public interface A{
    public void transform(char[]);
}

public class B implements A{
        public void transform(char[] args){
            String s = "";
            for(char c : args){
            s += c;
            }
            System.out.println(s);
        }
    }

    public class C implements A{
        public void transform(char[] args){
            System.out.println(args[0] + args[1]);
        }
    }

Anyway you do it, you will end up with a bit complicated code, even if using generics you must remember that 1 method takes 1 parameter and other one 2. I actually think that it would be best to simply make this methods separate.


问:
Excel VBA & UserForm Login and Password VLOOKUP Table in Sheet
I've been trying to get my login userform to login when clicked based on data in a table in the workbook, but I just can't seem to get the code right.

Details are:

Userform username textbox = UsernameTextbox;

Userform password textbox = PasswordTextbox;

Userform submit button = LoginButton

My workbook has a number of sheets, one of which is "Users". In that sheet, there is a table called "Users_Table". That table has 4 columns:

ID (individual IDs for users) [Column A],

Username [Column B],

Password [Column C],

Admin (answer is "True" or "False" depending on if they have admin rights) [Column D].

I'm trying to do this:
If the username and password is correct for a user AND if the admin column entry is False, then I want to show sheets "Quick Add" and "Overview", I want to make the sheet "Admin" hidden (not VeryHidden since I need to use data on this sheet for other macros), and make "User" sheets VeryHidden so those logged in can't see other users' details. But for users who correctly enter their username and password AND for whom the admin column entry is True, I want to show all sheets.

This is what I have so far:

```<code>Private Sub LoginButton_Click()
  Dim Username As String
  Username = UsernameTextbox.Text
  Dim password As String
  Password = PasswordTextbox.Text
  If IsNull(Me.UsernameTextbox) Or Me.UsernameTextbox = "" Then
    MsgBox "You must enter your username.", vbOKOnly, "Required Data"
    Me.UsernameTextbox.SetFocus
    Exit Sub
  End If
  If IsNull(Me.PasswordTextbox) Or Me.PasswordTextbox = "" Then
    MsgBox "You must enter your Password (case sensitive).", vbOKOnly, "Incomplete Entry"
    Me.PasswordTextbox.SetFocus
    Exit Sub
  End If
  Dim temp As String
  On Error Resume Next
  temp = WorksheetFunction.VLookup(Me.UsernameTextbox.Value, Worksheets("Users").Range("Users_Table"), 2, 0)
  If Username = temp Then
    Err.Clear
    temp = ""
    temp = WorksheetFunction.VLookup(Me.UsernameTextbox.Value, Worksheets("Users").Range("Users_Table"), 3, 0)
    On Error Goto 0
    If Password = temp Then
      Sheets("Quick Add").Visible = xlSheetVisible
      Sheets("Overview").Visible = xlSheetVisible
      Sheets("Admin").Visible = xlSheetHidden 'This is now just Hidden and not VeryHidden since other macros need to use data on this sheet
      Sheets("Users").Visible = xlVeryHidden
      MsgBox "Password and Username Accepted. You are now Logged In."
      'Unload Me
      'Sheets("Quick Add").Select
      'Range("A1").Select
    Else
      Sheets("Quick Add").Visible = xlVeryHidden
      Sheets("Overview").Visible = xlVeryHidden
      Sheets("Admin").Visible = xlVeryHidden
      Sheets("Users").Visible = xlVeryHidden
      MsgBox "Username and Password Combination Not Accepted"
    End If
  Else
    Sheets("Quick Add").Visible = xlVeryHidden
    Sheets("Overview").Visible = xlVeryHidden
    Sheets("Admin").Visible = xlVeryHidden
    Sheets("Users").Visible = xlVeryHidden
    MsgBox "Invalid Username"
  End If
End Sub
</code>```

This works for the first entry in the "Users_Table", but it won't recognise the Username for the others (and so I don't know if it's recognising the Passwords for users as it's failing on the initial Username check). Any ideas what might be going wrong? I'm also not sure how I'd go about adding in the Admin requirement mentioned above. I need Admins ("True" in "Admin" column, i.e. Column D, in the "Users_Table") to be able to see all sheets; the code above is just for Users and shows "Quick Add" and "Overview" and hides "Admin" and "Users" sheets.

Any help would be much appreciated. Thank you!

答:
Any ideas what might be going wrong?

There are a few errors in the code that don't match your description.

```<code>temp = WorksheetFunction.VLookup(Me.UsernameTextbox.Value, _
  Worksheets("Users").Range("Users_Table"), 2, 0)
If Username = temp Then
</code>```

Here you are matching the UsernameTextbox to column A (ID). The test for existence of the username should be in column B not A. The same mistake is made where you are matching the username onto the ID column A insread of the column B of user names:

```<code>temp = WorksheetFunction.VLookup(Me.UsernameTextbox.Value, _
   Worksheets("Users").Range("Users_Table"), 3, 0)
</code>```

The best approach would be to fetch to row of the user at once (if it exists) and from there get all the attributes.

```<code>Private Sub LoginButton_Click()
  ' Get the user row or exit if not found
  Dim r As Range
  Set r = Worksheets("Users").Range("Users_Table").Columns(2) _
    .Find(UsernameTextbox.text, , xlValues, xlWhole)
  If r Is Nothing Then
    MsgBox "username not found."
    Me.UsernameTextbox.SetFocus
    Exit Sub
  End If
  If Me.PasswordTextbox.Value <> r.Offset(, 1).Value2 Then
    MsgBox "Wrong Password."
    Me.PasswordTextbox.SetFocus
    Exit Sub
  End If

  ' So far user and password are ok
  Dim isAdmin As Boolean: isAdmin = r.Offset(, 2).Value2
  Sheets("Quick Add").Visible = xlSheetVisible
  Sheets("Overview").Visible = xlSheetVisible
  Sheets("Admin").Visible = IIf(isAdmin, xlSheetVisible, xlSheetHidden)
  Sheets("Users").Visible = IIf(isAdmin, xlSheetVisible, xlSheetVeryHidden)
End Sub
</code>```

Body:
I've been trying to get my login userform to login when clicked based on data in a table in the workbook, but I just can't seem to get the code right.

Details are:

Userform username textbox = UsernameTextbox;

Userform password textbox = PasswordTextbox;

Userform submit button = LoginButton

My workbook has a number of sheets, one of which is "Users". In that sheet, there is a table called "Users_Table". That table has 4 columns:

ID (individual IDs for users) [Column A],

Username [Column B],

Password [Column C],

Admin (answer is "True" or "False" depending on if they have admin rights) [Column D].

I'm trying to do this:
If the username and password is correct for a user AND if the admin column entry is False, then I want to show sheets "Quick Add" and "Overview", I want to make the sheet "Admin" hidden (not VeryHidden since I need to use data on this sheet for other macros), and make "User" sheets VeryHidden so those logged in can't see other users' details. But for users who correctly enter their username and password AND for whom the admin column entry is True, I want to show all sheets.

This is what I have so far:

Private Sub LoginButton_Click()
  Dim Username As String
  Username = UsernameTextbox.Text
  Dim password As String
  Password = PasswordTextbox.Text
  If IsNull(Me.UsernameTextbox) Or Me.UsernameTextbox = "" Then
    MsgBox "You must enter your username.", vbOKOnly, "Required Data"
    Me.UsernameTextbox.SetFocus
    Exit Sub
  End If
  If IsNull(Me.PasswordTextbox) Or Me.PasswordTextbox = "" Then
    MsgBox "You must enter your Password (case sensitive).", vbOKOnly, "Incomplete Entry"
    Me.PasswordTextbox.SetFocus
    Exit Sub
  End If
  Dim temp As String
  On Error Resume Next
  temp = WorksheetFunction.VLookup(Me.UsernameTextbox.Value, Worksheets("Users").Range("Users_Table"), 2, 0)
  If Username = temp Then
    Err.Clear
    temp = ""
    temp = WorksheetFunction.VLookup(Me.UsernameTextbox.Value, Worksheets("Users").Range("Users_Table"), 3, 0)
    On Error Goto 0
    If Password = temp Then
      Sheets("Quick Add").Visible = xlSheetVisible
      Sheets("Overview").Visible = xlSheetVisible
      Sheets("Admin").Visible = xlSheetHidden 'This is now just Hidden and not VeryHidden since other macros need to use data on this sheet
      Sheets("Users").Visible = xlVeryHidden
      MsgBox "Password and Username Accepted. You are now Logged In."
      'Unload Me
      'Sheets("Quick Add").Select
      'Range("A1").Select
    Else
      Sheets("Quick Add").Visible = xlVeryHidden
      Sheets("Overview").Visible = xlVeryHidden
      Sheets("Admin").Visible = xlVeryHidden
      Sheets("Users").Visible = xlVeryHidden
      MsgBox "Username and Password Combination Not Accepted"
    End If
  Else
    Sheets("Quick Add").Visible = xlVeryHidden
    Sheets("Overview").Visible = xlVeryHidden
    Sheets("Admin").Visible = xlVeryHidden
    Sheets("Users").Visible = xlVeryHidden
    MsgBox "Invalid Username"
  End If
End Sub

This works for the first entry in the "Users_Table", but it won't recognise the Username for the others (and so I don't know if it's recognising the Passwords for users as it's failing on the initial Username check). Any ideas what might be going wrong? I'm also not sure how I'd go about adding in the Admin requirement mentioned above. I need Admins ("True" in "Admin" column, i.e. Column D, in the "Users_Table") to be able to see all sheets; the code above is just for Users and shows "Quick Add" and "Overview" and hides "Admin" and "Users" sheets.

Any help would be much appreciated. Thank you!

Body:
Any ideas what might be going wrong?

There are a few errors in the code that don't match your description.

temp = WorksheetFunction.VLookup(Me.UsernameTextbox.Value, _
  Worksheets("Users").Range("Users_Table"), 2, 0)
If Username = temp Then

Here you are matching the UsernameTextbox to column A (ID). The test for existence of the username should be in column B not A. The same mistake is made where you are matching the username onto the ID column A insread of the column B of user names:

temp = WorksheetFunction.VLookup(Me.UsernameTextbox.Value, _
   Worksheets("Users").Range("Users_Table"), 3, 0)

The best approach would be to fetch to row of the user at once (if it exists) and from there get all the attributes.

Private Sub LoginButton_Click()
  ' Get the user row or exit if not found
  Dim r As Range
  Set r = Worksheets("Users").Range("Users_Table").Columns(2) _
    .Find(UsernameTextbox.text, , xlValues, xlWhole)
  If r Is Nothing Then
    MsgBox "username not found."
    Me.UsernameTextbox.SetFocus
    Exit Sub
  End If
  If Me.PasswordTextbox.Value <> r.Offset(, 1).Value2 Then
    MsgBox "Wrong Password."
    Me.PasswordTextbox.SetFocus
    Exit Sub
  End If

  ' So far user and password are ok
  Dim isAdmin As Boolean: isAdmin = r.Offset(, 2).Value2
  Sheets("Quick Add").Visible = xlSheetVisible
  Sheets("Overview").Visible = xlSheetVisible
  Sheets("Admin").Visible = IIf(isAdmin, xlSheetVisible, xlSheetHidden)
  Sheets("Users").Visible = IIf(isAdmin, xlSheetVisible, xlSheetVeryHidden)
End Sub


答:
awk solution:

```<code>awk -F, '{ $1=sprintf("%02d",$1) }1' OFS=',' file
</code>```

Title: Replace first column on csv file based on their value

Body:
awk solution:

awk -F, '{ $1=sprintf("%02d",$1) }1' OFS=',' file


问:
Getting error while starting hive
I have no idea what is going on while starting hive in terminal of Ubuntu 17.04, I am getting some error on the terminal. I am new to hive facing some issues with it, can anybody help me on this.

I have (installed and specified in .bashrc file) :

Hadoop : 2.8.0

Hive : 2.1.1

Java : 1.8.0_131

SLF4J: Class path contains multiple SLF4J bindings. SLF4J: Found
  binding in
  [jar:file:/usr/local/src/hive-2.1.1/lib/log4j-slf4j-impl-2.4.1.jar!/org/slf4j/impl/StaticLoggerBinder.class]
  SLF4J: Found binding in
  [jar:file:/usr/local/src/hadoop-2.8.0/share/hadoop/common/lib/slf4j-log4j12-1.7.10.jar!/org/slf4j/impl/StaticLoggerBinder.class]
  SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an
  explanation. SLF4J: Actual binding is of type
  [org.apache.logging.slf4j.Log4jLoggerFactory]

Logging initialized using configuration in
  jar:file:/usr/local/src/hive-2.1.1/lib/hive-common-2.1.1.jar!/hive-log4j2.properties
  Async: true Exception in thread "main" java.lang.RuntimeException:
  org.apache.hadoop.hive.ql.metadata.HiveException:
  java.lang.RuntimeException: Unable to instantiate
  org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient     at
  org.apache.hadoop.hive.ql.session.SessionState.start(SessionState.java:591)
    at
  org.apache.hadoop.hive.ql.session.SessionState.beginStart(SessionState.java:531)
    at org.apache.hadoop.hive.cli.CliDriver.run(CliDriver.java:705)     at
  org.apache.hadoop.hive.cli.CliDriver.main(CliDriver.java:641)     at
  sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)   at
  sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)     at
  org.apache.hadoop.util.RunJar.run(RunJar.java:234)    at
  org.apache.hadoop.util.RunJar.main(RunJar.java:148) Caused by:
  org.apache.hadoop.hive.ql.metadata.HiveException:
  java.lang.RuntimeException: Unable to instantiate
  org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient     at
  org.apache.hadoop.hive.ql.metadata.Hive.registerAllFunctionsOnce(Hive.java:226)
    at org.apache.hadoop.hive.ql.metadata.Hive.(Hive.java:366)    at
  org.apache.hadoop.hive.ql.metadata.Hive.create(Hive.java:310)     at
  org.apache.hadoop.hive.ql.metadata.Hive.getInternal(Hive.java:290)    at
  org.apache.hadoop.hive.ql.metadata.Hive.get(Hive.java:266)    at
  org.apache.hadoop.hive.ql.session.SessionState.start(SessionState.java:558)
    ... 9 more Caused by: java.lang.RuntimeException: Unable to
  instantiate
  org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient     at
  org.apache.hadoop.hive.metastore.MetaStoreUtils.newInstance(MetaStoreUtils.java:1654)
    at
  org.apache.hadoop.hive.metastore.RetryingMetaStoreClient.(RetryingMetaStoreClient.java:80)
    at
  org.apache.hadoop.hive.metastore.RetryingMetaStoreClient.getProxy(RetryingMetaStoreClient.java:130)
    at
  org.apache.hadoop.hive.metastore.RetryingMetaStoreClient.getProxy(RetryingMetaStoreClient.java:101)
    at
  org.apache.hadoop.hive.ql.metadata.Hive.createMetaStoreClient(Hive.java:3367)
    at org.apache.hadoop.hive.ql.metadata.Hive.getMSC(Hive.java:3406)   at
  org.apache.hadoop.hive.ql.metadata.Hive.getMSC(Hive.java:3386)    at
  org.apache.hadoop.hive.ql.metadata.Hive.getAllFunctions(Hive.java:3640)
    at
  org.apache.hadoop.hive.ql.metadata.Hive.reloadFunctions(Hive.java:236)
    at
  org.apache.hadoop.hive.ql.metadata.Hive.registerAllFunctionsOnce(Hive.java:221)
    ... 14 more Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native
  Method)   at
  sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at
  sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at
  org.apache.hadoop.hive.metastore.MetaStoreUtils.newInstance(MetaStoreUtils.java:1652)
    ... 23 more Caused by: MetaException(message:Version information not
  found in metastore. )     at
  org.apache.hadoop.hive.metastore.ObjectStore.checkSchema(ObjectStore.java:7753)
    at
  org.apache.hadoop.hive.metastore.ObjectStore.verifySchema(ObjectStore.java:7731)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  at
  sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)     at
  org.apache.hadoop.hive.metastore.RawStoreProxy.invoke(RawStoreProxy.java:101)
    at com.sun.proxy.$Proxy21.verifySchema(Unknown Source)  at
  org.apache.hadoop.hive.metastore.HiveMetaStore$HMSHandler.getMS(HiveMetaStore.java:565)
    at
  org.apache.hadoop.hive.metastore.HiveMetaStore$HMSHandler.createDefaultDB(HiveMetaStore.java:626)
    at
  org.apache.hadoop.hive.metastore.HiveMetaStore$HMSHandler.init(HiveMetaStore.java:416)
    at
  org.apache.hadoop.hive.metastore.RetryingHMSHandler.(RetryingHMSHandler.java:78)
    at
  org.apache.hadoop.hive.metastore.RetryingHMSHandler.getProxy(RetryingHMSHandler.java:84)
    at
  org.apache.hadoop.hive.metastore.HiveMetaStore.newRetryingHMSHandler(HiveMetaStore.java:6490)
    at
  org.apache.hadoop.hive.metastore.HiveMetaStoreClient.(HiveMetaStoreClient.java:238)
    at
  org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient.(SessionHiveMetaStoreClient.java:70)
    ... 28 more

答:
Hive uses a relational database (Derby, MySQL, Postgresql, etc can be configured) to store its metadata.

Let's see a part of your error message:

```<code>more Caused by: MetaException(message:Version information not found in metastore. ) at org.apache.hadoop.hive.metastore.ObjectStore.checkSchema(ObjectStore.java:7753) at org.apache.hadoop.hive.metastore.ObjectStore.verifySchema(ObjectStore.java:7731)
</code>```

Hive tried to verify that the metastore schema version is compatible with Hive binaries that are going to accesss the metastore. In your case, the versions were not incompatible.
See Hive official documents for more detail.

To get thing work, you can:

1) Find the hive-site.xml file and configure the property hive.metastore.schema.verification is "false" so that metastore to implicitly write the schema version if it's not matching.

2) Use schematool to upgrade the current schema to later version.
See the below link or Cloudera guide.

Title: Getting error while starting hive

Body:
Hive uses a relational database (Derby, MySQL, Postgresql, etc can be configured) to store its metadata.

Let's see a part of your error message:

more Caused by: MetaException(message:Version information not found in metastore. ) at org.apache.hadoop.hive.metastore.ObjectStore.checkSchema(ObjectStore.java:7753) at org.apache.hadoop.hive.metastore.ObjectStore.verifySchema(ObjectStore.java:7731)

Hive tried to verify that the metastore schema version is compatible with Hive binaries that are going to accesss the metastore. In your case, the versions were not incompatible.
See Hive official documents for more detail.

To get thing work, you can:

1) Find the hive-site.xml file and configure the property hive.metastore.schema.verification is "false" so that metastore to implicitly write the schema version if it's not matching.

2) Use schematool to upgrade the current schema to later version.
See the below link or Cloudera guide.


问:
c# getting the right form to show
I have two forms a salaried employee and an hourly employee which has the employees details on it loading from a textfile. In my main form there is a listbox with the names of the employees, once one is clicked, i want to be able to press an edit employee details button on my main form and for the correct form to come up and I am struggling on how to do this. The code for my main form is here:

```<code> public partial class MainForm : Form
 {
// The file used to store employee details
string employeesFile = "employees.txt";

// The collection used to hold the employee data
Employees employees;

public MainForm()
{
    InitializeComponent();
}

private void MainForm_Load(object sender, EventArgs e)
{
    employees = new Employees();
    if (!employees.Load(employeesFile))
    {
        MessageBox.Show("Unable to load employees file");
    }
    else
    {
        PopulateListBox();
    }
}

private void PopulateListBox()
{
    listBoxEmployees.Items.Clear();
    foreach (Employee employee in employees)
    {
        listBoxEmployees.Items.Add(employee.LastName + "," +
employee.FirstName);
    }
    listBoxEmployees.SelectedIndex = 0;
}

private void listBoxEmployees_DoubleClick(object sender, EventArgs e)
{ }

private void buttonEdit_Click(object sender, EventArgs e)
{

}
</code>```

my load method:

```<code>{
public bool Load(string employeesFile)
{
    bool status = false;
    StreamReader inputFile = null;
    string inputLine;

    if (!File.Exists(employeesFile))
    {
        return false;
    }
    try
    {
        inputFile = new StreamReader(employeesFile);
        if (inputFile != null)
        {
            inputLine = inputFile.ReadLine();
            while (inputLine != null)
            {
                Employee employeeEntry =
EmployeeClass.NewEmployee(inputLine);
                if (employeeEntry != null)
                {
                    this.Add(employeeEntry);
                }
                inputLine = inputFile.ReadLine();
            }
            inputFile.Close();
        }
        status = true;
    }
    catch
    {
    }
    return status;
   }
 }
</code>```

the employees class code from the load method:

```<code> public class EmployeeClass
 {
 public static Employee NewEmployee(string employeeData)
 {
    if (employeeData.Length < 1)
    {
        return null;
    }
    switch (employeeData[0])
    {
        case 'S':
           return new SalariedEmployee(employeeData);

        case 'H':
            return new HourlyEmployee(employeeData);

        default:
            return null;
</code>```

the hourly employee form:

```<code>public partial class Hourly_Employee : Form {

HourlyEmployee _employeeEntry;

public Hourly_Employee()
{
  InitializeComponent();
}

public HourlyEmployee employeeEntry
{
    get
    {
        return _employeeEntry;
    }
    set
    {
        _employeeEntry = value;
    }
}

private void Hourly_Employee_Load(object sender, EventArgs e)
{
    textBoxlastName.Text = _employeeEntry.LastName;
    textBoxfirstName.Text = _employeeEntry.FirstName;
    textBoxaddress.Text = _employeeEntry.Address;
    textBoxpostCode.Text = _employeeEntry.PostCode;
    textBoxphoneNumber.Text = _employeeEntry.PhoneNumber;
    dateTimePickerdateOfBirth.Text =
_employeeEntry.DateOfBirth.ToString();
    textBoxhourlyPay.Text = _employeeEntry.HourlyPay.ToString();
    textBoxoverTimePay.Text = _employeeEntry.OvertimePay.ToString();
  }
 }
</code>```

and lastly my salaried employee form:

```<code>public partial class Salary_Employee : Form
{
SalariedEmployee _employeeEntry;

public SalariedEmployee employeeEntry
{
    get
    {
        return _employeeEntry;
    }
    set
    {
        _employeeEntry = value;
    }
}

private void Salary_Employee_Load(object sender, EventArgs e)
{
    textBoxlastName.Text = _employeeEntry.LastName;
    textBoxfirstName.Text = _employeeEntry.FirstName;
    textBoxaddress.Text = _employeeEntry.Address;
    textBoxpostCode.Text = _employeeEntry.PostCode;
    textBoxphoneNumber.Text = _employeeEntry.PhoneNumber;
    dateTimePickerdateOfBirth.Text =
 _employeeEntry.DateOfBirth.ToString();
    textBoxSalary.Text = _employeeEntry.Salary.ToString();
 }
</code>```

any help with this issue would be great!!

答:
The trick is to add the employee objects to the listbox instead of only strings containing the employee names. This allows you to retrieve the selected employee directly from the listbox. Otherwise you would need a way to find the employee object belonging to a name.

Use the type of the selected item to determine the employee type and the employee form.

```<code>private void buttonEdit_Click(object sender, EventArgs e)
{
    // Get the selected employee from the listBox.
    object employee = listBoxEmployees.SelectedItem;

    if (employee != null) { // An employee has been selected.
         // Use the new C# 7.0 switch syntax in order to switch by employee type.
        switch (employee) {
            case SalariedEmployee sEmployee:
                var sfrm = new Salary_Employee(); // Open the salaried employee form..
                sfrm.employeeEntry = sEmployee;
                sfrm.Show();
                break;
            case HourlyEmployee hEmployee:
                var hfrm = new Hourly_Employee(); // Open the hourly employee form.
                hfrm.employeeEntry = hEmployee;
                hfrm.Show();
                break;
        }
    }
}
</code>```

In case you are using an older C# version you can test a type with

```<code>if (employee is SalariedEmployee) {
    var frm = new Salary_Employee();;
    frm.employeeEntry = (SalariedEmployee)employee;
    frm.Show();
} else if (employee is HourlyEmployee) {
    var frm = new Hourly_Employee();
    frm.employeeEntry = (HourlyEmployee)employee;
    frm.Show();
}
</code>```

By default, an object's ToString method returns the name of the object's type. Enable the listbox to display the employees correctly by overriding the ToString method inherited from object in the common base class Employee.

```<code>public class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public override string ToString()
    {
        return LastName + ", " + FirstName;
    }
}
</code>```

Title: c# getting the right form to show

Body:
I have two forms a salaried employee and an hourly employee which has the employees details on it loading from a textfile. In my main form there is a listbox with the names of the employees, once one is clicked, i want to be able to press an edit employee details button on my main form and for the correct form to come up and I am struggling on how to do this. The code for my main form is here:

 public partial class MainForm : Form
 {
// The file used to store employee details
string employeesFile = "employees.txt";

// The collection used to hold the employee data
Employees employees;

public MainForm()
{
    InitializeComponent();
}

private void MainForm_Load(object sender, EventArgs e)
{
    employees = new Employees();
    if (!employees.Load(employeesFile))
    {
        MessageBox.Show("Unable to load employees file");
    }
    else
    {
        PopulateListBox();
    }
}

private void PopulateListBox()
{
    listBoxEmployees.Items.Clear();
    foreach (Employee employee in employees)
    {
        listBoxEmployees.Items.Add(employee.LastName + "," +
employee.FirstName);
    }
    listBoxEmployees.SelectedIndex = 0;
}

private void listBoxEmployees_DoubleClick(object sender, EventArgs e)
{ }

private void buttonEdit_Click(object sender, EventArgs e)
{

}

my load method:

{
public bool Load(string employeesFile)
{
    bool status = false;
    StreamReader inputFile = null;
    string inputLine;

    if (!File.Exists(employeesFile))
    {
        return false;
    }
    try
    {
        inputFile = new StreamReader(employeesFile);
        if (inputFile != null)
        {
            inputLine = inputFile.ReadLine();
            while (inputLine != null)
            {
                Employee employeeEntry =
EmployeeClass.NewEmployee(inputLine);
                if (employeeEntry != null)
                {
                    this.Add(employeeEntry);
                }
                inputLine = inputFile.ReadLine();
            }
            inputFile.Close();
        }
        status = true;
    }
    catch
    {
    }
    return status;
   }
 }

the employees class code from the load method:

 public class EmployeeClass
 {
 public static Employee NewEmployee(string employeeData)
 {
    if (employeeData.Length < 1)
    {
        return null;
    }
    switch (employeeData[0])
    {
        case 'S':
           return new SalariedEmployee(employeeData);

        case 'H':
            return new HourlyEmployee(employeeData);

        default:
            return null;

the hourly employee form:

public partial class Hourly_Employee : Form {

HourlyEmployee _employeeEntry;

public Hourly_Employee()
{
  InitializeComponent();
}

public HourlyEmployee employeeEntry
{
    get
    {
        return _employeeEntry;
    }
    set
    {
        _employeeEntry = value;
    }
}

private void Hourly_Employee_Load(object sender, EventArgs e)
{
    textBoxlastName.Text = _employeeEntry.LastName;
    textBoxfirstName.Text = _employeeEntry.FirstName;
    textBoxaddress.Text = _employeeEntry.Address;
    textBoxpostCode.Text = _employeeEntry.PostCode;
    textBoxphoneNumber.Text = _employeeEntry.PhoneNumber;
    dateTimePickerdateOfBirth.Text =
_employeeEntry.DateOfBirth.ToString();
    textBoxhourlyPay.Text = _employeeEntry.HourlyPay.ToString();
    textBoxoverTimePay.Text = _employeeEntry.OvertimePay.ToString();
  }
 }

and lastly my salaried employee form:

public partial class Salary_Employee : Form
{
SalariedEmployee _employeeEntry;

public SalariedEmployee employeeEntry
{
    get
    {
        return _employeeEntry;
    }
    set
    {
        _employeeEntry = value;
    }
}

private void Salary_Employee_Load(object sender, EventArgs e)
{
    textBoxlastName.Text = _employeeEntry.LastName;
    textBoxfirstName.Text = _employeeEntry.FirstName;
    textBoxaddress.Text = _employeeEntry.Address;
    textBoxpostCode.Text = _employeeEntry.PostCode;
    textBoxphoneNumber.Text = _employeeEntry.PhoneNumber;
    dateTimePickerdateOfBirth.Text =
 _employeeEntry.DateOfBirth.ToString();
    textBoxSalary.Text = _employeeEntry.Salary.ToString();
 }

any help with this issue would be great!!

Body:
The trick is to add the employee objects to the listbox instead of only strings containing the employee names. This allows you to retrieve the selected employee directly from the listbox. Otherwise you would need a way to find the employee object belonging to a name.

Use the type of the selected item to determine the employee type and the employee form.

private void buttonEdit_Click(object sender, EventArgs e)
{
    // Get the selected employee from the listBox.
    object employee = listBoxEmployees.SelectedItem;

    if (employee != null) { // An employee has been selected.
         // Use the new C# 7.0 switch syntax in order to switch by employee type.
        switch (employee) {
            case SalariedEmployee sEmployee:
                var sfrm = new Salary_Employee(); // Open the salaried employee form..
                sfrm.employeeEntry = sEmployee;
                sfrm.Show();
                break;
            case HourlyEmployee hEmployee:
                var hfrm = new Hourly_Employee(); // Open the hourly employee form.
                hfrm.employeeEntry = hEmployee;
                hfrm.Show();
                break;
        }
    }
}

In case you are using an older C# version you can test a type with

if (employee is SalariedEmployee) {
    var frm = new Salary_Employee();;
    frm.employeeEntry = (SalariedEmployee)employee;
    frm.Show();
} else if (employee is HourlyEmployee) {
    var frm = new Hourly_Employee();
    frm.employeeEntry = (HourlyEmployee)employee;
    frm.Show();
}

By default, an object's ToString method returns the name of the object's type. Enable the listbox to display the employees correctly by overriding the ToString method inherited from object in the common base class Employee.

public class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public override string ToString()
    {
        return LastName + ", " + FirstName;
    }
}


问:
PHP variable appended by arbitrarily issuing variable name
I don't know if this is good place to ask such a questions, but I want to understand how PHP variables work. As we all know that we can add a variable to another variable like this:

```<code>$abc = "Some Text"
$ab_apnd = "{$abc} missing*";
echo $ab_apnd;
</code>```

Then this will show output like:

Some Text missing*

But the question here is when I pass the same text over $_POST it doesn't work.

```<code># $_POST['abc'] = "{$abc}" // through a form not from php code //
$abc = "Some Text";
$ab_apnd = $_POST['abc'] . " missing*";
echo $ab_apnd;
</code>```

Now this will show an output like this:

{abc} missing*;

I will be thankful if you teach me why this happens! Thank you.

答:
I guess you want to use a variable value as a variable name. You can use eval function for this. </p>

```<code><form action="" method=post>
   <input type='text' name="abc">
   <input type="submit">
</form>

<?php
  $abc = "Some Text";
  eval('$ab_apnd ="' . $_POST['abc'] . ' missing*";');
  echo $ab_apnd;
?>
</code>```

Body:
I don't know if this is good place to ask such a questions, but I want to understand how PHP variables work. As we all know that we can add a variable to another variable like this:

$abc = "Some Text"
$ab_apnd = "{$abc} missing*";
echo $ab_apnd;

Then this will show output like:

Some Text missing*

But the question here is when I pass the same text over $_POST it doesn't work.

# $_POST['abc'] = "{$abc}" // through a form not from php code //
$abc = "Some Text";
$ab_apnd = $_POST['abc'] . " missing*";
echo $ab_apnd;

Now this will show an output like this:

{abc} missing*;

I will be thankful if you teach me why this happens! Thank you.

Body:
I guess you want to use a variable value as a variable name. You can use eval function for this.

<form action="" method=post>
   <input type='text' name="abc">
   <input type="submit">
</form>

<?php
  $abc = "Some Text";
  eval('$ab_apnd ="' . $_POST['abc'] . ' missing*";');
  echo $ab_apnd;
?>


问:
ngShow not hiding view when argument is updated to false
I am trying to hide a part of my view after 3 secs with $timeout, but for some weird reasons this is not happening although the $scope value is updating.

```<code>$scope.failed = true;
$scope.des = res.data.description;
$timeout(function(){
   $scope.failed = false;
   $scope.loading = false;
   $scope.des = null;
   console.log($scope.failed);
}, 2000);
</code>```

The template

```<code><div class="done failed" ng-show="failed">
   <i class="material-icons">error_outline</i>
   <p>{{des}}</p>
</div>
</code>```

答:
Try this:

```<code>$scope.status = {failed: true};
$scope.des = res.data.description;
$timeout(function(){
   $scope.status.failed = false;
   $scope.loading = false;
   $scope.des = null;
   console.log($scope.status.failed);
}, 2000);
</code>```

The template

```<code><div class="done failed" ng-show="status.failed">
   <i class="material-icons">error_outline</i>
   <p>{{des}}</p>
</div>
</code>```

Body:
I am trying to hide a part of my view after 3 secs with $timeout, but for some weird reasons this is not happening although the $scope value is updating.

$scope.failed = true;
$scope.des = res.data.description;
$timeout(function(){
   $scope.failed = false;
   $scope.loading = false;
   $scope.des = null;
   console.log($scope.failed);
}, 2000);

The template

   error_outline

{{des}}

Body:
Try this:

$scope.status = {failed: true};
$scope.des = res.data.description;
$timeout(function(){
   $scope.status.failed = false;
   $scope.loading = false;
   $scope.des = null;
   console.log($scope.status.failed);
}, 2000);

The template

<div class="done failed" ng-show="status.failed">
   <i class="material-icons">error_outline</i>
   <p>{{des}}</p>
</div>


问:
How can I view how much time each cell took to run in a Jupyter notebook?
After I select run all, run all above, or run all below in a Jupyter notebook, how can I view how much time each cell took to run?

My question is different from Simple way to measure cell execution time in ipython notebook as I want the running times for all cells, not just one. I.e., if the notebook contains 10 cells I want 10 running times.

答: I believe only by putting magic function %%time


问:
ArrayList for Audio player cannot convert to Int
So I followed a tutorial for an AudioPlayer for part an App I am making, however I am coming across this error:

Error:(30, 43) error: incompatible types: String cannot be converted to int

Here are the code sections:

```<code>playAudio(audioList.get(0).getData());
</code>```

This calls the following Method:

```<code>private void playAudio(int audioIndex) {
    //Check is service is active
    if (!serviceBound) {
        //Store Serializable audioList to SharedPreferences
        StorageUtil storage = new StorageUtil(getApplicationContext());
        storage.storeAudio(audioList);
        storage.storeAudioIndex(audioIndex);

        Intent playerIntent = new Intent(this, MediaPlayerService.class);
        startService(playerIntent);
        bindService(playerIntent, serviceConnection, Context.BIND_AUTO_CREATE);
    } else {
        //Store the new audioIndex to SharedPreferences
        StorageUtil storage = new StorageUtil(getApplicationContext());
        storage.storeAudioIndex(audioIndex);

        //Service is active
        //Send a broadcast to the service -> PLAY_NEW_AUDIO
        Intent broadcastIntent = new Intent(Broadcast_PLAY_NEW_AUDIO);
        sendBroadcast(broadcastIntent);
    }
}
</code>```

If I change it from int audioIndex to String audioIndex, it causes errors in other parts of the code where the storage is held.

What am I missing?

答:
The fact that a string is not a number, even when it only contains digits.

Simply use a conversion method such as Integer.valueOf() to convert the string before passing.

Where the real answer is: spend quite some time on studying the basics of Java. Don't get me wrong, but when you don't know about such super simple things, you are far away from doing android development.

Body:
So I followed a tutorial for an AudioPlayer for part an App I am making, however I am coming across this error:

Error:(30, 43) error: incompatible types: String cannot be converted to int

Here are the code sections:

playAudio(audioList.get(0).getData());

This calls the following Method:

private void playAudio(int audioIndex) {
    //Check is service is active
    if (!serviceBound) {
        //Store Serializable audioList to SharedPreferences
        StorageUtil storage = new StorageUtil(getApplicationContext());
        storage.storeAudio(audioList);
        storage.storeAudioIndex(audioIndex);

        Intent playerIntent = new Intent(this, MediaPlayerService.class);
        startService(playerIntent);
        bindService(playerIntent, serviceConnection, Context.BIND_AUTO_CREATE);
    } else {
        //Store the new audioIndex to SharedPreferences
        StorageUtil storage = new StorageUtil(getApplicationContext());
        storage.storeAudioIndex(audioIndex);

        //Service is active
        //Send a broadcast to the service -> PLAY_NEW_AUDIO
        Intent broadcastIntent = new Intent(Broadcast_PLAY_NEW_AUDIO);
        sendBroadcast(broadcastIntent);
    }
}

If I change it from int audioIndex to String audioIndex, it causes errors in other parts of the code where the storage is held.

What am I missing?


问:
Choose a path depending on relationship property on neo4j?
All my nodes are 'Places' with only the 'name' property, and I have different relationships named A, B and C, each one of them has a 'cost' property.

If I am at the first node, connected to the second one, I want to 'take' the relationship with the lower cost.

For example:

```<code>MATCH (p1:Place{name: place1})
MATCH (p2:Place{name: place2})

MERGE (place1)-[:A{cost: "10"}]->(place2)
MERGE (place1)-[:B{cost: "5"}]->(place2)
MERGE (place1)-[:C{cost: "20"}]->(place2)
</code>```

What Ii want to do, is take (in this case) the relationship B

The costs of the relationships are always the same for the name each one of them (A always costs 10, and B always 5) so maybe it will not be necessary to put the cost property to it).

the best solution is to do it with a query or list the paths and select the best one with java?

Depending on that, how can I do it? and what it would be the query?

答:
There's a few ways you can do this.

For few nodes and few relationships, it should be easy enough to order the relationships by cost and grab the first one:

```<code>...
MATCH path=(:Place{name: place1})-[r]-(:Place{name: place2})
WITH path, r
ORDER BY r.cost ASC
LIMIT 1
RETURN path
</code>```

If this is for a more complex operation, such as calculating a path of least cost between nodes, then this turns into a weighted shortest path query, and you might want to look into solutions using Dijkstra's algorithm. APOC Procedures has an implementation you might use.

Body:
All my nodes are 'Places' with only the 'name' property, and I have different relationships named A, B and C, each one of them has a 'cost' property.

If I am at the first node, connected to the second one, I want to 'take' the relationship with the lower cost.

For example:

MATCH (p1:Place{name: place1})
MATCH (p2:Place{name: place2})

MERGE (place1)-[:A{cost: "10"}]->(place2)
MERGE (place1)-[:B{cost: "5"}]->(place2)
MERGE (place1)-[:C{cost: "20"}]->(place2)

What Ii want to do, is take (in this case) the relationship B

The costs of the relationships are always the same for the name each one of them (A always costs 10, and B always 5) so maybe it will not be necessary to put the cost property to it).

the best solution is to do it with a query or list the paths and select the best one with java?

Depending on that, how can I do it? and what it would be the query?

Body:
There's a few ways you can do this.

For few nodes and few relationships, it should be easy enough to order the relationships by cost and grab the first one:

...
MATCH path=(:Place{name: place1})-[r]-(:Place{name: place2})
WITH path, r
ORDER BY r.cost ASC
LIMIT 1
RETURN path

If this is for a more complex operation, such as calculating a path of least cost between nodes, then this turns into a weighted shortest path query, and you might want to look into solutions using Dijkstra's algorithm. APOC Procedures has an implementation you might use.


问:
.NET CF Application and Out of Memory Exception
I am developing a .NET CF 3.5 network game. My issue is the app loads all the resources at first instance. However upon subsequent launches, the app gives me memory out of exception while loading resources especially sounds or big images.

Please guide me

答:
Based on experience in programming with .NET CF, you are exposed to memory constraints and the garbage collection is not as would be expected in a normal desktop/PC environment.

In my application, by always calling the Close() and Dispose() methods before objects went out of scope solved the issues I faced with out of memory exceptions.

If you still have problems, another way to try this is to hook onto the application closing event handler and call GC.Collect(). This will force the garbage collector to immediately collect all unused or disposed objects.

OwnerDisplayName: Cronos


问:
Start Jetty application but "java.lang.IllegalStateException: Duplicate fragment name"
Sorry if duplicated.

I am using gradle to build my .war file and start my application using Jetty. But I see this error message

```<code>java.lang.IllegalStateException: Duplicate fragment name: spring_web for jar:file:/private/var/folders/r7/z7yqbhx10wl9kyw738crggdd0zwztx/T/jetty-0.0.0.0-8080-application-1.0.war-_pplication-1.0-any-/webapp/WEB-INF/lib/spring-web-4.1.9.RELEASE.jar!/META-INF/web-fragment.xml and jar:file:/private/var/folders/r7/z7yqbhx10wl9kyw738crggdd0zwztx/T/jetty-0.0.0.0-8080-cpplication-1.0.war-_pplication-1.0-any-/webapp/WEB-INF/lib/spring-web-4.1.9.RELEASE.jar!/META-INF/web-fragment.xml
</code>```

I already did some research on internet, but all are talking about jetty-maven-plugin and the solution is to add "<allowDuplicateFragmentNames>true</allowDuplicateFragmentNames>" to webAppConfig. But in my application I don't have webAppConfig. Is this only for Maven? How to solve this if I am using Gradle?

Thanks!

答:
you can put jetty.xml under WEB-INF

jetty.xml

```<code><?xml version="1.0"  encoding="UTF-8"?>
<!DOCTYPE Configure PUBLIC
    "-//Mort Bay Consulting//DTD Configure//EN"
    "http://www.eclipse.org/jetty/configure_9_0.dtd">

<Configure class="org.eclipse.jetty.webapp.WebAppContext">
  <Set name="allowDuplicateFragmentNames">true</Set>
</Configure>
</code>```

In your WEB-INF/web.xml, look for the  tag (should be at the top), and modify atributes to match these values:

```<code><web-app version="3.0" xmlns="http://java.sun.com/xml/ns/j2ee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
metadata-complete="true"
..
>
</code>```

Body:
Sorry if duplicated.

I am using gradle to build my .war file and start my application using Jetty. But I see this error message

java.lang.IllegalStateException: Duplicate fragment name: spring_web for jar:file:/private/var/folders/r7/z7yqbhx10wl9kyw738crggdd0zwztx/T/jetty-0.0.0.0-8080-application-1.0.war-_pplication-1.0-any-/webapp/WEB-INF/lib/spring-web-4.1.9.RELEASE.jar!/META-INF/web-fragment.xml and jar:file:/private/var/folders/r7/z7yqbhx10wl9kyw738crggdd0zwztx/T/jetty-0.0.0.0-8080-cpplication-1.0.war-_pplication-1.0-any-/webapp/WEB-INF/lib/spring-web-4.1.9.RELEASE.jar!/META-INF/web-fragment.xml

I already did some research on internet, but all are talking about jetty-maven-plugin and the solution is to add "<allowDuplicateFragmentNames>true</allowDuplicateFragmentNames>" to webAppConfig. But in my application I don't have webAppConfig. Is this only for Maven? How to solve this if I am using Gradle?

Thanks!

Body:
you can put jetty.xml under WEB-INF

jetty.xml

<?xml version="1.0"  encoding="UTF-8"?>
<!DOCTYPE Configure PUBLIC
    "-//Mort Bay Consulting//DTD Configure//EN"
    "http://www.eclipse.org/jetty/configure_9_0.dtd">

<Configure class="org.eclipse.jetty.webapp.WebAppContext">
  <Set name="allowDuplicateFragmentNames">true</Set>
</Configure>

In your WEB-INF/web.xml, look for the  tag (should be at the top), and modify atributes to match these values:

<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/j2ee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
metadata-complete="true"
..
>


问:
When creating game object position is wrong when set
This is my code

```<code>GameObject tocreate = new GameObject ("newsstory1");
    tocreate.AddComponent<SpriteRenderer> ();
    tocreate.GetComponent<SpriteRenderer> ().sprite = newsbuilten;

    tocreate.transform.parent = notifcationparents.transform;
    tocreate.transform.localScale = new Vector3 (6, 6, 0);
    tocreate.transform.position = new Vector3 (80, 18 ,5);
</code>```

My problem is when I run this the game object is in the wrong position; here is the image

答:
This is normal. Don't worry about the position you see in the Editor. It is happening because you are setting the parent GameObject.

Let's say that the parent Object(notifcationparents) is at the position of:

5, 10, 30

Then you create a new GameObject named "newsstory1" and set its position to:

80, 18, 5

That new GameObject will move to that position but you will see:

75, 8, -25

as its position in the Editor because that's what (80, 18, 5) -- (5, 10, 30) is. You are just seeing a position relative to its parent GameObject. That wouldn't happen if there is no parent GameObject.

Body:
This is my code

GameObject tocreate = new GameObject ("newsstory1");
    tocreate.AddComponent<SpriteRenderer> ();
    tocreate.GetComponent<SpriteRenderer> ().sprite = newsbuilten;

    tocreate.transform.parent = notifcationparents.transform;
    tocreate.transform.localScale = new Vector3 (6, 6, 0);
    tocreate.transform.position = new Vector3 (80, 18 ,5);

My problem is when I run this the game object is in the wrong position; here is the image


问:
How the LLVM handle the debug location information of continue keyword and right brace?
Let me show you the following simple C code:

```<code>int main()
{
  int i;

  for (i = 0; i < 256; i++)
  {
      i++;
  }
}
</code>```

In this simple C code, if we use Clang to compile it and debug it:
We will get something like this:

```<code>(gdb) b main
Breakpoint 1 at 0x100000f7b: file a.c, line 5.
(gdb) r
Starting program: a.out
[New Thread 0x1403 of process 23435]
warning: unhandled dyld version (15)

Thread 2 hit Breakpoint 1, main () at a.c:5
5     for (i = 0; i < 256; i++)
(gdb) n
7         i++;
(gdb)
5     for (i = 0; i < 256; i++)
(gdb)
7         i++;
</code>```

That is to say, the right brace of location LLVM doesn't emit. However if we have the continue keyword:

```<code>int main()
{
  int i;

  for (i = 0; i < 256; i++)
  {
    continue;
    i++;
  }
}
</code>```

Then we compile and debug it:

```<code>Thread 2 hit Breakpoint 1, main () at a.c:5
5     for (i = 0; i < 256; i++)
(gdb) n
7       continue;
(gdb)
5     for (i = 0; i < 256; i++)
(gdb)
7       continue;
(gdb)
5     for (i = 0; i < 256; i++)
(gdb)
7       continue;
</code>```

We will stop the line of continue. But if we compare the LLVM IR between them:

The right brace and continue keyword both are the following the br instruction and !dbg !23. Except that the line number of !dbg !23 not the same.

; :6:                                      ; preds = %3
  br label %7, !dbg !23

The question is how LLVM know whether to generate the debug location(generate for the continue keyword line, but not for the loop's right brace)? Because they are the same instruction and others are the same.

答:
The brace is just a syntactic scope, there is no difference for the compiler between:

```<code>for (i = 0; i < 256; i++)
{
  i++;
}
</code>```

and

```<code>for (i = 0; i < 256; i++)
  i++;
</code>```

The parser is using the scope you create to group statement together, but this will not appear in the LLVM IR. The LLVM IR represent more the instructions that the program needs to execute.

When you using n in a debugger, you are asking to continue executing the program until you reach an instruction that corresponds to a different source line. The brace does not correspond to any instruction in the executable.

Body:
Let me show you the following simple C code:

int main()
{
  int i;

  for (i = 0; i < 256; i++)
  {
      i++;
  }
}

In this simple C code, if we use Clang to compile it and debug it:
We will get something like this:

(gdb) b main
Breakpoint 1 at 0x100000f7b: file a.c, line 5.
(gdb) r
Starting program: a.out
[New Thread 0x1403 of process 23435]
warning: unhandled dyld version (15)

Thread 2 hit Breakpoint 1, main () at a.c:5
5     for (i = 0; i < 256; i++)
(gdb) n
7         i++;
(gdb)
5     for (i = 0; i < 256; i++)
(gdb)
7         i++;

That is to say, the right brace of location LLVM doesn't emit. However if we have the continue keyword:

int main()
{
  int i;

  for (i = 0; i < 256; i++)
  {
    continue;
    i++;
  }
}

Then we compile and debug it:

Thread 2 hit Breakpoint 1, main () at a.c:5
5     for (i = 0; i < 256; i++)
(gdb) n
7       continue;
(gdb)
5     for (i = 0; i < 256; i++)
(gdb)
7       continue;
(gdb)
5     for (i = 0; i < 256; i++)
(gdb)
7       continue;

We will stop the line of continue. But if we compare the LLVM IR between them:

The right brace and continue keyword both are the following the br instruction and !dbg !23. Except that the line number of !dbg !23 not the same.

; :6:                                      ; preds = %3
  br label %7, !dbg !23

The question is how LLVM know whether to generate the debug location(generate for the continue keyword line, but not for the loop's right brace)? Because they are the same instruction and others are the same.

Body:
The brace is just a syntactic scope, there is no difference for the compiler between:

for (i = 0; i < 256; i++)
{
  i++;
}

and

for (i = 0; i < 256; i++)
  i++;

The parser is using the scope you create to group statement together, but this will not appear in the LLVM IR. The LLVM IR represent more the instructions that the program needs to execute.

When you using n in a debugger, you are asking to continue executing the program until you reach an instruction that corresponds to a different source line. The brace does not correspond to any instruction in the executable.


问:
Reliably waiting for page to load 2
How completely detect when awesomium browser end rendering the page? I try use this code, but its not correct detect it. In SO i can't find answer.</p>

```<code>bool LoadingFinished;

    Wb.LoadingFrameComplete += WbLoadingFrameCompleted;
    ...

void WbLoadingFrameCompleted(object sender, FrameEventArgs e)
{
    if (!e.IsMainFrame)
        return;

    LoadingFinished = true;
}

void LoadUrl(string url)
{
    LoadingFinished = false;

    Wb.Source = new Uri(url);

    while (!LoadingFinished)
    {
        Thread.Sleep(100);
        WebCore.Update();
    }
}
</code>```

答:
Try this code after changing url:</p>

```<code>while (!webControl.IsDocumentReady)
{
    Thread.Sleep(100);
}
</code>```

Title: Reliably waiting for page to load 2

Body:
How completely detect when awesomium browser end rendering the page? I try use this code, but its not correct detect it. In SO i can't find answer.

bool LoadingFinished;

    Wb.LoadingFrameComplete += WbLoadingFrameCompleted;
    ...

void WbLoadingFrameCompleted(object sender, FrameEventArgs e)
{
    if (!e.IsMainFrame)
        return;

    LoadingFinished = true;
}

void LoadUrl(string url)
{
    LoadingFinished = false;

    Wb.Source = new Uri(url);

    while (!LoadingFinished)
    {
        Thread.Sleep(100);
        WebCore.Update();
    }
}

Body:
Try this code after changing url:

while (!webControl.IsDocumentReady)
{
    Thread.Sleep(100);
}


问:
C# WPF Multiple Panels in App - how to do that
I'm pretty new to WPF/XAML in C#, I saw some simple tutorials and stuff but, today I'm confused, never used to make UI there.

I need to output multiple forms which instance would look something like that:

(NB: I constructed it just in WYSIWG way, so XAML markup is total mess, it for screenshot. I cant even add table directly in grid, oh)

I got data like this for each month in schoolyear, so, depends on what class is choosen I want it to output like that (scheme)

(NB: instead of each CustomWindowInstance there I need my form from 1 st screenshot)

So, whats is best and simplies approach for that?

答:
EDIT 1: I'll name XAML from the first screenshot, which represents controls you want to display multiple times, XAML 1, and another one, where you want to do it, XAML 2.

--

Almost ORIGINAL:
Create a separate User Control and move the content of Window tag from XAML 1 into it. Then you'll be able to show it as many times as you want by placing <yourUserControlNamespace:YourUserControlClass /> in XAML 2.

For an ability of communication with this control in XAML like <yourUserControlNamespace:YourUserControlClass Parameter="SomethingHere" /> you should implement a dependency property with name ParameterProperty (desired name of property in XAML + "Property") in YourUserControlClass.xaml.cs.

--

EDIT 2: One may also create a DataTemplate with parameter DataType={x:Type yourVMNamespace:YourVMClass} for the XAML 1's ViewModel (not View) in XAML 2's or the whole application's Resources. In that case the ViewModel class you are binding to will be represented by the DataTemplate's content itself. Later you can write <yourVMNamespace:YourVMClass /> as in the first solution.

This approach allows displaying rich representation of any items themselves, for example, in controls derived from ItemsControl, such as ListBox, all you've got to do is to bind ListBox's ItemsSource property to a collection of YourVMClass instances (or specify them in XAML by hand).

More precisely, in this case I won't call YourVMClass a ViewModel.


问:
Parsing a date in ColdFusion
I have a date stored in the format dd-mm-yyyy. I want to store the day, date and year as individual variables, while getting rid of any leading zeros (e.g. "09-09-2010" is stored as 9, 9, 2010).

I attempted to use the code on this page to split the date by dashes, but it is throwing expression errors.

答:
If you're working with a string in that format, there's no need for regular expressions.

```<code>myDate = "13-12-2010";
theDay = listGetAt(myDate,1,"-");
theMonth = listGetAt(myDate,2,"-");
theYear = listGetAt(myDate,3,"-");
</code>```

Using the val() function will also drop leading zeroes, if any.

Title: Parsing a date in ColdFusion

Body:
If you're working with a string in that format, there's no need for regular expressions.

myDate = "13-12-2010";
theDay = listGetAt(myDate,1,"-");
theMonth = listGetAt(myDate,2,"-");
theYear = listGetAt(myDate,3,"-");

Using the val() function will also drop leading zeroes, if any.