问:
perform event-sourcing projections over table storage
I'm creating a tiny event-sourcing-style function app, where every invocation of a function will write an event to table storage. An example of such an event would be:

```<code>+------------+---------------+-----------------+
|   Event    |   Timestamp   |   Destination   |
+------------+---------------+-----------------+
| Connect    | 7/1/2019 4:52 | sftp.alex.com   |
| Disconnect | 7/1/2019 4:53 | sftp.liza.com   |
| Connect    | 7/1/2019 4:54 | sftp.yomama.com |
| Connect    | 7/1/2019 4:54 | sftp.alex.com   |
| Connect    | 7/1/2019 4:59 | sftp.liza.com   |
| Disconnect | 7/1/2019 4:59 | sftp.alex.com   |
| Disconnect | 7/1/2019 4:59 | sftp.yomama.com |
| Connect    | 7/1/2019 5:03 | sftp.alex.com   |
+------------+---------------+-----------------+
</code>```

How do I create a projection over this table?

The main question that I would need to answer is:

How many connections does each destination currently have?

答:
I suppose there would be a lot of records in the table and iterating over all of them is not an option.

So here is a couple of ideas:

Can't you just keep track of number of connections?

That would be the easiest solution. I have no idea about your app and how it communicates with Azure, but at least there're triggers (although, judging by the supported bindings table, you will need to use some extra services... like for example Queue storage). And in them you should be able to store a current number of connections to each destination in a separate table, incrementing on Connect event and decrementing on Disconnect.

But in case if you have a single writer (a single server that communicates with Azure) you can keep track of connections right inside your code.

Also you can save the current number of connections to the table in an extra field. As a bonus, you'll be able to instantly get a number of connections at any given time in the past (at a memory cost).

As you're talking about event-sourcing... then maybe you should use it once more? Idea is still the same: you keep track of Connect and Disconnect events but in some external receiver. As your're writing event-sourcing-style function app I believe it should be easy to create one. And you won't have to depend on extra Azure services.

Then the only difference from the first idea is that if the receiver dies or disconnects or something - just remember the last events it received and, when the receiver is back online, iterate only over the younger ones.

This last received event that you should remember (plus the counters) is essentially the snapshot others were talking in the comments.

Body:
I'm creating a tiny event-sourcing-style function app, where every invocation of a function will write an event to table storage. An example of such an event would be:

+------------+---------------+-----------------+
|   Event    |   Timestamp   |   Destination   |
+------------+---------------+-----------------+
| Connect    | 7/1/2019 4:52 | sftp.alex.com   |
| Disconnect | 7/1/2019 4:53 | sftp.liza.com   |
| Connect    | 7/1/2019 4:54 | sftp.yomama.com |
| Connect    | 7/1/2019 4:54 | sftp.alex.com   |
| Connect    | 7/1/2019 4:59 | sftp.liza.com   |
| Disconnect | 7/1/2019 4:59 | sftp.alex.com   |
| Disconnect | 7/1/2019 4:59 | sftp.yomama.com |
| Connect    | 7/1/2019 5:03 | sftp.alex.com   |
+------------+---------------+-----------------+

How do I create a projection over this table?

The main question that I would need to answer is:

How many connections does each destination currently have?


来源: stackexchange

问:
How to get highlighted text of UITextView in UITableViewCell?
I have a custom cell (subclass of UITableViewCell) with a textView inside of it. It works great! Now, when I tap on a cell and highlight some text, the default UIMenuController appears and I can choose to copy the highlighted text. Also this function works perfectly. Now, I would like to add a custom button to the UIMenuController, which I actually did, but to perform the menu item action I need to know what the selected text is. How can I get it?</p>

答:
To explain this better, there is no method in UITextField that allows us to know what the currently selected text is. But we can leverage the copy action on the text field that is associated with the menu controller. The copy action copies the text onto the pasteboard which we will need to retrieve. I was able to implement a Log function in my custom subclass of UITextField like this –

```<code>- (void)log:(id)sender {
    [self copy:sender];
    NSString *highlightedText = [UIPasteboard generalPasteboard].string;
    NSLog(@"%@", highlightedText);
}
</code>```

This logs the selected text onto the console. Doesn't do much but gives you the basic idea.

ContentLicense: CC BY-SA 3.0

Body:
To explain this better, there is no method in UITextField that allows us to know what the currently selected text is. But we can leverage the copy action on the text field that is associated with the menu controller. The copy action copies the text onto the pasteboard which we will need to retrieve. I was able to implement a Log function in my custom subclass of UITextField like this –

- (void)log:(id)sender {
    [self copy:sender];
    NSString *highlightedText = [UIPasteboard generalPasteboard].string;
    NSLog(@"%@", highlightedText);
}

This logs the selected text onto the console. Doesn't do much but gives you the basic idea.


问:
Search for every value from one array in another array in Javascript
Please, I need your help.
I have array of a date range:

```<code>dateRange = [1 Jun 2020, 2 Jun 2020, 3 Jun 2020, 4 Jun 2020, 5 Jun 2020];
</code>```

and an array of offers:

```<code>offers = [
{DeskUID: "B200B3", Day: 1 Jun 2020}
{DeskUID: "B200B3", Day: 2 Jun 2020}
{DeskUID: "B200B3", Day: 3 Jun 2020}
{DeskUID: "B200B3", Day: 4 Jun 2020}
{DeskUID: "B200B3", Day: 5 Jun 2020}
{DeskUID: "B211B5", Day: 3 Jun 2020}
{DeskUID: "B211B5", Day: 4 Jun 2020}
]
</code>```

How to create a result array where will be just offers from offers array which have entries for every single day in the dateRange array?

```<code>result = [
{DeskUID: "B200B3", Day: 1 Jun 2020}
{DeskUID: "B200B3", Day: 2 Jun 2020}
{DeskUID: "B200B3", Day: 3 Jun 2020}
{DeskUID: "B200B3", Day: 4 Jun 2020}
{DeskUID: "B200B3", Day: 5 Jun 2020}
]
</code>```

The solution has to work in IE11 - no arrow functions,...

EDIT:
If I have offers array like the below, your function gives me wrong results.

```<code>dateRange = ['1 Jun 2020', '2 Jun 2020', '3 Jun 2020']

offers = [
    {DeskUID: "B201A10", Day: '1 Jun 2020'}
    {DeskUID: "B201A10", Day: '2 Jun 2020'}
    {DeskUID: "B211A15", Day: '1 Jun 2020'}
    {DeskUID: "B211A15", Day: '2 Jun 2020'}
    {DeskUID: "B211A15", Day: '3 Jun 2020'}
    ]

result = [
    {DeskUID: "B201A10", Day: '1 Jun 2020'}
    {DeskUID: "B201A10", Day: '2 Jun 2020'}
    {DeskUID: "B211A15", Day: '3 Jun 2020'}
    ]

expected result = [
    {DeskUID: "B201A15", Day: '1 Jun 2020'}
    {DeskUID: "B201A15", Day: '2 Jun 2020'}
    {DeskUID: "B201A15", Day: '3 Jun 2020'}
    ]
</code>```

答:
Uses a Set() to keep track of found Day matches, and return the DeskUID Days that contains all matches.  You also haven't made clear if you want to only match if the offers contains exactly only those Days or just needs to include them.

You didn't state what to do with dupes, so I'm just including them if you want non-matches included, and excluding if you only want matches.

dateRangeArray = ['1 Jun 2020', '2 Jun 2020', '3 Jun 2020']

offers = [{
  DeskUID: "B201A10",
  Day: '30 May 2020'
},{
  DeskUID: "B201A10",
  Day: '1 Jun 2020'
}, {
  DeskUID: "B201A10",
  Day: '2 Jun 2020'
}, {
  DeskUID: "B211A15",
  Day: '1 Jun 2020'
}, {
  DeskUID: "B211A15",
  Day: '2 Jun 2020'
}, {
  DeskUID: "B211A15",
  Day: '3 Jun 2020'
}, {
  DeskUID: "B211A15",
  Day: '4 Jun 2020'
}, {
  DeskUID: "B211A15",
  Day: '3 Jun 2020'
}]

// include non-match Day but match DeskUID contains all Day
var dateRange = new Set()
// Set() constructor is buggy under IE11
dateRangeArray.forEach(function(x){dateRange.add(x)})
var result = [], acc = {};
for(var i = 0; i < offers.length; i++) {
  var offer = offers[i]
  var days = acc[offer.DeskUID] = acc[offer.DeskUID] || [new Set(),[]]
  days[1].push(offer)
  if(dateRange.has(offer.Day)) {
    days[0].add(offer.Day)
  }
  if (days[0].size === dateRange.size) result = days[1]
}

console.log("include non-match Days:" + JSON.stringify(result));

// include only matches Day and exclude dupes
var dateRange = new Set()
// Set() constructor is buggy under IE11
dateRangeArray.forEach(function(x){dateRange.add(x)})
var result = [], acc = {};
for(var i = 0; i < offers.length; i++) {
  var offer = offers[i]
  var days = acc[offer.DeskUID] = acc[offer.DeskUID] || [new Set(),[]]
  if(dateRange.has(offer.Day) && !days[0].has(offer.Day)) {
    days[1].push(offer)
  }
  if(dateRange.has(offer.Day)) {
    days[0].add(offer.Day)
  }
  if (days[0].size === dateRange.size) result = days[1]
}

console.log("include only match Days no dupes:" + JSON.stringify(result));```

ContentLicense: CC BY-SA 4.0

Body:
Please, I need your help.
I have array of a date range:

dateRange = [1 Jun 2020, 2 Jun 2020, 3 Jun 2020, 4 Jun 2020, 5 Jun 2020];

and an array of offers:

offers = [
{DeskUID: "B200B3", Day: 1 Jun 2020}
{DeskUID: "B200B3", Day: 2 Jun 2020}
{DeskUID: "B200B3", Day: 3 Jun 2020}
{DeskUID: "B200B3", Day: 4 Jun 2020}
{DeskUID: "B200B3", Day: 5 Jun 2020}
{DeskUID: "B211B5", Day: 3 Jun 2020}
{DeskUID: "B211B5", Day: 4 Jun 2020}
]

How to create a result array where will be just offers from offers array which have entries for every single day in the dateRange array?

result = [
{DeskUID: "B200B3", Day: 1 Jun 2020}
{DeskUID: "B200B3", Day: 2 Jun 2020}
{DeskUID: "B200B3", Day: 3 Jun 2020}
{DeskUID: "B200B3", Day: 4 Jun 2020}
{DeskUID: "B200B3", Day: 5 Jun 2020}
]

The solution has to work in IE11 - no arrow functions,...

EDIT:
If I have offers array like the below, your function gives me wrong results.

dateRange = ['1 Jun 2020', '2 Jun 2020', '3 Jun 2020']

offers = [
    {DeskUID: "B201A10", Day: '1 Jun 2020'}
    {DeskUID: "B201A10", Day: '2 Jun 2020'}
    {DeskUID: "B211A15", Day: '1 Jun 2020'}
    {DeskUID: "B211A15", Day: '2 Jun 2020'}
    {DeskUID: "B211A15", Day: '3 Jun 2020'}
    ]

result = [
    {DeskUID: "B201A10", Day: '1 Jun 2020'}
    {DeskUID: "B201A10", Day: '2 Jun 2020'}
    {DeskUID: "B211A15", Day: '3 Jun 2020'}
    ]

expected result = [
    {DeskUID: "B201A15", Day: '1 Jun 2020'}
    {DeskUID: "B201A15", Day: '2 Jun 2020'}
    {DeskUID: "B201A15", Day: '3 Jun 2020'}
    ]


问:
How to set the type for a non-standard gstreamer property?
I'm attempting to set the pattern property for the videotestsrc. Following the normal logic, I have tried setting the variable as an i32 and a string. Both fail with an error that asks for a specific type.

Looking in the gstreamer API, I could not see a way to set the property.

How do you force the type of a variable to match the expected?

```<code>let pattern = "snow";
src.set_property("pattern", &pattern)
    .expect("setting pattern error");
</code>```

error message

thread 'main' panicked at 'setting pattern error: BoolError { message: "property \'pattern\' of type \'GstVideoTestSrc\' can\'t be set from the given type (expected: \'GstVideoTestSrcPattern\', got: \'gchararray\')",
```

答:
You can set it by string via src.set_property_from_str("snow").

Alternatively you can use the glib::EnumClass API to get all the possible values for the type. You can get the type via src.find_property("pattern") and then get_value_type() on it.

Body:
I'm attempting to set the pattern property for the videotestsrc. Following the normal logic, I have tried setting the variable as an i32 and a string. Both fail with an error that asks for a specific type.

Looking in the gstreamer API, I could not see a way to set the property.

How do you force the type of a variable to match the expected?

let pattern = "snow";
src.set_property("pattern", &pattern)
    .expect("setting pattern error");

error message

thread 'main' panicked at 'setting pattern error: BoolError { message: "property \'pattern\' of type \'GstVideoTestSrc\' can\'t be set from the given type (expected: \'GstVideoTestSrcPattern\', got: \'gchararray\')",


问:
python CSV module vs Pandas
I am using pandas to read CSV file data, but the CSV module is also there to manage the CSV file.

so my questions are :-

what is the difference between these both?

what are the cons of using pandas over the CSV module?

答:
Pandas is better then csv for managing data and doing operations on the data. CSV doesn't provide you with the scientific data manipulation tools that Pandas does.

If you are talking only about the part of reading the file it depends. You may simply google both modules online but generally I find it more comfortable to work with Pandas. it provides easier readability as well since printing there is better too.

Title: python CSV module vs Pandas


问:
Is there a way to parse two different dateTime formats into LocalDateTime or Instant in java?
How can we validate two formats "yyyy-MM-dd" and "yyyy-MM-dd'T'HH:mm:SSX" for a given string which can be of any of the two formats and either convert it to Instant or LocalDateTime?

```<code>LocalDateTime dateTime;
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd[\'T\'HH:mm:SSX]");
    TemporalAccessor temporalAccessor = formatter.parseBest(now, LocalDateTime::from, LocalDate::from);
    if (temporalAccessor instanceof LocalDateTime) {
      dateTime = (LocalDateTime)temporalAccessor;
    } else {
      dateTime = ((LocalDate)temporalAccessor).atStartOfDay();
    }
</code>```

When using the above format it's always resolving to LocalDate and chopping the time part.

答: Changing the format to "yyyy-MM-dd[\'T\'HH:mm:ssX]" fixed it.</p>

Body:
How can we validate two formats "yyyy-MM-dd" and "yyyy-MM-dd'T'HH:mm:SSX" for a given string which can be of any of the two formats and either convert it to Instant or LocalDateTime?

LocalDateTime dateTime;
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd[\'T\'HH:mm:SSX]");
    TemporalAccessor temporalAccessor = formatter.parseBest(now, LocalDateTime::from, LocalDate::from);
    if (temporalAccessor instanceof LocalDateTime) {
      dateTime = (LocalDateTime)temporalAccessor;
    } else {
      dateTime = ((LocalDate)temporalAccessor).atStartOfDay();
    }

When using the above format it's always resolving to LocalDate and chopping the time part.


问:
Simplest async/await example possible in Python
I've read many examples, blog posts, questions/answers about asyncio / async / await in Python 3.5+, many were complex, the simplest I found was probably this one.

Still it uses ensure_future, and for learning purposes about asynchronous programming in Python, I would like to see an even more minimal example, and what are the minimal tools necessary to do a basic async / await example.

Question: is it possible to give a simple example showing how async / await works, by using only these two keywords + code to run the async loop + other Python code but no other asyncio functions?

Example: something like this:

```<code>import asyncio

async def async_foo():
    print("async_foo started")
    await asyncio.sleep(5)
    print("async_foo done")

async def main():
    asyncio.ensure_future(async_foo())  # fire and forget async_foo()
    print('Do some actions 1')
    await asyncio.sleep(5)
    print('Do some actions 2')

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
</code>```

but without ensure_future, and still demonstrates how await / async works.

答:
Python 3.7+ now has a simpler API (in my opinion) with a simpler wording (easier to remember than "ensure_future"): you can use create_task which returns a Task object (that can be useful later to cancel the task if needed).

Basic example 1

```<code>import asyncio

async def hello(i):
    print(f"hello {i} started")
    await asyncio.sleep(4)
    print(f"hello {i} done")

async def main():
    task1 = asyncio.create_task(hello(1))  # returns immediately, the task is created
    await asyncio.sleep(3)
    task2 = asyncio.create_task(hello(2))
    await task1
    await task2

asyncio.run(main())  # main loop
</code>```

Result:

hello 1 started

hello 2 started

hello 1 done

hello 2 done

Basic example 2

If you need to get the return value of these async functions, then gather is useful. The following example is inspired from the documentation.

```<code>import asyncio

async def factorial(n):
    f = 1
    for i in range(2, n + 1):
        print(f"Computing factorial({n}), currently i={i}...")
        await asyncio.sleep(1)
        f *= i
    return f

async def main():
    L = await asyncio.gather(factorial(2), factorial(3), factorial(4))
    print(L)  # [2, 6, 24]

asyncio.run(main())
</code>```

Expected output:

Computing factorial(2), currently i=2...

Computing factorial(3), currently i=2...

Computing factorial(4), currently i=2...

Computing factorial(3), currently i=3...

Computing factorial(4), currently i=3...

Computing factorial(4), currently i=4...

[2, 6, 24]

PS: even if you use asyncio, and not trio, the tutorial of the latter was helpful for me to grok Python asynchronous programming.

Body:
I've read many examples, blog posts, questions/answers about asyncio / async / await in Python 3.5+, many were complex, the simplest I found was probably this one.

Still it uses ensure_future, and for learning purposes about asynchronous programming in Python, I would like to see an even more minimal example, and what are the minimal tools necessary to do a basic async / await example.

Question: is it possible to give a simple example showing how async / await works, by using only these two keywords + code to run the async loop + other Python code but no other asyncio functions?

Example: something like this:

import asyncio

async def async_foo():
    print("async_foo started")
    await asyncio.sleep(5)
    print("async_foo done")

async def main():
    asyncio.ensure_future(async_foo())  # fire and forget async_foo()
    print('Do some actions 1')
    await asyncio.sleep(5)
    print('Do some actions 2')

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

but without ensure_future, and still demonstrates how await / async works.

Body:
Python 3.7+ now has a simpler API (in my opinion) with a simpler wording (easier to remember than "ensure_future"): you can use create_task which returns a Task object (that can be useful later to cancel the task if needed).

Basic example 1

import asyncio

async def hello(i):
    print(f"hello {i} started")
    await asyncio.sleep(4)
    print(f"hello {i} done")

async def main():
    task1 = asyncio.create_task(hello(1))  # returns immediately, the task is created
    await asyncio.sleep(3)
    task2 = asyncio.create_task(hello(2))
    await task1
    await task2

asyncio.run(main())  # main loop

Result:

hello 1 started

hello 2 started

hello 1 done

hello 2 done

Basic example 2

If you need to get the return value of these async functions, then gather is useful. The following example is inspired from the documentation.

import asyncio

async def factorial(n):
    f = 1
    for i in range(2, n + 1):
        print(f"Computing factorial({n}), currently i={i}...")
        await asyncio.sleep(1)
        f *= i
    return f

async def main():
    L = await asyncio.gather(factorial(2), factorial(3), factorial(4))
    print(L)  # [2, 6, 24]

asyncio.run(main())

Expected output:

Computing factorial(2), currently i=2...

Computing factorial(3), currently i=2...

Computing factorial(4), currently i=2...

Computing factorial(3), currently i=3...

Computing factorial(4), currently i=3...

Computing factorial(4), currently i=4...

[2, 6, 24]

PS: even if you use asyncio, and not trio, the tutorial of the latter was helpful for me to grok Python asynchronous programming.


问:
Hadoop, Spark: java.lang.NoSuchFieldError: TOKEN_KIND
I want to share an interesting error I've caught up recently:

```<code>Exception in thread "main" java.lang.NoSuchFieldError: TOKEN_KIND
at org.apache.hadoop.crypto.key.kms.KMSClientProvider$KMSTokenRenewer.handleKind(KMSClientProvider.java:166)
at org.apache.hadoop.security.token.Token.getRenewer(Token.java:351)
at org.apache.hadoop.security.token.Token.renew(Token.java:377)
at org.apache.spark.deploy.security.HadoopFSCredentialProvider$$anonfun$getTokenRenewalInterval$1$$anonfun$5$$anonfun$apply$1.apply$mcJ$sp(HadoopFSDelegationTokeProvider.scala:119)
</code>```

I was trying to spark2-submit a job to a remote driver host on Cloudera cluster like this:

```<code>spark = SparkSession.builder
   .master("yarn")
   .config("cluster")
   .config("spark.driver.host", "remote_driver_host")
   .config("spark.yarn.keytab", "path_to_pricnipar.keytab")
   .config("spark.yarn.principal", "principal.name") \
   .config("spark.driver.bindAddress", "0.0.0.0") \
   .getOrCreate()
</code>```

The Apache spark and Hadoop versions on Cloudera cluster are: 2.3.0 and 2.6.0 accordingly.

答:
So the cause of issue was quite trivial, it is spark local binaries vs remote spark driver version mismatch.
Locally I had installed spark 2.4.5 and on Cloudera it was 2.3.0, after aligning the versions to 2.3.0, the issue resolved and the spark job completed successfully. </p>

Body:
I want to share an interesting error I've caught up recently:

Exception in thread "main" java.lang.NoSuchFieldError: TOKEN_KIND
at org.apache.hadoop.crypto.key.kms.KMSClientProvider$KMSTokenRenewer.handleKind(KMSClientProvider.java:166)
at org.apache.hadoop.security.token.Token.getRenewer(Token.java:351)
at org.apache.hadoop.security.token.Token.renew(Token.java:377)
at org.apache.spark.deploy.security.HadoopFSCredentialProvider$$anonfun$getTokenRenewalInterval$1$$anonfun$5$$anonfun$apply$1.apply$mcJ$sp(HadoopFSDelegationTokeProvider.scala:119)

I was trying to spark2-submit a job to a remote driver host on Cloudera cluster like this:

spark = SparkSession.builder
   .master("yarn")
   .config("cluster")
   .config("spark.driver.host", "remote_driver_host")
   .config("spark.yarn.keytab", "path_to_pricnipar.keytab")
   .config("spark.yarn.principal", "principal.name") \
   .config("spark.driver.bindAddress", "0.0.0.0") \
   .getOrCreate()

The Apache spark and Hadoop versions on Cloudera cluster are: 2.3.0 and 2.6.0 accordingly.


问:
Create a R function to be used in a loop with lapply
I have thousands of txt files (1.txt; 2.txt; 3.txt...) to be used as input (predictions), and another file called "labels".
I need to run few commands to create their respective outputs (AUC values). I am using the suggestion in a previous post (Looping through all files in directory in R, applying multiple commands).

But I am having trouble in creating my function to be included in this loop.

My original code (for 1 file predictions):

```<code>library(ROCR)
labels <- read.table(file="/data/labels/labels", header=F, sep="\t")
predictions <- read.table(file="/data/input/3.txt", header=F)
pred <- prediction(predictions, labels)
perf <- performance(pred,"tpr","fpr")
auc <- attr(performance(pred ,"auc"), "y.values")
auc
write.table(auc, "/data/out/AUC3.txt",sep="\t")
</code>```

My code so far (not working):

```<code>library(ROCR)
labels <- read.table(file="/data/labels/labels", header=F, sep="\t")

files <- list.files(path="/data/input/", pattern="*.txt", full.names=TRUE, recursive=FALSE)

auc <- function(r) {
    pred <- prediction(files, labels)
    perf <- performance(pred,"tpr","fpr")
    auc <- attr(performance(pred ,"auc"), "y.values")
}

lapply(files, function(x) {
    t <- read.table(x, header=F) # load file
    out <- auc(t)
    write.table(out, "/data/out/", sep="\t")
})
</code>```

Error message:

```<code>Error in prediction(files, labels) :
Number of predictions in each run must be equal to the number of labels for each run.
Calls: lapply -> FUN -> auc -> prediction
Execution halted
</code>```

答: The problem is this statement files$V1. files is created by list.files and that function returns an atomic vector (see ?list.files). You cannot use $ with atomic vectors. You have to address the element using a numeric index files[###] with ### being the correct index.

Body:
I have thousands of txt files (1.txt; 2.txt; 3.txt...) to be used as input (predictions), and another file called "labels".
I need to run few commands to create their respective outputs (AUC values). I am using the suggestion in a previous post (Looping through all files in directory in R, applying multiple commands).

But I am having trouble in creating my function to be included in this loop.

My original code (for 1 file predictions):

library(ROCR)
labels <- read.table(file="/data/labels/labels", header=F, sep="\t")
predictions <- read.table(file="/data/input/3.txt", header=F)
pred <- prediction(predictions, labels)
perf <- performance(pred,"tpr","fpr")
auc <- attr(performance(pred ,"auc"), "y.values")
auc
write.table(auc, "/data/out/AUC3.txt",sep="\t")

My code so far (not working):

library(ROCR)
labels <- read.table(file="/data/labels/labels", header=F, sep="\t")

files <- list.files(path="/data/input/", pattern="*.txt", full.names=TRUE, recursive=FALSE)

auc <- function(r) {
    pred <- prediction(files, labels)
    perf <- performance(pred,"tpr","fpr")
    auc <- attr(performance(pred ,"auc"), "y.values")
}

lapply(files, function(x) {
    t <- read.table(x, header=F) # load file
    out <- auc(t)
    write.table(out, "/data/out/", sep="\t")
})

Error message:

Error in prediction(files, labels) :
Number of predictions in each run must be equal to the number of labels for each run.
Calls: lapply -> FUN -> auc -> prediction
Execution halted


问:
Name of List with maximum value
I am new to python. Using it with grasshopper.
I have 5 lists, each actually with 8760 items for which i have found max values at each index "but I also need to know which list the value came from at any given index."

I would put a simple example to explain myself better.
For 2 lists
A = [5,10,15,20,25]
B = [4,9,16,19,26]

Max value per index = [5,10,16,20,26]

What I want is something like
Max value per index = [5(A), 10(A), 16(B), 20(A), 26(B)]

Or something along the line that can relate. I am not sure whether its possible.

I would really appreciate the help. Thank you.

答:
This can be adapted to N lists.

```<code>[(max(a),a.index(max(a))) for a in list(zip(A,B))]
</code>```

The .index(max(a)) gets the index at which the max(a) occurs.

The output for your example is

```<code>[(5, 0), (10, 0), (16, 1), (20, 0), (26, 1)]
</code>```

Of course, if both A and B share the same value, then the index will be the first one found, A.

See https://docs.python.org/3.3/library/functions.html for description of very useful zip built-in function.

Title: Name of List with maximum value

Body:
This can be adapted to N lists.

[(max(a),a.index(max(a))) for a in list(zip(A,B))]

The .index(max(a)) gets the index at which the max(a) occurs.

The output for your example is

[(5, 0), (10, 0), (16, 1), (20, 0), (26, 1)]

Of course, if both A and B share the same value, then the index will be the first one found, A.

See https://docs.python.org/3.3/library/functions.html for description of very useful zip built-in function.


问:
What is the clean way to call all the previous functions after each move? How to not repeat this code?
I am a newbie and I need help, please. I have been looking for a solution for long time, but cannot go further. I have a chess table with pieces without repeating codes, but I am stuck at a part when the pieces should move to positions I define. Its a chess analysis and all position is defined by me. This code below works, but it is repetitive.

I want the code not repetitive

if I click any button (except the first move), then all the previous button click should fire as well at once. So one move follow another.

if the above things would work, I also want to remove those chess pieces that was defined after a certain button. So if I am at the position of #move4 and I click the button #move3, then I want to move the chess piece back to position #move3

Thank you very much for help and for any advice.

HTML code:

```<code>  <button id="move1" class="move">d4</button>
  <button id="move2" class="move">Nf6</button>
  <button id="move3" class="move">c4</button>
  <button id="move4" class="move">g6</button>
</code>```

jQuery code:

```<code>
$('#move1').on('click', function () {

    pieces[19].y = 4;

    drawBoard();
    drawAllPieces();
});
$('#move2').on('click', function () {

    pieces[11].y = 2;
    pieces[11].x = 5;

    $("#move1").click();
    drawBoard();
    drawAllPieces();
});

$('#move3').on('click', function () {

    pieces[18].y = 4;

    $("#move1").click();
    $("#move2").click();
    drawBoard();
    drawAllPieces();
});

$('#move4').on('click', function () {

    pieces[6].y = 2;

    $("#move1").click();
    $("#move2").click();
    $("#move3").click();
    drawBoard();
    drawAllPieces();
});

</code>```

答:
I would store the moves in an array then you only need a single handler for the click.</p>

```<code><button data-move="0">d4</button>
<button data-move="1">Nf6</button>
<button data-move="2">c4</button>
<button data-move="3">g6</button>

var moves = [
    { piece: 19, y: 4 },
    { piece: 11, y: 2, x: 5 },
    { piece: 18, y: 4 },
    { piece: 6, y: 2 },
];

$('button').on('click', function () {
    var index = +$(this).attr('data-move');

    for (var i = 0; i <= index; i++) {
        var data = moves[i];

        if (!isNaN(data.y)) // check if the data has y property
            pieces[data.piece] = data.y;

        if (!isNaN(data.x)) // check if the data has x property
            pieces[data.piece] = data.x;
    }

    drawBoard();
    drawAllPieces();

});
</code>```

Body:
I am a newbie and I need help, please. I have been looking for a solution for long time, but cannot go further. I have a chess table with pieces without repeating codes, but I am stuck at a part when the pieces should move to positions I define. Its a chess analysis and all position is defined by me. This code below works, but it is repetitive.

I want the code not repetitive

if I click any button (except the first move), then all the previous button click should fire as well at once. So one move follow another.

if the above things would work, I also want to remove those chess pieces that was defined after a certain button. So if I am at the position of #move4 and I click the button #move3, then I want to move the chess piece back to position #move3

Thank you very much for help and for any advice.

HTML code:

  <button id="move1" class="move">d4</button>
  <button id="move2" class="move">Nf6</button>
  <button id="move3" class="move">c4</button>
  <button id="move4" class="move">g6</button>

jQuery code:

$('#move1').on('click', function () {

    pieces[19].y = 4;

    drawBoard();
    drawAllPieces();
});
$('#move2').on('click', function () {

    pieces[11].y = 2;
    pieces[11].x = 5;

    $("#move1").click();
    drawBoard();
    drawAllPieces();
});

$('#move3').on('click', function () {

    pieces[18].y = 4;

    $("#move1").click();
    $("#move2").click();
    drawBoard();
    drawAllPieces();
});

$('#move4').on('click', function () {

    pieces[6].y = 2;

    $("#move1").click();
    $("#move2").click();
    $("#move3").click();
    drawBoard();
    drawAllPieces();
});

Body:
I would store the moves in an array then you only need a single handler for the click.

<button data-move="0">d4</button>
<button data-move="1">Nf6</button>
<button data-move="2">c4</button>
<button data-move="3">g6</button>

var moves = [
    { piece: 19, y: 4 },
    { piece: 11, y: 2, x: 5 },
    { piece: 18, y: 4 },
    { piece: 6, y: 2 },
];

$('button').on('click', function () {
    var index = +$(this).attr('data-move');

    for (var i = 0; i <= index; i++) {
        var data = moves[i];

        if (!isNaN(data.y)) // check if the data has y property
            pieces[data.piece] = data.y;

        if (!isNaN(data.x)) // check if the data has x property
            pieces[data.piece] = data.x;
    }

    drawBoard();
    drawAllPieces();

});


问:
If string then paste the count value in an offset column and add one to count for next value
hopefully this is an easy one. In this For loop, I would like VBA to read in the first range (LeftStrike) for the string "Foot Strike" and then assign the value of "1" and put that assigned value in the offset cell. Then I want it to add 1 to assigned value and run the For loop again, looking for the next "Foot Strike" string. That way, I can see what row the "First" foot strike is, and so on. I'm really struggling with understanding the .value of one thing = .value of another thing in order to "copy and paste" so to speak. </p>

```<code>Private Sub CommandButton2_Click()
Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
Dim ws2 As Worksheet: Set ws2 = ThisWorkbook.Sheets("Sheet2")
Dim LeftStrike As Range, FrameLTD As Range, StepNum As Range
Dim lrL As Long, LastFrame As Long
Dim StepCount As Long
StepCount = 1

lrL = ws.Range("H" & ws.Rows.Count).End(xlUp).Row
LastFrame = ws.Range("A" & ws.Rows.Count).End(xlUp).Row

Set LeftStrike = ws.Range("H2:H" & lrL)
Set StepNum = ws.Range("J2:J" & lrL)

For Each FrameLTD In LeftStrike
   If InStr(FrameLTD, "Foot Strike") Then
           ' assign value of "1" to StepCount
           ' somehow get StepCount to = FrameLTD.Offset(0, 3).Value
           ' StepCount = StepCount + 1

    End If
Next FrameLTD

MsgBox "Steps Numbered"
End Sub

</code>```

<p>Can someone tell me what my lines of code should be within the For Loop to get my "step count" into the offset column??? </p>

答:
Tim Williams solution should work!

Double-check that you are looking/referring code to the correct worksheet (it will
print values in "Sheet1")

The values will be printed in column K as
the range you refer to is column H and then you offset it by 3
columns. You don't have any other code running that will overwrite this column?

Code:

```<code>Option Explicit

Private Sub CommandButton2_Click()
Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
Dim ws2 As Worksheet: Set ws2 = ThisWorkbook.Sheets("Sheet2")
Dim LeftStrike As Range, FrameLTD As Range, StepNum As Range
Dim lrL As Long, LastFrame As Long
Dim StepCount As Long

StepCount = 1

lrL = ws.Range("H" & ws.Rows.Count).End(xlUp).Row
LastFrame = ws.Range("A" & ws.Rows.Count).End(xlUp).Row

Set LeftStrike = ws.Range("H2:H" & lrL)
Set StepNum = ws.Range("J2:J" & lrL)

For Each FrameLTD In LeftStrike
   If InStr(FrameLTD, "Foot Strike") Then
           'assign value of "1" to StepCount
           'somehow get StepCount to = FrameLTD.Offset(0, 3).Value
           FrameLTD.Offset(0, 3).Value = StepCount
           StepCount = StepCount + 1
    End If
Next FrameLTD

MsgBox "Steps Numbered"
End Sub
</code>```

Result:

Body:
hopefully this is an easy one. In this For loop, I would like VBA to read in the first range (LeftStrike) for the string "Foot Strike" and then assign the value of "1" and put that assigned value in the offset cell. Then I want it to add 1 to assigned value and run the For loop again, looking for the next "Foot Strike" string. That way, I can see what row the "First" foot strike is, and so on. I'm really struggling with understanding the .value of one thing = .value of another thing in order to "copy and paste" so to speak.

Private Sub CommandButton2_Click()
Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
Dim ws2 As Worksheet: Set ws2 = ThisWorkbook.Sheets("Sheet2")
Dim LeftStrike As Range, FrameLTD As Range, StepNum As Range
Dim lrL As Long, LastFrame As Long
Dim StepCount As Long
StepCount = 1

lrL = ws.Range("H" & ws.Rows.Count).End(xlUp).Row
LastFrame = ws.Range("A" & ws.Rows.Count).End(xlUp).Row

Set LeftStrike = ws.Range("H2:H" & lrL)
Set StepNum = ws.Range("J2:J" & lrL)

For Each FrameLTD In LeftStrike
   If InStr(FrameLTD, "Foot Strike") Then
           ' assign value of "1" to StepCount
           ' somehow get StepCount to = FrameLTD.Offset(0, 3).Value
           ' StepCount = StepCount + 1

    End If
Next FrameLTD

MsgBox "Steps Numbered"
End Sub

Can someone tell me what my lines of code should be within the For Loop to get my "step count" into the offset column???

Body:
Tim Williams solution should work!

Double-check that you are looking/referring code to the correct worksheet (it will
print values in "Sheet1")

The values will be printed in column K as
the range you refer to is column H and then you offset it by 3
columns. You don't have any other code running that will overwrite this column?

Code:

Option Explicit

Private Sub CommandButton2_Click()
Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
Dim ws2 As Worksheet: Set ws2 = ThisWorkbook.Sheets("Sheet2")
Dim LeftStrike As Range, FrameLTD As Range, StepNum As Range
Dim lrL As Long, LastFrame As Long
Dim StepCount As Long

StepCount = 1

lrL = ws.Range("H" & ws.Rows.Count).End(xlUp).Row
LastFrame = ws.Range("A" & ws.Rows.Count).End(xlUp).Row

Set LeftStrike = ws.Range("H2:H" & lrL)
Set StepNum = ws.Range("J2:J" & lrL)

For Each FrameLTD In LeftStrike
   If InStr(FrameLTD, "Foot Strike") Then
           'assign value of "1" to StepCount
           'somehow get StepCount to = FrameLTD.Offset(0, 3).Value
           FrameLTD.Offset(0, 3).Value = StepCount
           StepCount = StepCount + 1
    End If
Next FrameLTD

MsgBox "Steps Numbered"
End Sub

Result:


问:
implementing simple Document management
My qustion is: How would you go on implementing simple DMS(document management) based on following requirements?

DMS shouls be distributed web application.

Support for document versioning.

Support for document locking.

Document search.

Im already clear on what technologies I want to use. I will use Sring MVC, Hibernate and relational (most likely MYSQL) database.

One thing Im not very clear on is if I need to use webdav, since I could just upload or download documets. I thing I have to because I need to acomplish point 2. and especially point 3. somehow. Is this the right way to go?

Any examples or experience with this would come very handy :). May be Milton is not the best library to pick for webdav?

答:
@Eduard, regarding dependencies on 3rd parties - are you doing this as a college/university exercise or something that will affect real users in a production environment?

At the risk of sounding very pretentious; don't reimplement the wheel! I'd definitely 2nd the call to use JCR, this way you are depending a standard and not a 3rd party implementation.

JCR is a well defined standard (that means a lot of people invested commercial effort (i.e. cash and expertise in huge amounts) into this).  I would seriously reconsider looking into JCR - think of it as an API where 3rd parties provide the implementation (no vendor lockin).

Have a look at the features you'll get out-of-the-box, I believe 99 - 110% of the functionality you require is available through a JCR implementation. Plus you'll benefit from the fact the code you'll be using has been tested by hundreds of people in real world situations.

Where I'd differ from bmscomp is in suggesting JackRabbit http://jackrabbit.apache.org/

Title: implementing simple Document management


问:
Flask - allowing users into a group of projects, based on project being a variable and an @app.route id
I am using flask-security. I would like to set up @roles_accepted with a variable based upon the app route.

For example, if _id = Lon_2020 the @roles_accepted would allow Lon. This would grant certain users to projects, but not others, based on the _id.

```<code>@app.route('/<string:_id>')
@app.route('/<string:_id>/')
@roles_accepted('admin',_id[:3])
def home(_id):
    return redirect(url_for('tb',_id=_id))
</code>```

At the moment, this causes an error, because _id is not defined. The roles_accepted relies on the _id data.

If this is not possible, would you mind letting me know a better way of allowing certain users into certain projects. e.g.

```<code>Lon_2019
Lon_2020
Lon_2021
Par_2019
Par_2020
Par_2021
Ber_2018
Ber_2019

where the identified is the first 3 characters 'Lon','Par','Ber'
</code>```

Any help is much appreciated. Thank you.

答:
I have a solution which is working, but isn’t perfect. Based on @Jessi suggestion of 403 abort:</p>

```<code>
def check_user(c_id):
    if current_user.has_role('admin'):
        current = c_id
    to_check = ['Lon','Par’,’Ber'] #manual inserton of roles from db, could use sqlalchemy to query db instead?
    for n in to_check:
        if current_user.has_role(n):
            current = n
    if c_id == current:
        return True

@app.route('/<string:_id>')
@app.route('/<string:_id>/')
def home(_id):
    c_id = _id[:3])
    if check_user(c_id):
        return redirect(url_for('tb',_id=_id))
    else:
        return abort(403)
</code>```

Body:
I am using flask-security. I would like to set up @roles_accepted with a variable based upon the app route.

For example, if _id = Lon_2020 the @roles_accepted would allow Lon. This would grant certain users to projects, but not others, based on the _id.

@app.route('/<string:_id>')
@app.route('/<string:_id>/')
@roles_accepted('admin',_id[:3])
def home(_id):
    return redirect(url_for('tb',_id=_id))

At the moment, this causes an error, because _id is not defined. The roles_accepted relies on the _id data.

If this is not possible, would you mind letting me know a better way of allowing certain users into certain projects. e.g.

Lon_2019
Lon_2020
Lon_2021
Par_2019
Par_2020
Par_2021
Ber_2018
Ber_2019

where the identified is the first 3 characters 'Lon','Par','Ber'

Any help is much appreciated. Thank you.

Body:
I have a solution which is working, but isn’t perfect. Based on @Jessi suggestion of 403 abort:

def check_user(c_id):
    if current_user.has_role('admin'):
        current = c_id
    to_check = ['Lon','Par’,’Ber'] #manual inserton of roles from db, could use sqlalchemy to query db instead?
    for n in to_check:
        if current_user.has_role(n):
            current = n
    if c_id == current:
        return True

@app.route('/<string:_id>')
@app.route('/<string:_id>/')
def home(_id):
    c_id = _id[:3])
    if check_user(c_id):
        return redirect(url_for('tb',_id=_id))
    else:
        return abort(403)


问:
CORS Policy Issue in Cosmos DB Table
I am unable to see the CORS option in the settings panel of Azure Cosmos DB Table. Please help me on it

Azure Cosmos DB Table options Panel

答: Unfortunately CORS is only currently supported for Cosmos accounts created with the Core (SQL) API. It looks like yours was created with the Azure Table API and so CORS isn't available.</p>

Title: CORS Policy Issue in Cosmos DB Table


问:
Javascript array, building from a set of variables
The variables following are defined through a Car prototype:

var Car = function(maker, type, model) {
  this.maker = maker;
  this.type = type;
  this.model = model;
}

var golf = new Car('VW', 'Hatchback', 'Golf');
var sentra = new Car('Nissan', 'Sedan', 'Sentra');
var _328i = new Car('BMW', 'Convertible', "328i");
var gallardo = new Car('Lamborghini', 'Convertible', "Gallardo");
var corniche = new Car('Rolls Royce', 'Sedan', "Corniche");

Car.prototype.year = 0;

golf.year = 2015;
sentra.year = 2010;
_328i.year = 2019;
gallardo.year = 2020;
corniche.year = 1998;
```

How does one build an array of the var values for the property maker

Something that might console log like this:

(5) ['VW', 'Nissan', 'BMW', 'Lamborghini', 'Roll Royce']

答:
There are a lot of solutions to that. First, you need to make an array with all your cars, and then use a method to iterate on each car to get the car maker.

Here two examples:

var Car = function (maker, type, model) {
  this.maker = maker;
  this.type = type;
  this.model = model;
}

Car.prototype.year = 0;

var golf = new Car ('VW', 'Hatchback', 'Golf');
var sentra = new Car ('Nissan', 'Sedan', 'Sentra');
var _328i = new Car ('BMW', 'Convertible', "328i");
var gallardo = new Car ('Lamborghini', 'Convertible', "Gallardo", 2020);
var corniche = new Car('Rolls Royce', 'Sedan', "Corniche");

golf.year = 2015;
sentra.year = 2010;
_328i.year = 2019;
gallardo.year = 2020;
corniche.year = 1998;

var cars = [golf, sentra, _328i, gallardo, corniche]
var carsMakers = []

for(var i = 0; i < cars.length; i++) {
  var c = cars[i]
  carsMakers.push(c.maker)
}
console.log(carsMakers)

var carsMakers2 = cars.map(function(c) { return c.maker });
console.log(carsMakers2)```

Body:
The variables following are defined through a Car prototype:

var Car = function(maker, type, model) {
  this.maker = maker;
  this.type = type;
  this.model = model;
}

var golf = new Car('VW', 'Hatchback', 'Golf');
var sentra = new Car('Nissan', 'Sedan', 'Sentra');
var _328i = new Car('BMW', 'Convertible', "328i");
var gallardo = new Car('Lamborghini', 'Convertible', "Gallardo");
var corniche = new Car('Rolls Royce', 'Sedan', "Corniche");

Car.prototype.year = 0;

golf.year = 2015;
sentra.year = 2010;
_328i.year = 2019;
gallardo.year = 2020;
corniche.year = 1998;

How does one build an array of the var values for the property maker

Something that might console log like this:

(5) ['VW', 'Nissan', 'BMW', 'Lamborghini', 'Roll Royce']


问:
JFrame window size too big for screen?
Okay so i've tried finding an answer for this pretty much all day but can't seem to find any. :/

Using JFrame, i've been trying to set a window to 1920x1080 resolution but when i try doing this it seems to use my whole screen as a window, kinda like my screen resolution is 1920x1080 but it's 3840x2160, why is this? When i run another application with a 1920x1080 resolution window it seems to not be the same size. (it's smaller)

Current code:

```<code>JFrame frame = new JFrame("Test");
GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
int width = gd.getDisplayMode().getWidth();
int height = gd.getDisplayMode().getHeight();
frame.setSize(width, height);
System.out.println(width+" "+height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
</code>```

The output from this is a window covering my screen tho a little off at some parts and then in the console it says 3840 2160. If i change the frame.setSize(width, height);
from the current to frame.setSize(1920, 1080); it still makes the window the same size. I think the maximum is a little below 1920x1080 for some reason. :/ Any ideas here?

EDIT: It seems using frame.setSize(Toolkit.getDefaultToolkit().getScreenSize()); makes the window size 1536x864 and not 3840x2160, setting it any higher than 1536x864 makes no difference, it'll say the size is bigger but i can't see any difference, it covers the screen anyway.

答: Thats because your windows scaling is not set to 100%.</p>

Title: JFrame window size too big for screen?

Body:
Okay so i've tried finding an answer for this pretty much all day but can't seem to find any. :/

Using JFrame, i've been trying to set a window to 1920x1080 resolution but when i try doing this it seems to use my whole screen as a window, kinda like my screen resolution is 1920x1080 but it's 3840x2160, why is this? When i run another application with a 1920x1080 resolution window it seems to not be the same size. (it's smaller)

Current code:

JFrame frame = new JFrame("Test");
GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
int width = gd.getDisplayMode().getWidth();
int height = gd.getDisplayMode().getHeight();
frame.setSize(width, height);
System.out.println(width+" "+height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);

The output from this is a window covering my screen tho a little off at some parts and then in the console it says 3840 2160. If i change the frame.setSize(width, height);
from the current to frame.setSize(1920, 1080); it still makes the window the same size. I think the maximum is a little below 1920x1080 for some reason. :/ Any ideas here?

EDIT: It seems using frame.setSize(Toolkit.getDefaultToolkit().getScreenSize()); makes the window size 1536x864 and not 3840x2160, setting it any higher than 1536x864 makes no difference, it'll say the size is bigger but i can't see any difference, it covers the screen anyway.


问:
How To Update the React js project from 15.6 to 16.8?
How To Update the React js project from 15.6 to 16.8? is there any Steps need to to be followed ?</p>

答:
there is 2 way, directly and indirectly

1.directly: bin this code in the import of your code

import update from 'react-update'

2.indirectly: in terminal use, this command for update the react to the last version , also if you install it again, it will install the last version of react.js (npm install --g create-react-app)

npm i --save react-update


问:
array implementation of queue in c
new to programming. I need to use queues and link lists to solve this problem. I am having trouble with the logic because I am unaware of all the tricks you can do with structures and how to implement them along with this new topic. I am not trying to cheat just need the general direction of what I am missing here. problem is the time the customer enters the line is added along with the number of shopped items after their name plus the cashier time to give a final checkout length. Then they must be put into ascending order. That is where I am tripped up. How do I take this input in a queue with all this information then change the order after the fact? hints greatly appreciated.

sample input
2
5
10 1 STEVEN 12

12 6 AHMAD 8

13 1 JENNY 40

22 6 JERMAINE 39

100000 12 AMALIA 53

6

100 1 A 100

200 2 B 99

300 3 C 98

400 4 D 97

500 5 E 96

600 6 F 95

Sample Output
STEVEN from line 1 checks out at time 100.

AHMAD from line 6 checks out at time 170.

JERMAINE from line 6 checks out at time 395.

JENNY from line 1 checks out at time 625.

AMALIA from line 12 checks out at time 100295.

A from line 1 checks out at time 630.

F from line 6 checks out at time 1135.

E from line 5 checks out at time 1645.

D from line 4 checks out at time 2160.

C from line 3 checks out at time 2680.

B from line 2 checks out at time 3205.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

#define TRUE 1
#define FALSE 0

typedef char customerName[9];

typedef struct node
{
    int data;
    struct node *next;
}node;

typedef struct queue
{
    int size;
    int front;
    int back;
    int *array;
    unsigned capacity;

}queue;

typedef struct customer
{
    customerName name;//1-9 upper case letters
    int lineNumber;
    int time;
    int numberItems;
} customer;

int minIndex( queue *q, int sortedIndex);
int isEmpty(queue *q);
void initialize(queue *q);
void insertMinToFront ( queue *q, int minIndex);
void isSorted(queue *q, int numCustomers);

void initialize(queue *q)
{
    q->size = 0;
    q->front = -1;
    q->back = -1;
}

int isEmpty(queue *q){
    return (q->size == 0);//returns 1 if empty or 0 if false
}

int isFull(queue *q)
{  return (q->size == q->capacity);  }

void enqueue(queue *q, int item)
{
    if (isFull(q))
        return;
    q->back = (q->back + 1)%q->capacity;
    q->array[q->back] = item;
    q->size = q->size + 1;
}

int dequeue(queue *q)
{
    if (isEmpty(q))
        return 0;
    int item = q->array[q->front];
    q->front = (q->front + 1)%q->capacity;
    q->size = q->size - 1;
    return item;
}

int front(queue* q){
    if(isEmpty(q)){
        return 0;
    }
    return q->array[q->front];
}

int minIndex( queue *q, int sortedIndex){

    int min_index = -1;
    int min_val = INT_MAX;
    int n = q->size;

    for (int i = 0; i<n; i++){
        int current = q->front;
        dequeue(q);

        if(current <= min_val && i <= sortedIndex){
            min_index = i;
            min_val = current;
        }
        enqueue(q, current);
    }
    return min_index;
}

void insertMinToFront ( queue *q, int minIndex){

        int minVal;
        int n = q->size;
        for (int i = 0; i < n; i++)
        {
            int curr = q->front;
            dequeue(q);
            if (i != minIndex)
                enqueue(q, curr);
            else
                minVal = curr;
        }
        enqueue(q, minVal);
    }

void isSorted(queue *q, int numCustomers) {

    for ( int i = 0; i < numCustomers; i++){

        int min_index = minIndex(q, q->size - i );
        insertMinToFront(q, min_index);
    }
}

int main(int argc, const char * argv[]) {

    int testCases = 0;
    scanf("%d", &testCases);

    if(testCases > 0 && testCases <= 25){//shortcircuiting???

    while (testCases--){

        queue *q;
        q = malloc(sizeof(queue));
        initialize(q);// starting new queue

        int numCustomers;
        scanf("%d", &numCustomers);

        if(numCustomers < 0 || numCustomers > 12){
            return 0;
        }

        struct customer newCustomer[12];

        for ( int i = 0; i < numCustomers; i++){
            scanf("%d", &newCustomer[i].time);
            scanf("%d", &newCustomer[i].lineNumber);
            scanf("%s", newCustomer[i].name);
            scanf("%d", &newCustomer[i].numberItems);
            enqueue(q, newCustomer[i].time);
            enqueue(q, newCustomer[i].lineNumber);

        }

          isSorted(q, numCustomers);

        for ( int i = 0; i < numCustomers; i++){
            printf("%d %d %s %d\n", newCustomer[i].time, newCustomer[i].lineNumber, newCustomer[i].name, newCustomer[i].numberItems);

               }

    }
}
    return 0;
}
</code>```

答:
Here's a quick guide on how to approach this sort of problem. There are some actual bugs in your code, but they're not what you asked about.

I need to use queues and link lists

OK, you know which data structures you need. So - implement them.

Hopefully you have some textbook which describes them, but if not, you can just start by reading Wikipedia, eg. on linked lists which has diagrams and pseudocode.

Containers have well-defined behaviour and a bounded set of natural operations (eg. insert or append or push_front). You can write, and test, a linked list of integers (or whatever) independently of the rest of your problem.

I am unaware of all the tricks you can do with structures

You shouldn't need any tricks - just write a structure capable of containing the input fields.

Then they must be put into ascending order

You know this is called sorting, right? If you didn't there's your key search term. Look for sort or, if you're allowed to use stdlib and an array, qsort.

How do I take this input in a queue with all this information then change the order after the fact?

The natural operations on a queue are basically push (to the back) and pop (from the front). This doesn't lend itself well to sorting.

If your queue is implemented on top of a linked list, you'd perform the sort on the underlying linked list (although it definitely won't be a qsort, at least not directly).

The alternative is to use a priority queue, that keeps itself sorted as you insert. This probably isn't what you're being asked for though, since it wouldn't be implemented with a linked list.

Title: array implementation of queue in c

Body:
new to programming. I need to use queues and link lists to solve this problem. I am having trouble with the logic because I am unaware of all the tricks you can do with structures and how to implement them along with this new topic. I am not trying to cheat just need the general direction of what I am missing here. problem is the time the customer enters the line is added along with the number of shopped items after their name plus the cashier time to give a final checkout length. Then they must be put into ascending order. That is where I am tripped up. How do I take this input in a queue with all this information then change the order after the fact? hints greatly appreciated.

sample input
2
5
10 1 STEVEN 12

12 6 AHMAD 8

13 1 JENNY 40

22 6 JERMAINE 39

100000 12 AMALIA 53

6

100 1 A 100

200 2 B 99

300 3 C 98

400 4 D 97

500 5 E 96

600 6 F 95

Sample Output
STEVEN from line 1 checks out at time 100.

AHMAD from line 6 checks out at time 170.

JERMAINE from line 6 checks out at time 395.

JENNY from line 1 checks out at time 625.

AMALIA from line 12 checks out at time 100295.

A from line 1 checks out at time 630.

F from line 6 checks out at time 1135.

E from line 5 checks out at time 1645.

D from line 4 checks out at time 2160.

C from line 3 checks out at time 2680.

B from line 2 checks out at time 3205.

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

#define TRUE 1
#define FALSE 0

typedef char customerName[9];

typedef struct node
{
    int data;
    struct node *next;
}node;

typedef struct queue
{
    int size;
    int front;
    int back;
    int *array;
    unsigned capacity;

}queue;

typedef struct customer
{
    customerName name;//1-9 upper case letters
    int lineNumber;
    int time;
    int numberItems;
} customer;

int minIndex( queue *q, int sortedIndex);
int isEmpty(queue *q);
void initialize(queue *q);
void insertMinToFront ( queue *q, int minIndex);
void isSorted(queue *q, int numCustomers);

void initialize(queue *q)
{
    q->size = 0;
    q->front = -1;
    q->back = -1;
}

int isEmpty(queue *q){
    return (q->size == 0);//returns 1 if empty or 0 if false
}

int isFull(queue *q)
{  return (q->size == q->capacity);  }

void enqueue(queue *q, int item)
{
    if (isFull(q))
        return;
    q->back = (q->back + 1)%q->capacity;
    q->array[q->back] = item;
    q->size = q->size + 1;
}

int dequeue(queue *q)
{
    if (isEmpty(q))
        return 0;
    int item = q->array[q->front];
    q->front = (q->front + 1)%q->capacity;
    q->size = q->size - 1;
    return item;
}

int front(queue* q){
    if(isEmpty(q)){
        return 0;
    }
    return q->array[q->front];
}

int minIndex( queue *q, int sortedIndex){

    int min_index = -1;
    int min_val = INT_MAX;
    int n = q->size;

    for (int i = 0; i<n; i++){
        int current = q->front;
        dequeue(q);

        if(current <= min_val && i <= sortedIndex){
            min_index = i;
            min_val = current;
        }
        enqueue(q, current);
    }
    return min_index;
}

void insertMinToFront ( queue *q, int minIndex){

        int minVal;
        int n = q->size;
        for (int i = 0; i < n; i++)
        {
            int curr = q->front;
            dequeue(q);
            if (i != minIndex)
                enqueue(q, curr);
            else
                minVal = curr;
        }
        enqueue(q, minVal);
    }

void isSorted(queue *q, int numCustomers) {

    for ( int i = 0; i < numCustomers; i++){

        int min_index = minIndex(q, q->size - i );
        insertMinToFront(q, min_index);
    }
}

int main(int argc, const char * argv[]) {

    int testCases = 0;
    scanf("%d", &testCases);

    if(testCases > 0 && testCases <= 25){//shortcircuiting???

    while (testCases--){

        queue *q;
        q = malloc(sizeof(queue));
        initialize(q);// starting new queue

        int numCustomers;
        scanf("%d", &numCustomers);

        if(numCustomers < 0 || numCustomers > 12){
            return 0;
        }

        struct customer newCustomer[12];

        for ( int i = 0; i < numCustomers; i++){
            scanf("%d", &newCustomer[i].time);
            scanf("%d", &newCustomer[i].lineNumber);
            scanf("%s", newCustomer[i].name);
            scanf("%d", &newCustomer[i].numberItems);
            enqueue(q, newCustomer[i].time);
            enqueue(q, newCustomer[i].lineNumber);

        }

          isSorted(q, numCustomers);

        for ( int i = 0; i < numCustomers; i++){
            printf("%d %d %s %d\n", newCustomer[i].time, newCustomer[i].lineNumber, newCustomer[i].name, newCustomer[i].numberItems);

               }

    }
}
    return 0;
}


问:
Add rows in a gridview c#
Im new in asp.net. I want to know how to add a row in a gridview programatically. I was able to do it but it just displays the latest addition.
Here is my code: </p>

```<code>DataTable dt = new DataTable();
dt.Columns.Add("Question");
dt.Columns.Add("Answer");

DataRow dr = dt.NewRow();
dr["Question"] = txtQuestion.Text;
dr["Answer"] = txtAnswer.Text;
dt.Rows.Add(dr);
dt.AcceptChanges();

gvQnA.DataSource = dt;
gvQnA.DataBind();
</code>```

答:
@Pranay is correct.In addition You can also achive that by using DataTable as property.

```<code>  private DataTable Dt
    {
        set { ViewState.Add("Dt", value); }
        get { return (DataTable)ViewState["Dt"]; }
    }
</code>```

...

```<code>DataRow dr = Dt.NewRow();
dr["Question"] = txtQuestion.Text;
dr["Answer"] = txtAnswer.Text;
Dt.Rows.Add(dr);
Dt.AcceptChanges();

gvQnA.DataSource = Dt;
gvQnA.DataBind();
</code>```

Title: Add rows in a gridview c#

Body:
Im new in asp.net. I want to know how to add a row in a gridview programatically. I was able to do it but it just displays the latest addition.
Here is my code:

DataTable dt = new DataTable();
dt.Columns.Add("Question");
dt.Columns.Add("Answer");

DataRow dr = dt.NewRow();
dr["Question"] = txtQuestion.Text;
dr["Answer"] = txtAnswer.Text;
dt.Rows.Add(dr);
dt.AcceptChanges();

gvQnA.DataSource = dt;
gvQnA.DataBind();

Body:
@Pranay is correct.In addition You can also achive that by using DataTable as property.

  private DataTable Dt
    {
        set { ViewState.Add("Dt", value); }
        get { return (DataTable)ViewState["Dt"]; }
    }

...

DataRow dr = Dt.NewRow();
dr["Question"] = txtQuestion.Text;
dr["Answer"] = txtAnswer.Text;
Dt.Rows.Add(dr);
Dt.AcceptChanges();

gvQnA.DataSource = Dt;
gvQnA.DataBind();


问:
How to force flex-row into 2x2 grid on certain window size?
I'm not very experienced with react-bootstrap. I'm working on this code which renders four buttons in a flex-row:

```<code>renderBoxes(boxes) {
        return Object.keys(boxes).map((key, index) => {
            var box = boxes[key];
            return <div className="col-lg-3 col-md-6 col-sm-6 col-xs-6 col-12 d-flex flex-row" key={index}>
                <IconBox
                    key={index}
                    title={box.title}
                    description={box.description}
                    icon={box.icon}
                    link={box.link}
                />
            </div>
        });
    }

<div className="row d-flex flex-row">
    {this.renderBoxes(boxes)}
</div>
</code>```

At lg window widths, the buttons look like this:

At md window widths, the buttons look like this, in a 2x2 grid:

However, at sm window widths, the buttons begin displaying one on top of the other:

I want to force the buttons to stay in the 2x2 grid at all of the screen sizes including and smaller than md. Is there any way to achieve this? I can't seem to figure it out.

答:
All you have to do is giving class of col-lg-3 for larger devices and then the second class col-6 and that's it. So when screen get smaller than lg the button will always remain in 2x2grid and never going to fall into single column.

```<code>renderBoxes(boxes) {
  return Object.keys(boxes).map((key, index) => {
      var box = boxes[key];
      return <div className="col-lg-3 col-6 d-flex flex-row" key={index}>
          <IconBox
              key={index}
              title={box.title}
              description={box.description}
              icon={box.icon}
              link={box.link}
          />
      </div>
  });
}

<div className="row">
{this.renderBoxes(boxes)}
</div>
</code>```

One extra thing i want to tell you

xs is now removed from bootstrap so you can use col-6 instead of col-xs-6

so in the future if you are setting different resolution devices then you can do this

```<code><div class=" col-lg-4 col-md-6 col-sm-6 col-12"> some text </div>
</code>```

Body:
I'm not very experienced with react-bootstrap. I'm working on this code which renders four buttons in a flex-row:

renderBoxes(boxes) {
        return Object.keys(boxes).map((key, index) => {
            var box = boxes[key];
            return

                <IconBox
                    key={index}
                    title={box.title}
                    description={box.description}
                    icon={box.icon}
                    link={box.link}
                />

        });
    }

    {this.renderBoxes(boxes)}

At lg window widths, the buttons look like this:

At md window widths, the buttons look like this, in a 2x2 grid:

However, at sm window widths, the buttons begin displaying one on top of the other:

I want to force the buttons to stay in the 2x2 grid at all of the screen sizes including and smaller than md. Is there any way to achieve this? I can't seem to figure it out.

Body:
All you have to do is giving class of col-lg-3 for larger devices and then the second class col-6 and that's it. So when screen get smaller than lg the button will always remain in 2x2grid and never going to fall into single column.

renderBoxes(boxes) {
  return Object.keys(boxes).map((key, index) => {
      var box = boxes[key];
      return <div className="col-lg-3 col-6 d-flex flex-row" key={index}>
          <IconBox
              key={index}
              title={box.title}
              description={box.description}
              icon={box.icon}
              link={box.link}
          />
      </div>
  });
}

<div className="row">
{this.renderBoxes(boxes)}
</div>

One extra thing i want to tell you

xs is now removed from bootstrap so you can use col-6 instead of col-xs-6

so in the future if you are setting different resolution devices then you can do this

<div class=" col-lg-4 col-md-6 col-sm-6 col-12"> some text </div>


问:
How to avoid using random_id for Managed Instance Group creation in GCP
Please help me to understand if I may avoid "random_id" using for Managed Instance group creation in GCP.
I know it is possible for the Unmanaged instance group where I can specify the exact names for instances.
But for MIG I always have some suffix with random_id

答:
I think you can't and it's because the service needs a way to name instances that it creates. The service will use the template to create instances on-the-fly in order to maintain the number of instances that you define. Each instance requires a unique name.

A simple numbering system (could result in gaps and) would require the current number to be persisted.

Random suffixes are used because it's very improbable (but possibly, possible) for a random name to collide.

Conceptually (!) you should treat the instances as cattle not pets (link) too. You(r code) should not prefer a specific instance but should treat all the instances homogeneously.

Corollary: if you want to be able to refer to a specific instance, you probably shouldn't use a managed instance group.

With an unmanaged group you must either manually or via code maintain a list of named instances and so you can define the naming mechanism.


问:
pass tuple with one element as param in sql query Python
I am passing Python tuple as a SQL parameter when making bulk API Call with simple salesforce library. The script works perfectly fine if my tuple has more than one element in it, however, it gives me IndexError: list index out of range if my tuple has just one element. . My code below:

```<code>id_params_tuple = ('0060z000023HFr4AAG',)
sql = "SELECT Id FROM OpportunityLineItem where Opportunity_ID__c IN {}".format(id_params_tuple)
opp_products_raw_data = sf.bulk.OpportunityLineItem.query(sql)
print(opp_products_raw_data)
</code>```

How can I work around this issue?

答:
You're missing parenthesis in the IN clause.  Try this on the second line.</p>

```<code>sql = "SELECT Id FROM OpportunityLineItem where Opportunity_ID__c IN ({})".format(id_params_tuple)
</code>```

Body:
I am passing Python tuple as a SQL parameter when making bulk API Call with simple salesforce library. The script works perfectly fine if my tuple has more than one element in it, however, it gives me IndexError: list index out of range if my tuple has just one element. . My code below:

id_params_tuple = ('0060z000023HFr4AAG',)
sql = "SELECT Id FROM OpportunityLineItem where Opportunity_ID__c IN {}".format(id_params_tuple)
opp_products_raw_data = sf.bulk.OpportunityLineItem.query(sql)
print(opp_products_raw_data)

How can I work around this issue?

Body:
You're missing parenthesis in the IN clause.  Try this on the second line.

sql = "SELECT Id FROM OpportunityLineItem where Opportunity_ID__c IN ({})".format(id_params_tuple)


问:
Error replacing network map and notary on corda
we have replaced our network map and one of our three notaries with new machine.
We stopped all nodes. Changed configuration in node.conf files to point to new notary and network map but after start all network environment is broke and we are not able to submit any transaction between nodes.

We see following errors:
1- In the New Newtwork Map

[ERROR] 2018-04-18T09:30:30,588Z [Thread-12
  (ActiveMQ-server-org.apache.activemq.artemis.core.server.impl.ActiveMQServerImpl$3@2f07930a)]
  core.client.createConnection - AMQ214016: Failed to create netty
  connection javax.net.ssl.SSLException: handshake timed out    at
  io.netty.handler.ssl.SslHandler.handshake(...)(Unknown Source)
  ~[netty-all-4.1.9.Final.jar:4.1.9.Final] [WARN ]
  2018-04-18T09:30:46,087Z [Thread-11
  (ActiveMQ-server-org.apache.activemq.artemis.core.server.impl.ActiveMQServerImpl$3@2f07930a)]
  core.client.fail - AMQ212037: Connection failure has been detected:
  AMQ119014: Did not receive data from null within the 60,000ms
  connection TTL. The connection will now be closed.
  [code=CONNECTION_TIMEDOUT]

2- In one previous existing notary node:

[ERROR] 2018-04-18T10:22:05,682Z [main]
  internal.ExceptionMapperStandardImpl.mapManagedFlushFailure -
  HHH000346: Error during managed flush
  [org.hibernate.exception.ConstraintViolationException: could not
  execute statement] [ERROR] 2018-04-18T10:22:05,714Z [main]
  internal.Node.run - Exception during node startup
  javax.persistence.PersistenceException:
  org.hibernate.exception.ConstraintViolationException: could not
  execute statement     at
  org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:147)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:155)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:162)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1434)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:484)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3190)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2404)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:467)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:146)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:220)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:68)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  net.corda.node.services.network.PersistentNetworkMapCache.updateInfoDB(PersistentNetworkMapCache.kt:287)
  ~[corda-node-2.0.0.jar:?]     at
  net.corda.node.services.network.PersistentNetworkMapCache.access$updateInfoDB(PersistentNetworkMapCache.kt:52)
  ~[corda-node-2.0.0.jar:?]     at
  net.corda.node.services.network.PersistentNetworkMapCache$addNode$$inlined$synchronized$lambda$2.invoke(PersistentNetworkMapCache.kt:169)
  ~[corda-node-2.0.0.jar:?]     at
  net.corda.node.services.network.PersistentNetworkMapCache$addNode$$inlined$synchronized$lambda$2.invoke(PersistentNetworkMapCache.kt:52)
  ~[corda-node-2.0.0.jar:?]     at
  net.corda.node.utilities.CordaPersistence.inTopLevelTransaction(CordaPersistence.kt:84)
  ~[corda-node-2.0.0.jar:?]     at
  net.corda.node.utilities.CordaPersistence.transaction(CordaPersistence.kt:75)
  ~[corda-node-2.0.0.jar:?]     at
  net.corda.node.utilities.CordaPersistence.transaction(CordaPersistence.kt:65)
  ~[corda-node-2.0.0.jar:?]     at
  net.corda.node.services.network.PersistentNetworkMapCache.addNode(PersistentNetworkMapCache.kt:168)
  ~[corda-node-2.0.0.jar:?]     at
  net.corda.node.internal.AbstractNode.registerWithNetworkMapIfConfigured(AbstractNode.kt:512)
  ~[corda-node-2.0.0.jar:?]     at
  net.corda.node.internal.AbstractNode.start(AbstractNode.kt:221)
  ~[corda-node-2.0.0.jar:?]     at
  net.corda.node.internal.Node.start(Node.kt:312)
  ~[corda-node-2.0.0.jar:?]     at
  net.corda.node.internal.NodeStartup.startNode(NodeStartup.kt:95)
  ~[corda-node-2.0.0.jar:?]     at
  net.corda.node.internal.NodeStartup.run(NodeStartup.kt:74)
  [corda-node-2.0.0.jar:?]  at net.corda.node.Corda.main(Corda.kt:11)
  [corda-node-2.0.0.jar:?] Caused by:
  org.hibernate.exception.ConstraintViolationException: could not
  execute statement     at
  org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:112)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:207)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:45)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1323)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.action.internal.CollectionUpdateAction.execute(CollectionUpdateAction.java:80)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:586)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:460)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:337)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1428)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     ... 22 more Caused by:
  org.h2.jdbc.JdbcSQLException: Unique index or primary key violation:
  "UK_MH4X07LLMH7CQIHD64UPRW7TT_INDEX_2 ON
  PUBLIC.""NODE_INFOS_NODEINFOSCHEMAV1$DBHOSTANDPORT""(ADDRESSES_HOST,
  ADDRESSES_PORT) VALUES ('10.83.80.46', 10002, 48)"; SQL statement:
  insert into node_infos_NodeInfoSchemaV1$DBHostAndPort
  (NodeInfoSchemaV1$PersistentNodeInfo_node_info_id, addresses_host,
  addresses_port) values (?, ?, ?) [23505-194]  at
  org.h2.engine.SessionRemote.done(SessionRemote.java:629)
  ~[h2-1.4.194.jar:1.4.194]     at
  org.h2.command.CommandRemote.executeUpdate(CommandRemote.java:203)
  ~[h2-1.4.194.jar:1.4.194]     at
  org.h2.jdbc.JdbcPreparedStatement.executeUpdateInternal(JdbcPreparedStatement.java:160)
  ~[h2-1.4.194.jar:1.4.194]     at
  org.h2.jdbc.JdbcPreparedStatement.executeUpdate(JdbcPreparedStatement.java:146)
  ~[h2-1.4.194.jar:1.4.194]     at
  com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61)
  ~[HikariCP-2.5.1.jar:?]   at
  com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java)
  ~[HikariCP-2.5.1.jar:?]   at
  org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:204)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:45)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1323)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.action.internal.CollectionUpdateAction.execute(CollectionUpdateAction.java:80)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:586)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:460)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:337)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1428)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]

3- error on existing corda node:

[ERROR] 2018-04-18T08:50:39,726Z [Node thread]
  network.PersistentNetworkMapCache.invoke - Exception processing update
  from network map service javax.persistence.PersistenceException:
  org.hibernate.exception.ConstraintViolationException: could not
  execute statement     at
  org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:147)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:155)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:162)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1434)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:484)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3190)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2404)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:467)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:146)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:220)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:68)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  net.corda.node.services.network.PersistentNetworkMapCache.updateInfoDB(PersistentNetworkMapCache.kt:287)
  ~[corda-node-2.0.0.jar:?]     at
  net.corda.node.services.network.PersistentNetworkMapCache.access$updateInfoDB(PersistentNetworkMapCache.kt:52)
  ~[corda-node-2.0.0.jar:?]     at
  net.corda.node.services.network.PersistentNetworkMapCache$addNode$$inlined$synchronized$lambda$1.invoke(PersistentNetworkMapCache.kt:164)
  ~[corda-node-2.0.0.jar:?]     at
  net.corda.node.services.network.PersistentNetworkMapCache$addNode$$inlined$synchronized$lambda$1.invoke(PersistentNetworkMapCache.kt:52)
  ~[corda-node-2.0.0.jar:?]     at
  net.corda.node.utilities.CordaPersistence.transaction(CordaPersistence.kt:72)
  ~[corda-node-2.0.0.jar:?]     at
  net.corda.node.utilities.CordaPersistence.transaction(CordaPersistence.kt:65)
  ~[corda-node-2.0.0.jar:?]     at
  net.corda.node.services.network.PersistentNetworkMapCache.addNode(PersistentNetworkMapCache.kt:163)
  ~[corda-node-2.0.0.jar:?]     at
  net.corda.node.services.network.PersistentNetworkMapCache.processRegistration(PersistentNetworkMapCache.kt:223)
  ~[corda-node-2.0.0.jar:?]     at
  net.corda.node.services.network.PersistentNetworkMapCache.processUpdatePush(PersistentNetworkMapCache.kt:206)
  ~[corda-node-2.0.0.jar:?]     at
  net.corda.node.services.network.PersistentNetworkMapCache$addMapService$1.invoke(PersistentNetworkMapCache.kt:137)
  [corda-node-2.0.0.jar:?]  at
  net.corda.node.services.network.PersistentNetworkMapCache$addMapService$1.invoke(PersistentNetworkMapCache.kt:52)
  [corda-node-2.0.0.jar:?]  at
  net.corda.node.services.messaging.NodeMessagingClient.callHandlers(NodeMessagingClient.kt:444)
  [corda-node-2.0.0.jar:?]  at
  net.corda.node.services.messaging.NodeMessagingClient.access$callHandlers(NodeMessagingClient.kt:76)
  [corda-node-2.0.0.jar:?]  at
  net.corda.node.services.messaging.NodeMessagingClient$deliver$1$1.invoke(NodeMessagingClient.kt:429)
  [corda-node-2.0.0.jar:?]  at
  net.corda.node.services.messaging.NodeMessagingClient$deliver$1$1.invoke(NodeMessagingClient.kt:76)
  [corda-node-2.0.0.jar:?]  at
  net.corda.node.utilities.CordaPersistence.inTopLevelTransaction(CordaPersistence.kt:84)
  [corda-node-2.0.0.jar:?]  at
  net.corda.node.utilities.CordaPersistence.transaction(CordaPersistence.kt:75)
  [corda-node-2.0.0.jar:?]  at
  net.corda.node.utilities.CordaPersistence.transaction(CordaPersistence.kt:65)
  [corda-node-2.0.0.jar:?]  at
  net.corda.node.services.messaging.NodeMessagingClient$deliver$1.invoke(NodeMessagingClient.kt:421)
  [corda-node-2.0.0.jar:?]  at
  net.corda.node.services.messaging.NodeMessagingClient$deliver$1.invoke(NodeMessagingClient.kt:76)
  [corda-node-2.0.0.jar:?]  at
  net.corda.node.utilities.AffinityExecutor$fetchFrom$1.get(AffinityExecutor.kt:44)
  [corda-node-2.0.0.jar:?]  at
  java.util.concurrent.CompletableFuture$AsyncSupply.run(Unknown Source)
  [?:1.8.0_162]     at
  java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
  [?:1.8.0_162]     at java.util.concurrent.FutureTask.run(Unknown Source)
  [?:1.8.0_162]     at
  java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown
  Source) [?:1.8.0_162]     at
  java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown
  Source) [?:1.8.0_162]     at
  java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
  [?:1.8.0_162]     at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
  [?:1.8.0_162]     at
  net.corda.node.utilities.AffinityExecutor$ServiceAffinityExecutor$1$thread$1.run(AffinityExecutor.kt:69)
  [corda-node-2.0.0.jar:?] Caused by:
  org.hibernate.exception.ConstraintViolationException: could not
  execute statement     at
  org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:112)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:207)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:45)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1323)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.action.internal.CollectionRecreateAction.execute(CollectionRecreateAction.java:50)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:586)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:460)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:337)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1428)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     ... 37 more Caused by:
  org.h2.jdbc.JdbcSQLException: Unique index or primary key violation:
  "UK_MH4X07LLMH7CQIHD64UPRW7TT_INDEX_2 ON
  PUBLIC.""NODE_INFOS_NODEINFOSCHEMAV1$DBHOSTANDPORT""(ADDRESSES_HOST,
  ADDRESSES_PORT) VALUES ('10.83.80.5', 10001, 34)"; SQL statement:
  insert into node_infos_NodeInfoSchemaV1$DBHostAndPort
  (NodeInfoSchemaV1$PersistentNodeInfo_node_info_id, addresses_host,
  addresses_port) values (?, ?, ?) [23505-194]  at
  org.h2.engine.SessionRemote.done(SessionRemote.java:629)
  ~[h2-1.4.194.jar:1.4.194]     at
  org.h2.command.CommandRemote.executeUpdate(CommandRemote.java:203)
  ~[h2-1.4.194.jar:1.4.194]     at
  org.h2.jdbc.JdbcPreparedStatement.executeUpdateInternal(JdbcPreparedStatement.java:160)
  ~[h2-1.4.194.jar:1.4.194]     at
  org.h2.jdbc.JdbcPreparedStatement.executeUpdate(JdbcPreparedStatement.java:146)
  ~[h2-1.4.194.jar:1.4.194]     at
  com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61)
  ~[HikariCP-2.5.1.jar:?]   at
  com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java)
  ~[HikariCP-2.5.1.jar:?]   at
  org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:204)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:45)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1323)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.action.internal.CollectionRecreateAction.execute(CollectionRecreateAction.java:50)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:586)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:460)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:337)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     at
  org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1428)
  ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]     ... 37 more [WARN ]
  2018-04-18T08:51:17,425Z [Thread-1
  (ActiveMQ-server-org.apache.activemq.artemis.core.server.impl.ActiveMQServerImpl$3@319aa9ee)]
  core.client.fail - AMQ212037: Connection failure has been detected:
  AMQ119014: Did not receive data from null within the 60,000ms
  connection TTL. The connection will now be closed.
  [code=CONNECTION_TIMEDOUT]

is there a way to clean network / notaries to work with new scenario?

Thanks!!

Javier

答:
You can use a Network bootstrapper to load out your network with the new conf file. Please take a look at: https://docs.corda.net/docs/corda-os/4.4/network-bootstrapper.html

In related to your original question, you can achieve the notary sway by follow the steps for: Adding a new node to the network section because it is virtually the same process: https://docs.corda.net/docs/corda-os/4.4/network-bootstrapper.html#adding-a-new-node-to-the-network


问:
Matplotlib v 3 Length mismatch ValueError: Expected axis has x elements, new values have x+1 elements
I'm using Matplotlib version 3.2.1 with Python 3.7 and pandas 1.0.3.

I'm using the following code which results in a length mismatch error:

```<code>import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.dates as mpl_dates
df_train = pd.read_csv('mydata.csv', date_parser=True)
df_train.columns = ['date', 'col1', 'col2', 'col3', 'col4', 'col5', 'col6']
df_train['date'] = pd.to_datetime(df_train['date'])
df_train.set_index(['date'])

x_value = df_train['date']
y_value = df_train['col4']
plt.plot_date(x_value, y_value, 'g')
plt.gcf().autofmt_xdate()
plt.show()
</code>```

which results in the following error:

```<code>     File "C:\Users\brohj\anaconda3\lib\site-packages\pandas\core\internals\managers.py", line 178, in set_axis
    f"Length mismatch: Expected axis has {old_len} elements, new "
ValueError: Length mismatch: Expected axis has 6 elements, new values have 7 elements
</code>```

(Note: There is no typo in the error message.  Copied directly as is.)

What gives?  Thanks in advance.

答:
The problem is these two lines:

```<code>df_train = pd.read_csv('mydata.csv', date_parser=True)
df_train.columns = ['date', 'col1', 'col2', 'col3', 'col4', 'col5', 'col6']
</code>```

which I believe your data in csv does not have a name for index. You can do:

```<code># read and parse index as date
df_train = pd.read_csv('mydata.csv', parse_dates=True, index_col=[0])

# rename column
df_train.columns = ['col1', 'col2', 'col3', 'col4', 'col5']

# rename index
df_train.index.name = 'date'

df_train.plot(y='col4', c='g')
plt.show()
</code>```

Body:
I'm using Matplotlib version 3.2.1 with Python 3.7 and pandas 1.0.3.

I'm using the following code which results in a length mismatch error:

import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.dates as mpl_dates
df_train = pd.read_csv('mydata.csv', date_parser=True)
df_train.columns = ['date', 'col1', 'col2', 'col3', 'col4', 'col5', 'col6']
df_train['date'] = pd.to_datetime(df_train['date'])
df_train.set_index(['date'])

x_value = df_train['date']
y_value = df_train['col4']
plt.plot_date(x_value, y_value, 'g')
plt.gcf().autofmt_xdate()
plt.show()

which results in the following error:

     File "C:\Users\brohj\anaconda3\lib\site-packages\pandas\core\internals\managers.py", line 178, in set_axis
    f"Length mismatch: Expected axis has {old_len} elements, new "
ValueError: Length mismatch: Expected axis has 6 elements, new values have 7 elements

(Note: There is no typo in the error message.  Copied directly as is.)

What gives?  Thanks in advance.

Body:
The problem is these two lines:

df_train = pd.read_csv('mydata.csv', date_parser=True)
df_train.columns = ['date', 'col1', 'col2', 'col3', 'col4', 'col5', 'col6']

which I believe your data in csv does not have a name for index. You can do:

# read and parse index as date
df_train = pd.read_csv('mydata.csv', parse_dates=True, index_col=[0])

# rename column
df_train.columns = ['col1', 'col2', 'col3', 'col4', 'col5']

# rename index
df_train.index.name = 'date'

df_train.plot(y='col4', c='g')
plt.show()


问:
Python slice complexity?
What is the time complexity of this short program? I'm thinking it's linear, but then again, in the if statement there's a Python slice. I'm wondering how it would contribute to the complexity:</p>

```<code>def count_s(string, sub):

  i = 0
  j =len(sub)-1
  count = 0

  while j < len(string):
      if string[i:j+1] == sub:
          count = count + 1
          j = j + 1
          i = i + 1
      else:
          i = i + 1
          j = j + 1

  return count
</code>```

答:
Python's time complexity is O(k) where k is the length of the slice, so your function is O(n * k), which is not linear, yet still not exponential. On the other hand, you could use Python's builtin count function, as such: string.count(sub).

Or, if you're set on using your own code, it could be slimmed down to this for readability's sake:

def count_s(string, sub):
    i = count = 0
    j = len(sub) - 1

    while j < len(string):
        count += string[i:j + 1] == sub
        j += 1
        i += 1

    return count
```

Title: Python slice complexity?

Body:
What is the time complexity of this short program? I'm thinking it's linear, but then again, in the if statement there's a Python slice. I'm wondering how it would contribute to the complexity:

def count_s(string, sub):

  i = 0
  j =len(sub)-1
  count = 0

  while j < len(string):
      if string[i:j+1] == sub:
          count = count + 1
          j = j + 1
          i = i + 1
      else:
          i = i + 1
          j = j + 1

  return count


问:
How to obtain the absolute path of a file via Shell (BASH/ZSH/SH)?
Question: is there a simple sh/bash/zsh/fish/... command to print the absolute path of whichever file I feed it?

Usage case: I'm in directory /a/b and I'd like to print the full path to file c on the command-line so that I can easily paste it into another program: /a/b/c. Simple, yet a little program to do this could probably save me 5 or so seconds when it comes to handling long paths, which in the end adds up. So it surprises me that I can't find a standard utility to do this — is there really none?

Here's a sample implementation, abspath.py:

```<code>#!/usr/bin/python
# Author: Diggory Hardy <diggory.hardy@gmail.com>
# Licence: public domain
# Purpose: print the absolute path of all input paths

import sys
import os.path
if len(sys.argv)>1:
    for i in range(1,len(sys.argv)):
        print os.path.abspath( sys.argv[i] )
    sys.exit(0)
else:
    print >> sys.stderr, "Usage: ",sys.argv[0]," PATH."
    sys.exit(1)
</code>```

答:
Answer with Homebrew

realpath is the best answer, but if you don't have it installed, you must first run brew install coreutils which will install coreutils with lots of awesome functions. Writing a custom function and exporting it is too much work and risk for error for something like this, here are two lines:

```<code>$ brew install coreutils
$ realpath your-file-name.json
</code>```

Body:
Question: is there a simple sh/bash/zsh/fish/... command to print the absolute path of whichever file I feed it?

Usage case: I'm in directory /a/b and I'd like to print the full path to file c on the command-line so that I can easily paste it into another program: /a/b/c. Simple, yet a little program to do this could probably save me 5 or so seconds when it comes to handling long paths, which in the end adds up. So it surprises me that I can't find a standard utility to do this — is there really none?

Here's a sample implementation, abspath.py:

#!/usr/bin/python
# Author: Diggory Hardy <diggory.hardy@gmail.com>
# Licence: public domain
# Purpose: print the absolute path of all input paths

import sys
import os.path
if len(sys.argv)>1:
    for i in range(1,len(sys.argv)):
        print os.path.abspath( sys.argv[i] )
    sys.exit(0)
else:
    print >> sys.stderr, "Usage: ",sys.argv[0]," PATH."
    sys.exit(1)

Body:
Answer with Homebrew

realpath is the best answer, but if you don't have it installed, you must first run brew install coreutils which will install coreutils with lots of awesome functions. Writing a custom function and exporting it is too much work and risk for error for something like this, here are two lines:

$ brew install coreutils
$ realpath your-file-name.json