问:
How to handle error properly in Promise chain?
Say we have 3 asynchronous tasks that return Promises: A, B and C. We want to chain them together (that is, for sake of clarity, taking the value returned by A and calling B with it), but also want to handle the errors correctly for each, and break out at the first failure. Currently, I see 2 ways of doing this:

```<code>A
.then(passA)
.then(B)
.then(passB)
.then(C)
.then(passC)
.catch(failAll)
</code>```

Here, the passX functions handle each of the success of the call to X. But in the failAll function, we'd have to handle all of the errors of A, B and C, which may be complex and not easy to read, especially if we had more than 3 async tasks. So the other way takes this into consideration:

```<code>A
.then(passA, failA)
.then(B)
.then(passB, failB)
.then(C)
.then(passC, failC)
.catch(failAll)
</code>```

Here, we separated out the logic of the original failAll into failA, failB and failC, which seems simple and readable, since all errors are handled right next to its source. However, this does not do what I want.

Let's see if A fails (rejected), failA must not proceed to call B, therefore must throw an exception or call reject. But both of these gets caught by failB and failC, meaning that failB and failC needs to know if we had already failed or not, presumably by keeping state (i.e. a variable).

Moreover, it seems that the more async tasks we have, either our failAll function grows in size (way 1), or more failX functions gets called (way 2). This brings me to my question:

Is there a better way to do this?

Consideration: Since exceptions in then is handled by the rejection method, should there be a Promise.throw method to actually break off the chain?

A possible duplicate, with an answer that adds more scopes inside the handlers. Aren't promises supposed to honor linear chaining of functions, and not passing functions that pass functions that pass functions?

答:
You have a couple options.  First, let's see if I can distill down your requirements.

You want to handle the error near where it occurs so you don't have one error handler that has to sort through all the possible different errors to see what to do.

When one promise fails, you want to have the ability to abort the rest of the chain.

One possibility is like this:

```<code>A().then(passA).catch(failA).then(val => {
    return B(val).then(passB).catch(failB);
}).then(val => {
    return C(val).then(passC).catch(failC);
}).then(finalVal => {
    // chain done successfully here
}).catch(err => {
    // some error aborted the chain, may or may not need handling here
    // as error may have already been handled by earlier catch
});
</code>```

Then, in each failA, failB, failC, you get the specific error for that step.  If you want to abort the chain, you rethrow before the function returns.  If you want the chain to continue, you just return a normal value.

The above code could also be written like this (with slightly different behavior if passB or passC throws or returns a rejected promise.

```<code>A().then(passA, failA).then(val => {
    return B(val).then(passB, failB);
}).then(val => {
    return C(val).then(passC, failC);
}).then(finalVal => {
    // chain done successfully here
}).catch(err => {
    // some error aborted the chain, may or may not need handling here
    // as error may have already been handled by earlier catch
});
</code>```

Since these are completely repetitive, you could make the whole thing be table-driven for any length of sequence too.

```<code>function runSequence(data) {
    return data.reduce((p, item) => {
        return p.then(item[0]).then(item[1]).catch(item[2]);
    }, Promise.resolve());
}

let fns = [
    [A, passA, failA],
    [B, passB, failB],
    [C, passC, failC]
];

runSequence(fns).then(finalVal => {
    // whole sequence finished
}).catch(err => {
    // sequence aborted with an error
});
</code>```

Another useful point when chaining lots of promises is if you make a unique Error class for each reject error, then you can more easily switch on the type of error using instanceof in the final .catch() handler if you need to know there which step caused the aborted chain.  Libraries like Bluebird, provide specific .catch() semantics for making a .catch() that catches only a particular type of error (like the way try/catch does it).  You can see how Bluebird does that here: http://bluebirdjs.com/docs/api/catch.html.  If you're going to handle each error right at it's own promise rejection (as in the above examples), then this is not required unless you still need to know at the final .catch() step which step caused the error.

Body:
Say we have 3 asynchronous tasks that return Promises: A, B and C. We want to chain them together (that is, for sake of clarity, taking the value returned by A and calling B with it), but also want to handle the errors correctly for each, and break out at the first failure. Currently, I see 2 ways of doing this:

A
.then(passA)
.then(B)
.then(passB)
.then(C)
.then(passC)
.catch(failAll)

Here, the passX functions handle each of the success of the call to X. But in the failAll function, we'd have to handle all of the errors of A, B and C, which may be complex and not easy to read, especially if we had more than 3 async tasks. So the other way takes this into consideration:

A
.then(passA, failA)
.then(B)
.then(passB, failB)
.then(C)
.then(passC, failC)
.catch(failAll)

Here, we separated out the logic of the original failAll into failA, failB and failC, which seems simple and readable, since all errors are handled right next to its source. However, this does not do what I want.

Let's see if A fails (rejected), failA must not proceed to call B, therefore must throw an exception or call reject. But both of these gets caught by failB and failC, meaning that failB and failC needs to know if we had already failed or not, presumably by keeping state (i.e. a variable).

Moreover, it seems that the more async tasks we have, either our failAll function grows in size (way 1), or more failX functions gets called (way 2). This brings me to my question:

Is there a better way to do this?

Consideration: Since exceptions in then is handled by the rejection method, should there be a Promise.throw method to actually break off the chain?

A possible duplicate, with an answer that adds more scopes inside the handlers. Aren't promises supposed to honor linear chaining of functions, and not passing functions that pass functions that pass functions?

Body:
You have a couple options.  First, let's see if I can distill down your requirements.

You want to handle the error near where it occurs so you don't have one error handler that has to sort through all the possible different errors to see what to do.

When one promise fails, you want to have the ability to abort the rest of the chain.

One possibility is like this:

A().then(passA).catch(failA).then(val => {
    return B(val).then(passB).catch(failB);
}).then(val => {
    return C(val).then(passC).catch(failC);
}).then(finalVal => {
    // chain done successfully here
}).catch(err => {
    // some error aborted the chain, may or may not need handling here
    // as error may have already been handled by earlier catch
});

Then, in each failA, failB, failC, you get the specific error for that step.  If you want to abort the chain, you rethrow before the function returns.  If you want the chain to continue, you just return a normal value.

The above code could also be written like this (with slightly different behavior if passB or passC throws or returns a rejected promise.

A().then(passA, failA).then(val => {
    return B(val).then(passB, failB);
}).then(val => {
    return C(val).then(passC, failC);
}).then(finalVal => {
    // chain done successfully here
}).catch(err => {
    // some error aborted the chain, may or may not need handling here
    // as error may have already been handled by earlier catch
});

Since these are completely repetitive, you could make the whole thing be table-driven for any length of sequence too.

function runSequence(data) {
    return data.reduce((p, item) => {
        return p.then(item[0]).then(item[1]).catch(item[2]);
    }, Promise.resolve());
}

let fns = [
    [A, passA, failA],
    [B, passB, failB],
    [C, passC, failC]
];

runSequence(fns).then(finalVal => {
    // whole sequence finished
}).catch(err => {
    // sequence aborted with an error
});

Another useful point when chaining lots of promises is if you make a unique Error class for each reject error, then you can more easily switch on the type of error using instanceof in the final .catch() handler if you need to know there which step caused the aborted chain.  Libraries like Bluebird, provide specific .catch() semantics for making a .catch() that catches only a particular type of error (like the way try/catch does it).  You can see how Bluebird does that here: http://bluebirdjs.com/docs/api/catch.html.  If you're going to handle each error right at it's own promise rejection (as in the above examples), then this is not required unless you still need to know at the final .catch() step which step caused the error.


来源: stackexchange

问:
T-SQL Some questions about a recursive query (CTE)
I take all items (e.g advertisements) from a tree using CTE (here), but I'm wondering about two things - the hardest part:

1) is it somehow possible to get all category names of the found advertisements ? (in the recursive CTE query, look at the hyperlink above)

2) And (optional) how to get the total found advertisement's count of the each category ? I mean, let's say I found 6 items from 3 categories and I'd like to see the result in that way

```<code>category1 (6) -\
|               category3 (4)
category2 (2)
</code>```

Any ideas will be so helpful

答:
for the first question you need to go from down to up, it could be resolved with changing querying order ex:

```<code>with CTE (id, pid, name)
as
(
select id, parentid as pid,name
from category
where id = @lowLevelCategory
union all
select CTE.pid as id , category.parentid as pid, category.name
from CTE
inner join category
on category.id = CTE.pid
)
select * from ss
</code>```

for the second one: you can calculate only count of sub items, but not  summ and you need some function for this calculations, because grouping or subselecting can't be in recursive part

ContentLicense: CC BY-SA 2.5

Body:
I take all items (e.g advertisements) from a tree using CTE (here), but I'm wondering about two things - the hardest part:

1) is it somehow possible to get all category names of the found advertisements ? (in the recursive CTE query, look at the hyperlink above)

2) And (optional) how to get the total found advertisement's count of the each category ? I mean, let's say I found 6 items from 3 categories and I'd like to see the result in that way

category1 (6) -\
|               category3 (4)
category2 (2)

Any ideas will be so helpful

Body:
for the first question you need to go from down to up, it could be resolved with changing querying order ex:

with CTE (id, pid, name)
as
(
select id, parentid as pid,name
from category
where id = @lowLevelCategory
union all
select CTE.pid as id , category.parentid as pid, category.name
from CTE
inner join category
on category.id = CTE.pid
)
select * from ss

for the second one: you can calculate only count of sub items, but not  summ and you need some function for this calculations, because grouping or subselecting can't be in recursive part


问:
sqlite How many characters of the _id TEXT column are considered unique?
Sqlite on Android.
How many characters of the _id TEXT column are considered unique?
All characters or first few</p>

答:
Determining uniqueness is done with the normal comparison operations.

As mentioned in the collating sequences documentation, all characters in a value are used for comparisons. (Unless you're explicitily using the RTRIM collation, but then you'd know about this.)

ContentLicense: CC BY-SA 3.0


问:
How do I call concat : %variable% when the variable has internal spaces?
I am trying to concat variables in my class path using the following command, but it isn't working when the folder name contains spaces:

```<code>call concat : %variable%
</code>```

where %variable% ={folder name containing space}

I tried putting quotes:

```<code>call concat : "%variable%"
</code>```

but this adds 2 double-quotes in my classpath as follows:

```<code>""folder name containing space""

:concat
set CLASSPATH=%CLASSPATH%;"%1"
</code>```

答:
remove the double quote from input, use double quote around the entire set, when use the concatenated string, surrounding them by double quote, for example:</p>

```<code>set root=%~1
@echo off
setlocal EnableDelayedExpansion
set i=0
for %%d in (
1.07 1.023 1.075 1.08 1.04
) do (
   set /A i=i+1
   set scale[!i!]=%%d
)
set i=0
for %%d in (
CO DE MH PL Pr
) do (
   set /A i=i+1
   set port[!i!]=%%d
)
for %%A in (0 1 2 3 4) do (
set "file1=%root%\Event\Events.txt"
set "file2=%root%\Port E\PortE_!port[%%A]!.txt"
set "file3=%root%\Poli E By Port\E_!port[%%A]!.txt"
%0\..\average101v2.exe "!file1!" "!file2!" "!file3!" !scale[%%A]!
)
</code>```

Body:
I am trying to concat variables in my class path using the following command, but it isn't working when the folder name contains spaces:

call concat : %variable%

where %variable% ={folder name containing space}

I tried putting quotes:

call concat : "%variable%"

but this adds 2 double-quotes in my classpath as follows:

""folder name containing space""

:concat
set CLASSPATH=%CLASSPATH%;"%1"

Body:
remove the double quote from input, use double quote around the entire set, when use the concatenated string, surrounding them by double quote, for example:

set root=%~1
@echo off
setlocal EnableDelayedExpansion
set i=0
for %%d in (
1.07 1.023 1.075 1.08 1.04
) do (
   set /A i=i+1
   set scale[!i!]=%%d
)
set i=0
for %%d in (
CO DE MH PL Pr
) do (
   set /A i=i+1
   set port[!i!]=%%d
)
for %%A in (0 1 2 3 4) do (
set "file1=%root%\Event\Events.txt"
set "file2=%root%\Port E\PortE_!port[%%A]!.txt"
set "file3=%root%\Poli E By Port\E_!port[%%A]!.txt"
%0\..\average101v2.exe "!file1!" "!file2!" "!file3!" !scale[%%A]!
)


问:
Is it possible to make an editable select in blueprintjs?
I've been playing a bit with it and haven't found the way to do it. Here is a link to the relevant part of the documentation:
http://blueprintjs.com/docs/#components.forms.select

The desired functionality is like the one we can find in this framework:
http://jedwatson.github.io/react-select/
but for design reasons I want to avoid mixing different UI frameworks.

If it is not possible, is there any way to style react-select so that it looks like a blueprintjs select?

答: Sorry, we do not currently support such a thing, but we're planning to in the near future! Dropdown and Typeahead are literally next on our components list. You can follow the discussion here: https://github.com/palantir/blueprint/issues/118.


问:
How to execute goal after completion of Maven's package phase?
I need to copy packaged jar artifact from ${basedir}/target into another subdirectory.

But when I try to utilize maven-resource-plugin I get broken jar with different size. I think it happens because package phase is not completely finished when maven-resource-plugin start coping.

```<code>  <build>
    <plugins>
      <plugin>
        <artifactId>maven-resources-plugin</artifactId>
        <executions>
          <execution>
            <id>copy-jar-after-package</id>
            <phase>package</phase>
            <goals>
              <goal>copy-resources</goal>
            </goals>
            <configuration>
              <outputDirectory>${basedir}/target/dist</outputDirectory>
              <resources>
                <resource>
                  <directory>${basedir}/target</directory>
                  <include>${artifactId}-${version}.jar</include>
                  <filtering>true</filtering>
                </resource>
              </resources>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</code>```

答: Please remove the <filtering>true</filtering>, otherwise Maven will go through the jar as if it was a text-file and will try to replace any matching ${*}.

Body:
I need to copy packaged jar artifact from ${basedir}/target into another subdirectory.

But when I try to utilize maven-resource-plugin I get broken jar with different size. I think it happens because package phase is not completely finished when maven-resource-plugin start coping.

  <build>
    <plugins>
      <plugin>
        <artifactId>maven-resources-plugin</artifactId>
        <executions>
          <execution>
            <id>copy-jar-after-package</id>
            <phase>package</phase>
            <goals>
              <goal>copy-resources</goal>
            </goals>
            <configuration>
              <outputDirectory>${basedir}/target/dist</outputDirectory>
              <resources>
                <resource>
                  <directory>${basedir}/target</directory>
                  <include>${artifactId}-${version}.jar</include>
                  <filtering>true</filtering>
                </resource>
              </resources>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>


问:
How can I use python to iterate through multiple csv files and if a value is the same, update another value?
I'm trying to iterate through a few .csv files, and if a value is the same, add up the related entries. If a value is not the same, add that as a new row.

My current code is:

```<code>import pandas
s1011 = pandas.read_csv('goals/1011.csv', sep=',', usecols=(1,3,5))
s1011.dropna(how="all", inplace=True)
print s1011

s1112 = pandas.read_csv('goals/1112.csv', sep=',', usecols=(1,3,5))
s1112.dropna(how="all", inplace=True)
print s1112

s1213 = pandas.read_csv('goals/1213.csv', sep=',', usecols=(1,3,5))
s1213.dropna(how="all", inplace=True)
print s1213
</code>```

Currently this doesn't do much I know. It prints out 3 headings, Team, For & Against. It the prints out 20 football teams, how many goals they've scored, and how many conceded. I've tried using merge in python but it isn't suitable as it just makes one big table.

What I'm trying to do is open the multiple csv files, iterate through the list, if the Team is the same, add together goals for and goals against from each file. If Team has not been entered before, add a new row with new entries.

Is this possible using python?

Edit:

It currently prints

Team
  For
  Against

Man Utd
  86
  43

Man City
  83
  45

Chelsea
  89
  39

etc for 20 teams. So I want to update the For and Against entries by adding up the number of goals for each team over a number of seasons. Since it won't be the same 20 teams each season, I want to add a new row of entries if a team hasn't been in the league before.

答:
Here's one approach:

Use Pandas to append the file's identifying number to the For & Against column in each dataframe (i.e. For-1011, For-1112, For-1213).

Use a full outer join on 'Team' to bring in all rows into a new dataframe.

Sum the columns as you'd like: df[For-total] = df[For-1011] + df[For-1112] + df[For-1213]

Body:
I'm trying to iterate through a few .csv files, and if a value is the same, add up the related entries. If a value is not the same, add that as a new row.

My current code is:

import pandas
s1011 = pandas.read_csv('goals/1011.csv', sep=',', usecols=(1,3,5))
s1011.dropna(how="all", inplace=True)
print s1011

s1112 = pandas.read_csv('goals/1112.csv', sep=',', usecols=(1,3,5))
s1112.dropna(how="all", inplace=True)
print s1112

s1213 = pandas.read_csv('goals/1213.csv', sep=',', usecols=(1,3,5))
s1213.dropna(how="all", inplace=True)
print s1213

Currently this doesn't do much I know. It prints out 3 headings, Team, For & Against. It the prints out 20 football teams, how many goals they've scored, and how many conceded. I've tried using merge in python but it isn't suitable as it just makes one big table.

What I'm trying to do is open the multiple csv files, iterate through the list, if the Team is the same, add together goals for and goals against from each file. If Team has not been entered before, add a new row with new entries.

Is this possible using python?

Edit:

It currently prints

Team
  For
  Against

Man Utd
  86
  43

Man City
  83
  45

Chelsea
  89
  39

etc for 20 teams. So I want to update the For and Against entries by adding up the number of goals for each team over a number of seasons. Since it won't be the same 20 teams each season, I want to add a new row of entries if a team hasn't been in the league before.


问:
IntelliJ suggests wrong @NotNull annotation
IntelliJ is suggesting to import com.sun.istack.internal.NotNull the @NotNull annotation (which is wrong) in the following program:

```<code>public class Test implements Comparable<Test> {
    @Override
    public int compareTo(@NotNull Test o) {
        return 0;
    }
}
</code>```

When trying the correct import com.intellij.annotations.NotNull (I think) it looks like it can't find the class:

答:
I found I had to add the following dependency declaration to my Java project's build.gradle file before I was able to import the org.jetbrains.annotations.NotNull and org.jetbrains.annotations.Nullable annotations rather than the com.sun.istack.internal.NotNull and com.sun.istack.internal.Nullable annotations:

```<code>repositories {
    mavenCentral()
}

dependencies {
    compile 'org.jetbrains:annotations:15.0'
}
</code>```

Body:
IntelliJ is suggesting to import com.sun.istack.internal.NotNull the @NotNull annotation (which is wrong) in the following program:

public class Test implements Comparable<Test> {
    @Override
    public int compareTo(@NotNull Test o) {
        return 0;
    }
}

When trying the correct import com.intellij.annotations.NotNull (I think) it looks like it can't find the class:

Body:
I found I had to add the following dependency declaration to my Java project's build.gradle file before I was able to import the org.jetbrains.annotations.NotNull and org.jetbrains.annotations.Nullable annotations rather than the com.sun.istack.internal.NotNull and com.sun.istack.internal.Nullable annotations:

repositories {
    mavenCentral()
}

dependencies {
    compile 'org.jetbrains:annotations:15.0'
}


问:
Repeat async task by timer in xamarin forms
i'm new to xamarin.forms development and i'm still having my first steps from the few tutorials that are found on the net.
I have an async task that returns the time from date.jsontest.com
and i have a timer that decrements a text in a label.
i want to put the async task in the timer so that it repeats itself and displays the time on the label however im getting cannot convert async lamba to func

here's my code please help me, thanks

```<code>static async Task<string> RequestTimeAsync()
    {
        using (var client = new HttpClient())
        {
            var jsonString = await client.GetStringAsync("http://date.jsontest.com/");
            var jsonObject = JObject.Parse(jsonString);
            return jsonObject["time"].Value<string>();
        }
    }

 protected override async void OnAppearing()
    {
        base.OnAppearing();

        timeLabel.Text = await RequestTimeAsync();

        Device.StartTimer(TimeSpan.FromSeconds(1), () => { // i want the taks to be put
//here so that it gets repeated
            var number = float.Parse(button.Text) - 1;
            button.Text = number.ToString();
            return number > 0;
        });

    }
</code>```

Reloading the Content Page in the timer would do the trick, so if anybody can please help me it would be appreciated

答:
You just need to wrap the async method call in a Task.Run(), for example:</p>

```<code>Device.StartTimer(TimeSpan.FromSeconds(1), () =>
{
  Task.Run(async () =>
  {
    var time = await RequestTimeAsync();
    // do something with time...
  });
  return true;
});
</code>```

Body:
i'm new to xamarin.forms development and i'm still having my first steps from the few tutorials that are found on the net.
I have an async task that returns the time from date.jsontest.com
and i have a timer that decrements a text in a label.
i want to put the async task in the timer so that it repeats itself and displays the time on the label however im getting cannot convert async lamba to func

here's my code please help me, thanks

static async Task<string> RequestTimeAsync()
    {
        using (var client = new HttpClient())
        {
            var jsonString = await client.GetStringAsync("http://date.jsontest.com/");
            var jsonObject = JObject.Parse(jsonString);
            return jsonObject["time"].Value<string>();
        }
    }

 protected override async void OnAppearing()
    {
        base.OnAppearing();

        timeLabel.Text = await RequestTimeAsync();

        Device.StartTimer(TimeSpan.FromSeconds(1), () => { // i want the taks to be put
//here so that it gets repeated
            var number = float.Parse(button.Text) - 1;
            button.Text = number.ToString();
            return number > 0;
        });

    }

Reloading the Content Page in the timer would do the trick, so if anybody can please help me it would be appreciated

Body:
You just need to wrap the async method call in a Task.Run(), for example:

Device.StartTimer(TimeSpan.FromSeconds(1), () =>
{
  Task.Run(async () =>
  {
    var time = await RequestTimeAsync();
    // do something with time...
  });
  return true;
});


问:
Creating a Function that works for 2 models in Rails
I have two models which need an identical function. I'd like to learn how to make this DRY the right rails way...

For both models I have:

```<code>before_save :assign_uuid
</code>```

Which in each model has:

```<code>  def assign_uuid
    if self.uuid.nil?
      self.uuid = ActiveSupport::SecureRandom.hex(32)
    end
  end
</code>```

Since, assign_uuid lives in both models, Where is the one place I should place this func? Also, in the models, where it say's before_save. How do I call the assign_uuid in the location it is located?

Thanks

答:
In your lib folder, add a file uuid_lib.rb, and write

```<code>module UuidLib

  def assign_uuid
    if self.uuid.nil?
      self.uuid = ActiveSupport::SecureRandom.hex(32)
    end
  end
end
</code>```

and inside your model write

```<code>include UuidLib

before_save :assign_uuid
</code>```

An example article explaining modules and mixins in more detail can be found here.

Body:
I have two models which need an identical function. I'd like to learn how to make this DRY the right rails way...

For both models I have:

before_save :assign_uuid

Which in each model has:

  def assign_uuid
    if self.uuid.nil?
      self.uuid = ActiveSupport::SecureRandom.hex(32)
    end
  end

Since, assign_uuid lives in both models, Where is the one place I should place this func? Also, in the models, where it say's before_save. How do I call the assign_uuid in the location it is located?

Thanks

Body:
In your lib folder, add a file uuid_lib.rb, and write

module UuidLib

  def assign_uuid
    if self.uuid.nil?
      self.uuid = ActiveSupport::SecureRandom.hex(32)
    end
  end
end

and inside your model write

include UuidLib

before_save :assign_uuid

An example article explaining modules and mixins in more detail can be found here.


问:
Learning SQL: Need help Using HAVING to get the MIN result from an aggregate
was hoping to get some help. New to SQL and trying to keep my head on straight.

I've been given this assignment:

"Using HAVING, determine whose Direct Reports have the lowest Avg Salary."

My logic was to make a join on a derived table that would calculate the AVG salary of the crew for each Manager that had direct reports. This result would then get filtered to the MIN value by a HAVING clause.

```<code>SELECT Flash.firstname, Flash.lastname, Wally.AVGSalary,
       Wally.[Direct Reports] FROM CrewMembers Flash
    JOIN
    (
        SELECT Barry.crewMemberId, AVG(Zoom.salary) AS 'AVGSalary', COUNT(Zoom.firstname) AS 'Direct Reports'
                    FROM CrewMembers Barry
            JOIN CrewMembers Zoom
                           ON Zoom.managerId = Barry.crewMemberId
        GROUP BY Barry.crewMemberId
    )
    AS Wally ON Wally.crewMemberId = Flash.crewMemberId

GROUP BY Flash.firstname, Flash.lastname, Wally.AVGSalary, Wally.[Direct Reports]

HAVING MIN(Wally.AVGSalary) in (Wally.AVGSalary)

ORDER BY Wally.AVGSalary asc
</code>```

I'm getting this result:

```<code>firstname   lastname    AVGSalary   Direct Reports
Mike        Patton      33666.500000    2
Kurt        Corgan      37300.000000    2
Amber       Bruckner    45851.666666    3
Doug        Adams       86250.000000    2
Montgomery  Scott       92500.000000    2
James       Kirk        132666.750000   3
</code>```

I'm stumped. I need it to give me JUST the row with the minimum value and it's giving me every value. I've stared at this and can't figure out what I'm doing wrong.

I know, from looking at threads online, that using TOP is a way to filter items, but that hasn't been introduced yet and I'd like to stay within the parameters that have been established in the course so far.

Any critique of what I've written or any help would be awesome. Like I said, I'm new and just trying to keep up.

Thanks,

J

答:
You should use HAVING with equals to instead of IN so something like:

HAVING Wally.AVGSalary = MIN(Wally.AVGSalary)

In your case with IN it will return all rows and you want only the want with salary equals to lowest one.

Body:
was hoping to get some help. New to SQL and trying to keep my head on straight.

I've been given this assignment:

"Using HAVING, determine whose Direct Reports have the lowest Avg Salary."

My logic was to make a join on a derived table that would calculate the AVG salary of the crew for each Manager that had direct reports. This result would then get filtered to the MIN value by a HAVING clause.

SELECT Flash.firstname, Flash.lastname, Wally.AVGSalary,
       Wally.[Direct Reports] FROM CrewMembers Flash
    JOIN
    (
        SELECT Barry.crewMemberId, AVG(Zoom.salary) AS 'AVGSalary', COUNT(Zoom.firstname) AS 'Direct Reports'
                    FROM CrewMembers Barry
            JOIN CrewMembers Zoom
                           ON Zoom.managerId = Barry.crewMemberId
        GROUP BY Barry.crewMemberId
    )
    AS Wally ON Wally.crewMemberId = Flash.crewMemberId

GROUP BY Flash.firstname, Flash.lastname, Wally.AVGSalary, Wally.[Direct Reports]

HAVING MIN(Wally.AVGSalary) in (Wally.AVGSalary)

ORDER BY Wally.AVGSalary asc

I'm getting this result:

firstname   lastname    AVGSalary   Direct Reports
Mike        Patton      33666.500000    2
Kurt        Corgan      37300.000000    2
Amber       Bruckner    45851.666666    3
Doug        Adams       86250.000000    2
Montgomery  Scott       92500.000000    2
James       Kirk        132666.750000   3

I'm stumped. I need it to give me JUST the row with the minimum value and it's giving me every value. I've stared at this and can't figure out what I'm doing wrong.

I know, from looking at threads online, that using TOP is a way to filter items, but that hasn't been introduced yet and I'd like to stay within the parameters that have been established in the course so far.

Any critique of what I've written or any help would be awesome. Like I said, I'm new and just trying to keep up.

Thanks,

J


问:
Why is the __str__ method printing the nodes in an recursive way in a linked list?
Just wondering what's the correct way of showing the next node in the __str__ method. See the following code and the results. It looks like there's some built-in recursive nature chaining the __str__ methods for each node in the list. Could anyone explain why and how I can make it behave normally, like only printing the next node's address. Thanks.

```<code>class Node(object):
    def __init__(self, x):
        self.val = x
        self.next = None
    def __str__(self):
        return "Node {}, next is {}".format(self.val, self.next)

a = Node(1)
b = Node(2)
c = Node(3)
a.next = b
b.next = c
print(a)
Node 1, next is Node 2, next is Node 3, next is None
</code>```

答:
The reason this is printing all the nodes is because .format convert each input into a string before concatenating it. To do this, it calls the __str__ method of the next node and the cycle continues.

There are two options to get it to act the way you want. In the __str__ method you can call the __repr__, !r, or you can get the memory location manually using id and format it any way you want.

```<code>return "Node {}, next is {!r}".format(self.val, self.next)
# or
return "Node {}, next is <__main__.Node object at {}>".format(self.val, hex(id(self.next)))
</code>```

Both of these result in the same output:

```<code>Node 1, next is <__main__.Node object at 0x1005d7fd0>
</code>```

Body:
Just wondering what's the correct way of showing the next node in the __str__ method. See the following code and the results. It looks like there's some built-in recursive nature chaining the __str__ methods for each node in the list. Could anyone explain why and how I can make it behave normally, like only printing the next node's address. Thanks.

class Node(object):
    def __init__(self, x):
        self.val = x
        self.next = None
    def __str__(self):
        return "Node {}, next is {}".format(self.val, self.next)

a = Node(1)
b = Node(2)
c = Node(3)
a.next = b
b.next = c
print(a)
Node 1, next is Node 2, next is Node 3, next is None

Body:
The reason this is printing all the nodes is because .format convert each input into a string before concatenating it. To do this, it calls the __str__ method of the next node and the cycle continues.

There are two options to get it to act the way you want. In the __str__ method you can call the __repr__, !r, or you can get the memory location manually using id and format it any way you want.

return "Node {}, next is {!r}".format(self.val, self.next)
# or
return "Node {}, next is <__main__.Node object at {}>".format(self.val, hex(id(self.next)))

Both of these result in the same output:

Node 1, next is <__main__.Node object at 0x1005d7fd0>


问:
ADFS Single Signout not working in Internet explorer 10
We have an application that is using ADFS for authentication.  For the single signout we are redirecting the application to the url https:///adfs/ls/?wa=wsignout1.0.

The Application gets redirected to the URL without any issue but the signout is not working in INternet explorer.  In Chrome and Mozilla this single signout is working fine without any issue.

Has anybody face this issue and what was the workaround?

答:
Actually, from your post, I believe it is working correctly from everywhere. However, since you are using IE and likely on a domain joined machine you are silently signed in with desktop SSO (i.e. windows integrated authentication). For example, if you signed in from outside your corp network on IE and then signed out and signed-in again, you will see the behavior to be different.

Thanks
//Sam (Twitter: @MrADFS)


问:
Best practice to use aria-label as a selector for styling
I am styling a table that has table cells with (non-interactive) checkmarks in it. The checkmark icons are added via CSS. As there is no accessible content in it, I added an aria-label to it. Now I wonder if it is a good idea to use this attribute as a CSS selector to add those checkmark icons like this:

```<code>td[aria-label="yes"] {
  &:after {
    content: '\f00c';
    font-family: $font-family-icons;
  }
}
</code>```

I learned that using ARIA attributes as selectors is generally a good practice, at least for state related attributes like aria-hidden, aria-expanded etc. In this case it made sense to me to have the td styling coupled to the corresponding label. But of course if those labels change at some time I'll need to adapt the CSS too.

Do you know any other drawbacks apart from that? Or do you have ideas on how to solve this more elegantly?

答:
Do you know any other drawbacks apart from that?

On using aria-label attribute as a selector for styling, there's technically no problem.

Concerning this use of aria-label

It's itself not sufficient enough to be a valid alternative text for all kind of accessibility concerns.

Very few people use a screen-reader. If aria-label can be an help for them (depending on screen reader support, see @aardrian answer), it's of no use for a large part of the population.

A special UTF-8 code representing a checkmark is nothing else visually than an image, and users may expect, for instance, to have a tooltip. For that matter, the title attribute is recommended, used conjointly with aria-label for better browser and screen reader support.

Someone using a screen magnifier or with a a cognitive disorder, may then be able to access the alternative text of the checkmark without having to scroll to the table heading of the column.

The problem will still be important for someone with motor disabilities because having to scroll to see the heading or using the mouse to see what this checkmark means is still very difficult.

TLDR: ARIA does not give universal accessibility for all kind of disabilities

Body:
I am styling a table that has table cells with (non-interactive) checkmarks in it. The checkmark icons are added via CSS. As there is no accessible content in it, I added an aria-label to it. Now I wonder if it is a good idea to use this attribute as a CSS selector to add those checkmark icons like this:

td[aria-label="yes"] {
  &:after {
    content: '\f00c';
    font-family: $font-family-icons;
  }
}

I learned that using ARIA attributes as selectors is generally a good practice, at least for state related attributes like aria-hidden, aria-expanded etc. In this case it made sense to me to have the td styling coupled to the corresponding label. But of course if those labels change at some time I'll need to adapt the CSS too.

Do you know any other drawbacks apart from that? Or do you have ideas on how to solve this more elegantly?


问:
Kafka 0.10 SASL/PLAIN producer timeout
I've got a 3 broker kerberised Kafka 0.10 install running in Cloudera and I'm trying to authenticate with SASL/PLAIN

I'm passing kafka_server_jaas.conf into the JVM on each of the brokers.

KafkaServer {
  org.apache.kafka.common.security.plain.PlainLoginModule required
  username=admin
  password=password1
  user_admin=password1
  user_remote=password1;
};

My server.properties (or kafka.properties as Cloudera renames it) is set as below;

listeners=SASL_SSL://10.10.3.47:9093 # ip set for each broker
advertised.listeners=SASL_SSL://10.10.3.47:9093 # ip set for each broker
sasl.enabled.mechanisms=GSSAPI,PLAIN
security.inter.broker.protocol=SASL_SSL
sasl.mechanism.inter.broker.protocol=GSSAPI

When Kafka starts up, the inter-broker communication is all fine, but when I try to connect using the console producer I get a Timeout failed to update metadata

bin/kafka-consolproducer --broker-list 10.10.3.161:9093 --topic test1 --producer.config client.properties.plain

client.properties.plain is set to

security.protocol=SASL_SSL
sasl.mechanism=PLAIN

finally, the client side jaas.conf

KafkaClient {
        org.apache.kafka.common.security.plain.PlainLoginModule required
        username="remote"
        password="password1";
};

As far as I can tell I've followed all instructions correctly, can anyone see anything wrong?

Update
I've turned the logging on the console consumer up a bit, I'm getting the following error;

[2017-03-02 13:17:50,817] TRACE SSLHandshake NEED_UNWRAP channelId -1, handshakeResult Status = OK HandshakeStatus = FINISHED
bytesConsumed = 101 bytesProduced = 0, appReadBuffer pos 0, netReadBuffer pos 0, netWriteBuffer pos 101 (org.apache.kafka.common.network.SslTransportLayer)
[2017-03-02 13:17:50,817] TRACE SSLHandshake FINISHED channelId -1, appReadBuffer pos 0, netReadBuffer pos 0, netWriteBuffer pos 101  (org.apache.kafka.common.network.SslTransportLayer)
[2017-03-02 13:17:50,817] DEBUG Set SASL client state to RECEIVE_HANDSHAKE_RESPONSE (org.apache.kafka.common.security.authenticator.SaslClientAuthenticator)
[2017-03-02 13:17:50,818] DEBUG Set SASL client state to INITIAL (org.apache.kafka.common.security.authenticator.SaslClientAuthenticator)
[2017-03-02 13:17:50,819] DEBUG Set SASL client state to INTERMEDIATE (org.apache.kafka.common.security.authenticator.SaslClientAuthenticator)
[2017-03-02 13:17:50,820] DEBUG Connection with <IPADDESS_REMOVED> disconnected (org.apache.kafka.common.network.Selector)
java.io.EOFException
        at org.apache.kafka.common.network.SslTransportLayer.read(SslTransportLayer.java:488)
        at org.apache.kafka.common.network.NetworkReceive.readFromReadableChannel(NetworkReceive.java:81)
        at org.apache.kafka.common.network.NetworkReceive.readFrom(NetworkReceive.java:71)
        at org.apache.kafka.common.security.authenticator.SaslClientAuthenticator.receiveResponseOrToken(SaslClientAuthenticator.java:239)
        at org.apache.kafka.common.security.authenticator.SaslClientAuthenticator.authenticate(SaslClientAuthenticator.java:182)
        at org.apache.kafka.common.network.KafkaChannel.prepare(KafkaChannel.java:64)
        at org.apache.kafka.common.network.Selector.pollSelectionKeys(Selector.java:318)
        at org.apache.kafka.common.network.Selector.poll(Selector.java:283)
        at org.apache.kafka.clients.NetworkClient.poll(NetworkClient.java:260)
        at org.apache.kafka.clients.consumer.internals.ConsumerNetworkClient.clientPoll(ConsumerNetworkClient.java:360)
        at org.apache.kafka.clients.consumer.internals.ConsumerNetworkClient.poll(ConsumerNetworkClient.java:224)
        at org.apache.kafka.clients.consumer.internals.ConsumerNetworkClient.poll(ConsumerNetworkClient.java:192)
        at org.apache.kafka.clients.consumer.internals.ConsumerNetworkClient.awaitMetadataUpdate(ConsumerNetworkClient.java:134)
        at org.apache.kafka.clients.consumer.internals.AbstractCoordinator.ensureCoordinatorReady(AbstractCoordinator.java:183)
        at org.apache.kafka.clients.consumer.KafkaConsumer.pollOnce(KafkaConsumer.java:974)
        at org.apache.kafka.clients.consumer.KafkaConsumer.poll(KafkaConsumer.java:938)
        at kafka.consumer.NewShinyConsumer.<init>(BaseConsumer.scala:61)
        at kafka.tools.ConsoleConsumer$.run(ConsoleConsumer.scala:64)
        at kafka.tools.ConsoleConsumer$.main(ConsoleConsumer.scala:51)
        at kafka.tools.ConsoleConsumer.main(ConsoleConsumer.scala)
[2017-03-02 13:17:50,821] DEBUG Node -1 disconnected. (org.apache.kafka.clients.NetworkClient)

答:
I had a similar issue with SASL_PLAINTEXT auth. I was able to connect to the broker (via kafka-python), but any messages I sent from the producer would simply time out.

I ended up advertising both SASL_PLAINTEXT and PLAINTEXT listeners, but only publicly exposed the SASL_PLAINTEXT listener via AWS security groups.

My server_jaas.conf was basically the same.

My server.properties used these settings:

```<code>security.inter.broker.protocol=PLAINTEXT
sasl.mechanism.inter.broker.protocol=PLAIN
sasl.enabled.mechanisms=PLAIN
advertised.listeners=SASL_PLAINTEXT://example.com:9095,PLAINTEXT://example.com:9092
listeners = SASL_PLAINTEXT://0.0.0.0:9095,PLAINTEXT://0.0.0.0:9092
</code>```

I was debugging this with the kafka-python client and my command looked like this (python)

```<code>from kafka import KafkaProducer
producer = KafkaProducer(bootstrap_servers='example.com:9095', security_protocol="SASL_PLAINTEXT", sasl_mechanism='PLAIN', sasl_plain_username='username', sasl_plain_password='password')
</code>```

With this setup I was able to have username/password authentication and also produce and consume messages to the broker without timeouts.

Hope this helps in some way :)

Title: Kafka 0.10 SASL/PLAIN producer timeout

Body:
I had a similar issue with SASL_PLAINTEXT auth. I was able to connect to the broker (via kafka-python), but any messages I sent from the producer would simply time out.

I ended up advertising both SASL_PLAINTEXT and PLAINTEXT listeners, but only publicly exposed the SASL_PLAINTEXT listener via AWS security groups.

My server_jaas.conf was basically the same.

My server.properties used these settings:

security.inter.broker.protocol=PLAINTEXT
sasl.mechanism.inter.broker.protocol=PLAIN
sasl.enabled.mechanisms=PLAIN
advertised.listeners=SASL_PLAINTEXT://example.com:9095,PLAINTEXT://example.com:9092
listeners = SASL_PLAINTEXT://0.0.0.0:9095,PLAINTEXT://0.0.0.0:9092

I was debugging this with the kafka-python client and my command looked like this (python)

from kafka import KafkaProducer
producer = KafkaProducer(bootstrap_servers='example.com:9095', security_protocol="SASL_PLAINTEXT", sasl_mechanism='PLAIN', sasl_plain_username='username', sasl_plain_password='password')

With this setup I was able to have username/password authentication and also produce and consume messages to the broker without timeouts.

Hope this helps in some way :)


问:
How to structure content in Ruby (RoR) app?
I am in the process of building a super simple CMS to handle smaller "static" page type projects (e.g. - small sites for friends). I have different "page types" that I would like to add. I built something similar in Coldfusion previously. Looked something like this:

table content_type:

```<code>content_type_code varchar(10)
content_type_name
</code>```

table content:

```<code>content_id
content_type_code varchar(10)
content_name
content_desc
content_url
</code>```

I would create a content type called "blog" or "photo" and each time a content was added, it'd get assigned the content_type_code. Then in /blog/ I'd query for all content that had a content_type_code of "blog".

Now that I'm using Ruby/RoR I am trying to think about things differently. I was thinking a better way might be to use nested pages with awesome_nested_set (https://github.com/collectiveidea/awesome_nested_set). But I'm not sure if that's the best solution.

Then I could create a page called "blog" and add to that many pages. So essentially the top level would take place of the "content_type" from my previous example.

Can someone steer me in the right direction on what the best method would be? I'm a newb looking for a kick in the right direction.

EDIT

I should add that the only real thing that I would change between the different "types" of content would be the layout and where they are displayed ("photo" content at /photos/, "blog" content at /blog/).

答:
I try to recap:

You want to build a CMS

Your CMS manages a single web site

A web site is made of content

There are differenti type of contents, and I am assuming every type of content has its own behaviour

Contents are organized in a tree

Here is the plan I suggest you:

Create the Content resource; use the scaffold to have something already working, adding few field (title and body in example)

Add validations to your new model

Write a couple of unit tests against your validation (quite useless, just to see how it works)

Install awesome_nested_set and manage to make it working with your model

Work on the UI to make it quite easy to create new content, move content around, edit a single content

Now its time to implement the content types; STI is the Rails way, but I have to warn you it can be really hard. I suggest you to reiterate 1, 2, 3, 5 to create new models for Photo and BlogPost

Once you will be there, you will have hundreds of ideas to implement. Have fun :)

Body:
I am in the process of building a super simple CMS to handle smaller "static" page type projects (e.g. - small sites for friends). I have different "page types" that I would like to add. I built something similar in Coldfusion previously. Looked something like this:

table content_type:

content_type_code varchar(10)
content_type_name

table content:

content_id
content_type_code varchar(10)
content_name
content_desc
content_url

I would create a content type called "blog" or "photo" and each time a content was added, it'd get assigned the content_type_code. Then in /blog/ I'd query for all content that had a content_type_code of "blog".

Now that I'm using Ruby/RoR I am trying to think about things differently. I was thinking a better way might be to use nested pages with awesome_nested_set (https://github.com/collectiveidea/awesome_nested_set). But I'm not sure if that's the best solution.

Then I could create a page called "blog" and add to that many pages. So essentially the top level would take place of the "content_type" from my previous example.

Can someone steer me in the right direction on what the best method would be? I'm a newb looking for a kick in the right direction.

EDIT

I should add that the only real thing that I would change between the different "types" of content would be the layout and where they are displayed ("photo" content at /photos/, "blog" content at /blog/).


问:
xsl transform generating xsl stylesheet in a .net environment
What xsl do I need to use myVar1 variable inside myVar2? I'm using an xsl transform to produce the new stylesheet.</p>

```<code>    <xsl:element name="variable"><xsl:attribute name="myVar1">test value</xsl:attribute> </xsl:element>

    <xsl:element name="variable">
      <xsl:attribute name="myVar2" />
      <xsl:element name="xsl:value-of">
        <xsl:attribute name="select">
          /root/child[@myattr1='$myVar1']/@value      <!--Help here-->
        </xsl:attribute>
      </xsl:element>
    </xsl:element>
  </xsl:template>
</code>```

答:
I think you mean </p>

```<code><xsl:attribute name="select">
  <xsl:value-of select="concat('/root/child[@myattr1=',$myVar1,']/@value')"/>
</xsl:attribute>
</code>```

Body:
What xsl do I need to use myVar1 variable inside myVar2? I'm using an xsl transform to produce the new stylesheet.

    <xsl:element name="variable"><xsl:attribute name="myVar1">test value</xsl:attribute> </xsl:element>

    <xsl:element name="variable">
      <xsl:attribute name="myVar2" />
      <xsl:element name="xsl:value-of">
        <xsl:attribute name="select">
          /root/child[@myattr1='$myVar1']/@value
        </xsl:attribute>
      </xsl:element>
    </xsl:element>
  </xsl:template>

Body:
I think you mean

<xsl:attribute name="select">
  <xsl:value-of select="concat('/root/child[@myattr1=',$myVar1,']/@value')"/>
</xsl:attribute>


问:
Bash: Prune find results using absolute paths
I'm running a script to look through some folders for a file type, but I need to prune a few folders. The script works when I run it via PuTTy using relative filepaths, but when I add in the absolute file paths so I can run it as a cron task, it doesn't prune correctly.

Here's my command:

```<code>/bin/find . -not \( -path "./Ready" -prune \) -not \( -path "./Loading" -prune \) -not \( -path "./Backups" -prune \) -name "*.txt"
</code>```

However, when I replace "./" with the full path, it returns results for files in the folders it shouldn't be searching.

Any ideas? Thanks in advance.

答:
Note that the pattern match test applies to the whole file name,
  starting from one of the start points named on the command line.  It
  would only  make
                sense to use an absolute path name here if the relevant start point is also an absolute path.  This means that this command
  will never match anything:

find bar -path /foo/bar/myfile -print

You need to use the absolute path as search base too, so exchange the first . (the starting point of the search) with the same absolute path you use for the -path arguments.

```<code>find /usr -path "/usr/src/linux*" -prune -o -path "/usr/inclu*" -prune -o -name "*.txt" -print
</code>```

This will list all *.txt files but the content of any directory starting with /usr/src/linux* or /usr/inclu*.

Body:
I'm running a script to look through some folders for a file type, but I need to prune a few folders. The script works when I run it via PuTTy using relative filepaths, but when I add in the absolute file paths so I can run it as a cron task, it doesn't prune correctly.

Here's my command:

/bin/find . -not \( -path "./Ready" -prune \) -not \( -path "./Loading" -prune \) -not \( -path "./Backups" -prune \) -name "*.txt"

However, when I replace "./" with the full path, it returns results for files in the folders it shouldn't be searching.

Any ideas? Thanks in advance.

Body:
Note that the pattern match test applies to the whole file name,
  starting from one of the start points named on the command line.  It
  would only  make
                sense to use an absolute path name here if the relevant start point is also an absolute path.  This means that this command
  will never match anything:

find bar -path /foo/bar/myfile -print

You need to use the absolute path as search base too, so exchange the first . (the starting point of the search) with the same absolute path you use for the -path arguments.

find /usr -path "/usr/src/linux*" -prune -o -path "/usr/inclu*" -prune -o -name "*.txt" -print

This will list all *.txt files but the content of any directory starting with /usr/src/linux* or /usr/inclu*.


问:
C++ RemoveFront function for Doubly Linked List
I'm working on a lab for school and I'm stuck on a function for a doubly linked list. When I try to remove the front node from the list with the removeFront() function it returns NULL and couts for me to create a list even though there already is one. I'll post my cpp file and main below and hopefully someone can help me understand what's going wrong with it.</p>

```<code>//DLinkedList.h

#pragma once

#include <string>
using namespace std;

typedef string Elem;

struct DNode
{
    Elem value;
    DNode* next;
    DNode* prev;
};

class DLinkedList
{
public:
    DLinkedList() { header_ = NULL; }
    ~DLinkedList() { };
    bool empty() const;
    const Elem& front() const;
    const Elem& back() const;
    void addFront(const Elem& e);
    void addBack(const Elem& e);
    void removeFront();
    void removeBack();

private:
    DNode* header_;
    DNode* trailer_;

protected:
    void add(DNode* v, const DNode& e);
    void remove(DNode* v);
};

//DLinkedList.cpp

#include <iostream>
#include "DLinkedList.h"

using namespace std;

const Elem& DLinkedList::front() const
{
    if (header_ == NULL)
    {
        cout << "Please create a doubly linked list first.\n\n";
    }
    else
    {
        return header_->value;
    }

}

void DLinkedList::addFront(const Elem& e) //DONE
{
    // If there is no header
    // create a temporary node and set
    // the header to it
    if (header_ == NULL)
    {
        DNode *temp;
        temp = new(struct DNode);
        temp->prev = NULL;
        temp->value = e;
        temp->next = NULL;

        header_ = temp;
        trailer_ = temp;
    }
    else
    {
        //Create current node to point to header
        // and temp node to be the new front node
        DNode *current;
        DNode *temp;
        current = header_;
        temp = new(struct DNode);
        temp->prev = NULL;
        temp->value = e;
        temp->next = current->next;

        header_->prev = temp->next;
        header_ = temp;
    }

    cout << "Element Inserted at the front." << endl;

}

void DLinkedList::removeFront()
{
    // Check to see if there is anything
    // in the list first
    if (header_ == NULL)
    {
        cout << "Create a doubly linked list first.";
    }

    // Check to see if the list has more than one item.
    // If it only has one node erase it.
    DNode *current;
    current = header_;

    if (current->next == NULL)
    {
        header_->next = NULL;
        header_->value = "";
        header_->prev = NULL;
        header_ = NULL;
    }
    else
    {
        current = current->next;
        //header_->next = NULL;
        //header_->value = "";
        //header_->prev = NULL;
        header_ = current;
        header_->prev = NULL;
    }
}

//Main.cpp

#include <iostream>
#include <string>
#include <cassert>
#include "DLinkedList.h"

using namespace std;

int main()
{
    DLinkedList album;
    album.addFront("Word");
    album.addFront("Turn");
    album.addFront("Bird");
    album.addFront("Weird");

    cout << album.front() << endl;

    album.removeFront();

    cout << album.front() << endl;

    system("pause");

    return 0;
}
</code>```

答:
This how i would do it.</p>

```<code>void DLinkedList::removeFront()
    {
        // Check to see if there is anything
        // in the list first
        if (header_ == NULL)
        {
            cout << "Create a doubly linked list first.";
        }

        // Check to see if the list has more than one item.
        // If it only has one node erase it.
        if (header_->next == NULL)
        {
            delete header_;
        }
        else
        {
            DNode* next = header_->next;
            delete header_;
            header_ = next;
            header_->prev = NULL;
        }
    }
</code>```

Body:
I'm working on a lab for school and I'm stuck on a function for a doubly linked list. When I try to remove the front node from the list with the removeFront() function it returns NULL and couts for me to create a list even though there already is one. I'll post my cpp file and main below and hopefully someone can help me understand what's going wrong with it.

//DLinkedList.h

#pragma once

#include <string>
using namespace std;

typedef string Elem;

struct DNode
{
    Elem value;
    DNode* next;
    DNode* prev;
};

class DLinkedList
{
public:
    DLinkedList() { header_ = NULL; }
    ~DLinkedList() { };
    bool empty() const;
    const Elem& front() const;
    const Elem& back() const;
    void addFront(const Elem& e);
    void addBack(const Elem& e);
    void removeFront();
    void removeBack();

private:
    DNode* header_;
    DNode* trailer_;

protected:
    void add(DNode* v, const DNode& e);
    void remove(DNode* v);
};

//DLinkedList.cpp

#include <iostream>
#include "DLinkedList.h"

using namespace std;

const Elem& DLinkedList::front() const
{
    if (header_ == NULL)
    {
        cout << "Please create a doubly linked list first.\n\n";
    }
    else
    {
        return header_->value;
    }

}

void DLinkedList::addFront(const Elem& e) //DONE
{
    // If there is no header
    // create a temporary node and set
    // the header to it
    if (header_ == NULL)
    {
        DNode *temp;
        temp = new(struct DNode);
        temp->prev = NULL;
        temp->value = e;
        temp->next = NULL;

        header_ = temp;
        trailer_ = temp;
    }
    else
    {
        //Create current node to point to header
        // and temp node to be the new front node
        DNode *current;
        DNode *temp;
        current = header_;
        temp = new(struct DNode);
        temp->prev = NULL;
        temp->value = e;
        temp->next = current->next;

        header_->prev = temp->next;
        header_ = temp;
    }

    cout << "Element Inserted at the front." << endl;

}

void DLinkedList::removeFront()
{
    // Check to see if there is anything
    // in the list first
    if (header_ == NULL)
    {
        cout << "Create a doubly linked list first.";
    }

    // Check to see if the list has more than one item.
    // If it only has one node erase it.
    DNode *current;
    current = header_;

    if (current->next == NULL)
    {
        header_->next = NULL;
        header_->value = "";
        header_->prev = NULL;
        header_ = NULL;
    }
    else
    {
        current = current->next;
        //header_->next = NULL;
        //header_->value = "";
        //header_->prev = NULL;
        header_ = current;
        header_->prev = NULL;
    }
}

//Main.cpp

#include <iostream>
#include <string>
#include <cassert>
#include "DLinkedList.h"

using namespace std;

int main()
{
    DLinkedList album;
    album.addFront("Word");
    album.addFront("Turn");
    album.addFront("Bird");
    album.addFront("Weird");

    cout << album.front() << endl;

    album.removeFront();

    cout << album.front() << endl;

    system("pause");

    return 0;
}

Body:
This how i would do it.

void DLinkedList::removeFront()
    {
        // Check to see if there is anything
        // in the list first
        if (header_ == NULL)
        {
            cout << "Create a doubly linked list first.";
        }

        // Check to see if the list has more than one item.
        // If it only has one node erase it.
        if (header_->next == NULL)
        {
            delete header_;
        }
        else
        {
            DNode* next = header_->next;
            delete header_;
            header_ = next;
            header_->prev = NULL;
        }
    }


问:
Ignore missing properties during Jackson JSON deserialization in Java
In the example

class Person {
   String name;
   int age;
}
```
<p>If the JSON object has a missing property 'age',</p>
<pre class="lang-json prettyprint-override"><code>{
    "name": "John"
}
</code>```

Person person = objectMapper.readValue(jsonFileReader, Person.class);
```

it throws a JsonMappingException saying it cannot deserialize. Is there an annotation to ignore missing fields during deserialization?

答:
Annotation based approach is a better way for ignoring but If needed. The manual way of deserialization:</p>

```<code>ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Person       person = mapper.readValue(jsonFileReader, Person.class);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In the example

class Person {
   String name;
   int age;
}

If the JSON object has a missing property 'age',

{
    "name": "John"
}

Person person = objectMapper.readValue(jsonFileReader, Person.class);

it throws a JsonMappingException saying it cannot deserialize. Is there an annotation to ignore missing fields during deserialization?

Body:
Annotation based approach is a better way for ignoring but If needed. The manual way of deserialization:

ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Person       person = mapper.readValue(jsonFileReader, Person.class);


问:
segue only works on swipe of cell but not tap
I have a tableview (dynamic) which when tapped is meant to go to the detail view for each cell.

It doesn't move to the detail view if i tap the cell, but does if I swipe the cell.. its very strange.

I did copy this cell from another cell on a different view originally - I'm  not sure if that has something to do with it.

The original view (with the tableview) still works as normal, when tapped it goes to the detail.

The second screen only goes to the detail when swiped.

I have checked the properties, both are "show" segues on selection.

One other point, the first (working) one is from a cell in a TableViewController, the second is from a cell in a TableView.

Any ideas what's causing this?

答:
The problem was I had a searchbar on the page which had a tapgesture recogniser to dismiss keyboard when tapped anywhere else.

Removing this sort the issue!


问:
R httr error 403
I have a code in python working which uploads a file to server with following code

```<code> with open(file_path, 'rb') as fp:
     r = requests.Request('PUT', signedRequest, data=fp.read())
     prepped = r.prepare()
     s = requests.Session()
     resp = s.send(prepped)
</code>```

In R I am using the following code as it's replacement

```<code>PUT(url = signedRequest,
    body = upload_file(path = file_path),verbose()
   )
</code>```

But it is throwing out error

```<code>HTTP/1.1 403 Forbidden
</code>```

On requestbin the requests are received as

For Python

```<code>Cf-Connecting-Ip: ****
Host: requestb.in
Connect-Time: 1
Total-Route-Time: 0
Via: 1.1 vegur
Content-Length: 6481350
Connection: close
Cf-Ipcountry: US
X-Request-Id: f9b165cc-0f42-4eaa-8b40-2eb37a6ff1ca
Accept-Encoding: gzip
Cf-Ray: 346d734353e871df-ORD
Cf-Visitor: {"scheme":"http"}
</code>```

For R

```<code>Cf-Connecting-Ip: ****
Content-Length: 6481350
User-Agent: libcurl/7.47.0 r-curl/2.3 httr/1.2.1
Total-Route-Time: 0
Via: 1.1 vegur
Connection: close
Cf-Ipcountry: US
Content-Type: text/csv
X-Request-Id: 0bfbf6ab-4658-4650-bd4d-e1e19ffdba91
Accept: application/json, text/xml, application/xml, */*
Connect-Time: 0
Accept-Encoding: gzip
Host: requestb.in
Cf-Ray: 346d6e90d70f54ec-ORD
Cf-Visitor: {"scheme":"http"}
</code>```

Any suggestions?

答:
Hard to say exactly what the server is complaining about, but if we compare the two requests, we see there is a difference in content type and user-agent.

You can suppress the content type with

```<code>upload_file(path = file_path, type="")
</code>```

You can suppress the user agent by also passing

```<code>user_agent("")
</code>```

as a parameter to PUT()

Title: R httr error 403

Body:
I have a code in python working which uploads a file to server with following code

 with open(file_path, 'rb') as fp:
     r = requests.Request('PUT', signedRequest, data=fp.read())
     prepped = r.prepare()
     s = requests.Session()
     resp = s.send(prepped)

In R I am using the following code as it's replacement

PUT(url = signedRequest,
    body = upload_file(path = file_path),verbose()
   )

But it is throwing out error

HTTP/1.1 403 Forbidden

On requestbin the requests are received as

For Python

Cf-Connecting-Ip: ****
Host: requestb.in
Connect-Time: 1
Total-Route-Time: 0
Via: 1.1 vegur
Content-Length: 6481350
Connection: close
Cf-Ipcountry: US
X-Request-Id: f9b165cc-0f42-4eaa-8b40-2eb37a6ff1ca
Accept-Encoding: gzip
Cf-Ray: 346d734353e871df-ORD
Cf-Visitor: {"scheme":"http"}

For R

Cf-Connecting-Ip: ****
Content-Length: 6481350
User-Agent: libcurl/7.47.0 r-curl/2.3 httr/1.2.1
Total-Route-Time: 0
Via: 1.1 vegur
Connection: close
Cf-Ipcountry: US
Content-Type: text/csv
X-Request-Id: 0bfbf6ab-4658-4650-bd4d-e1e19ffdba91
Accept: application/json, text/xml, application/xml, */*
Connect-Time: 0
Accept-Encoding: gzip
Host: requestb.in
Cf-Ray: 346d6e90d70f54ec-ORD
Cf-Visitor: {"scheme":"http"}

Any suggestions?

Body:
Hard to say exactly what the server is complaining about, but if we compare the two requests, we see there is a difference in content type and user-agent.

You can suppress the content type with

upload_file(path = file_path, type="")

You can suppress the user agent by also passing

user_agent("")

as a parameter to PUT()


问:
"abline" doesn't work after "plot" when inside "with"
I want to create a scatterplot and draw the regression line for a subset of a dataset. To give a reproducible example I'll use the CO2 dataset.

I tried this but the regression line doesn't appear for some reason

```<code>with(subset(CO2,Type=="Quebec"),plot(conc,uptake),abline(lm(uptake~conc)))
</code>```

What is the correct way to give a command like this? Can I do it with a one-liner?

答:
Gavin and Joshua offer good solutions to your immediate problem; here's the equivalent plot using ggplot:</p>

```<code>library(ggplot2)
qplot(conc, uptake, data = CO2[CO2$Type == "Quebec" , ]) + stat_smooth(method = "lm", se = FALSE)
</code>```

Body:
I want to create a scatterplot and draw the regression line for a subset of a dataset. To give a reproducible example I'll use the CO2 dataset.

I tried this but the regression line doesn't appear for some reason

with(subset(CO2,Type=="Quebec"),plot(conc,uptake),abline(lm(uptake~conc)))

What is the correct way to give a command like this? Can I do it with a one-liner?

Body:
Gavin and Joshua offer good solutions to your immediate problem; here's the equivalent plot using ggplot:

library(ggplot2)
qplot(conc, uptake, data = CO2[CO2$Type == "Quebec" , ]) + stat_smooth(method = "lm", se = FALSE)


问:
Making Large IndexedDB Persistent in Browser
I am looking at making a LOB html5 web application. The main part we are trying to accomplish is to make the application offline capable. This will mean taking a large chunk of SQL data from the server and storing it in the browser. This will need to be living in the browser for quite a while, dont want to have to continuously refresh it everytime the browser is closed and reopened.

We are looking at storing the data inside the client in indexedDB but I read that indexedDB is stored in temporary storage so the lifetime of it cannot be relied on. Does anyone know of any strategies on prolonging its lifetime? Also we will be pulling down massive chunks of data so 1-5mb storage might not suffice what we require.

My current thought is to somewhat store it down to the browser storage using html5 storage API's and hydrate it into the indexedDb as it's required. Just need to make sure we can grow the storage limit to whatever we need.

Any advice on how we approach this?

答:
This might be a silly question to add, but can you access the storage area outside of the browser? For instance, if I did not want to have a huge lag when my app starts up and loads a bunch of data, could I make an external app to "refresh" the local data so that when the browser starts, it is ready to rock and roll?

I assume the answer here will be no, but I had to ask.

Has anyone worked around this for large data sets? For instance loading in one tab and working in another? Chrome extension to load, but access via the app?


问:
How do I remove the horizontal space around my list image?
On my website, I have had a list format menu at the top of the screen. I was wanting to place a small version of my company logo in the center of this menu, so I just added another list item for it on the test page:

```<code><nav id="main-navigation" data-content-field="navigation-mainNav">
     <ul class="cf">
          <li class="">
               <a href="/">Home</a></li>
          <li class="">
               <a href="/music/">Music</a></li>
          <li class="">
               <img src="/assets/img/glutenfreeradio.png" style="width:20%;height:20%;" /></li>
          <li class="">
               <a href="/reviews/">Reviews</a></li>
          <li class="">
               <a href="/contact/">Contact</a></li>
     </ul>
</nav>
</code>```

The problem is that, as you can see by viewing the links above, some ridiculous extra space has been added on the left and right sides of the list image. I definitely do not want that. I've been scouring the CSS and trying to figure out how to change it either there or directly in the HTML, but I'm at a loss.

答:
The image's inline styles are creating that space. Move those to the parent and adjust as needed.</p>

```<code><nav id="main-navigation" data-content-field="navigation-mainNav">
     <ul class="cf">
          <li class="">
               <a href="/">Home</a></li>
          <li class="">
               <a href="/music/">Music</a></li>
          <li class="" style="width:20%;height:20%;">
               <img src="/assets/img/glutenfreeradio.png"/></li>
          <li class="">
               <a href="/reviews/">Reviews</a></li>
          <li class="">
               <a href="/contact/">Contact</a></li>
     </ul>
</nav>
</code>```

Body:
On my website, I have had a list format menu at the top of the screen. I was wanting to place a small version of my company logo in the center of this menu, so I just added another list item for it on the test page:

               Home

               Music

               Reviews

               Contact

The problem is that, as you can see by viewing the links above, some ridiculous extra space has been added on the left and right sides of the list image. I definitely do not want that. I've been scouring the CSS and trying to figure out how to change it either there or directly in the HTML, but I'm at a loss.

Body:
The image's inline styles are creating that space. Move those to the parent and adjust as needed.

<nav id="main-navigation" data-content-field="navigation-mainNav">
     <ul class="cf">
          <li class="">
               <a href="/">Home</a></li>
          <li class="">
               <a href="/music/">Music</a></li>
          <li class="" style="width:20%;height:20%;">
               <img src="/assets/img/glutenfreeradio.png"/></li>
          <li class="">
               <a href="/reviews/">Reviews</a></li>
          <li class="">
               <a href="/contact/">Contact</a></li>
     </ul>
</nav>


问:
Store Enum as Char with Dapper
I have an enum like:

```<code>public enum AccountStatus : byte
{
    Locked = (byte)'L',
    Active = (byte)'A',
    Deleted = (byte)'D'
}
</code>```

and would like to to store the char values in the database.
Is there a way in Dapper with type maps or otherwise to define which enum types should be mapped to their char values (for read/update/insert)?

The anonymous type member declarator is also preventing me from casting the property to a char directly in the query:

答:
As mentioned by @TyCobb in the comments, this isn't an issue with storing an Enum as a char, but rather with how anonymous type properties are declared.

Anonymous types can only infer and generate names for "simple property references" where no transformation is done to the property during assignment, such as

```<code>new { account.AccountStatus }
</code>```

As soon as you transform the data or need to rename the property, you must explicitly declare the property name:

```<code>new { Status = (char)account.AccountStatus }
</code>```

In regards to reads, you can map to a char via dapper, then cast as your enum in your select (or transform the data in whatever way is most appropriate):

```<code>var result = connection.Query<char>(
    "select char column from table where Status = @Status",
    new {Status = (char)account.AccountStatus}
).Select(x => (AccountStatus)x).FirstOrDefault();
</code>```

In addition, Dapper also handles AccountStatus : byte cases natively, so you may be able to directly return the value as your enum:

```<code>var result = connection.Query<AccountStatus>(
    "select char column from table where Status = @Status",
    new {Status = (char)account.AccountStatus}
).FirstOrDefault();
</code>```

Title: Store Enum as Char with Dapper

Body:
I have an enum like:

public enum AccountStatus : byte
{
    Locked = (byte)'L',
    Active = (byte)'A',
    Deleted = (byte)'D'
}

and would like to to store the char values in the database.
Is there a way in Dapper with type maps or otherwise to define which enum types should be mapped to their char values (for read/update/insert)?

The anonymous type member declarator is also preventing me from casting the property to a char directly in the query:

Body:
As mentioned by @TyCobb in the comments, this isn't an issue with storing an Enum as a char, but rather with how anonymous type properties are declared.

Anonymous types can only infer and generate names for "simple property references" where no transformation is done to the property during assignment, such as

new { account.AccountStatus }

As soon as you transform the data or need to rename the property, you must explicitly declare the property name:

new { Status = (char)account.AccountStatus }

In regards to reads, you can map to a char via dapper, then cast as your enum in your select (or transform the data in whatever way is most appropriate):

var result = connection.Query<char>(
    "select char column from table where Status = @Status",
    new {Status = (char)account.AccountStatus}
).Select(x => (AccountStatus)x).FirstOrDefault();

In addition, Dapper also handles AccountStatus : byte cases natively, so you may be able to directly return the value as your enum:

var result = connection.Query<AccountStatus>(
    "select char column from table where Status = @Status",
    new {Status = (char)account.AccountStatus}
).FirstOrDefault();


问:
How do I parse an Excel file that will give me data exactly as it appears visually?
I'm on Rails 5 (Ruby 2.4).  I want to read an .xls doc and I would like to get the data into CSV format, just as it appears in the Excel file.  Someone recommended I use Roo, and so I have

```<code>book = Roo::Spreadsheet.open(file_location)
sheet = book.sheet(0)
text = sheet.to_csv
arr_of_arrs = CSV.parse(text)
</code>```

However what is getting returned is not the same as what I see in the spreadsheet.  For isntance, a cell in the spreadsheet has

```<code>16:45.81
</code>```

and when I get the CSV data from above, what is returned is

```<code>"0.011641319444444444"
</code>```

How do I parse the Excel doc and get exactly what I see?  I don't care if I use Roo to parse or not, just as long as I can get CSV data that is a representation of what I see rather than some weird internal representation.  For reference the file type I was parsing givies this when I run "file name_of_file.xls" ...

```<code>Composite Document File V2 Document, Little Endian, Os: Windows, Version 5.1, Code page: 1252, Author: Dwight Schroot, Last Saved By: Dwight Schroot, Name of Creating Application: Microsoft Excel, Create Time/Date: Tue Sep 21 17:05:21 2010, Last Saved Time/Date: Wed Oct 13 16:52:14 2010, Security: 0
</code>```

答:
You can use converters option. It seems looking like this:

arr_of_arrs = CSV.parse(text, {converters: :date_time})

http://ruby-doc.org/stdlib-2.0.0/libdoc/csv/rdoc/CSV.html

Body:
I'm on Rails 5 (Ruby 2.4).  I want to read an .xls doc and I would like to get the data into CSV format, just as it appears in the Excel file.  Someone recommended I use Roo, and so I have

book = Roo::Spreadsheet.open(file_location)
sheet = book.sheet(0)
text = sheet.to_csv
arr_of_arrs = CSV.parse(text)

However what is getting returned is not the same as what I see in the spreadsheet.  For isntance, a cell in the spreadsheet has

16:45.81

and when I get the CSV data from above, what is returned is

"0.011641319444444444"

How do I parse the Excel doc and get exactly what I see?  I don't care if I use Roo to parse or not, just as long as I can get CSV data that is a representation of what I see rather than some weird internal representation.  For reference the file type I was parsing givies this when I run "file name_of_file.xls" ...

Composite Document File V2 Document, Little Endian, Os: Windows, Version 5.1, Code page: 1252, Author: Dwight Schroot, Last Saved By: Dwight Schroot, Name of Creating Application: Microsoft Excel, Create Time/Date: Tue Sep 21 17:05:21 2010, Last Saved Time/Date: Wed Oct 13 16:52:14 2010, Security: 0


问:
Running python script in command prompt: syntax error unexpected character after line continuation character
I'm new to Python and have been trying to run a Python script through the cmd terminal (after invoking Python 3.6 in the Anaconda 4.3 distribution). I've looked through various forums which have outlined how to do this. I tried entering the following into the command prompt:

```<code>C:\Users\myname\Anaconda3\python.exe C:\Users\myname\Desktop\test.py
</code>```

However, I get the error "unexpected character after line continuation character". I got the same error when I tried to enter both pathnames separately as well. The reason I want to use the Anaconda distribution is because it has tensorflow installed on it. Thanks!

答:
Try putting the filename in quotation marks and see if that works.

If not, and you've installed anaconda, then you should be able to just type python "C:\Users\myname\Desktop\test.py". If python throws you the error then you need to check your python code. If the command prompt throws the error then check out how to add Anaconda's python to your environment variables.

Body:
I'm new to Python and have been trying to run a Python script through the cmd terminal (after invoking Python 3.6 in the Anaconda 4.3 distribution). I've looked through various forums which have outlined how to do this. I tried entering the following into the command prompt:

C:\Users\myname\Anaconda3\python.exe C:\Users\myname\Desktop\test.py

However, I get the error "unexpected character after line continuation character". I got the same error when I tried to enter both pathnames separately as well. The reason I want to use the Anaconda distribution is because it has tensorflow installed on it. Thanks!


问:
Totals on combo stacked bar/cumulative line chart in tableau
This is ultimately what I need in but in TableauSo I'm fairly new to Tableau and as I feared something extremely simple in Excel is proving to be rather complex in this new software.

I have a monthly running stacked bar chart of the closeouts by team(colored) and a line demonstrating the overall cumulative count of closeouts since the program started.

How do I simply add the total amount per month to a graph already using the Dual Axis feature for the cumulative running total?  Thank you!

This is what I have so far - Closeouts Combo Stacked Graph

答: It looks like you might have the label set to Line Ends. To check this do the following. Go to the marks card section on the left under filters. You will have three marks cards because of the dual axis, All, Bar and Line. Select the line card and click the label box. In there you can see if this is set to Line Ends under marks to label. Change this to All if so and see if that works.</p>


问:
str.split is not a function error in javascript
I keep getting an error when I input the following into Sublime:

function longestWord(str) {
  var result = str[0];
  str = str.split(' ');

  for (var i = 0; i < str.length; i++) {
    if (str[i].length > result.length) {
      result = str[i];
    }
  }
  return result;
}

var sentence = ["the quick brown fox jumped over the lazy dog."];

console.log(longestWord(sentence));```

I get an Uncaught TypeError: str.split is not a function(...)

What am I doing wrong?  Thank you!

答:
```<code>          function longestWord(str) {
             var result = str[0];
             str = str.split(' ');

              for (var i = 1; i < str.length; i++) {
                 if (str[i].length > result.length) {
                     result = str[i];
                 }
            }
           return result;
       }
        var sentence = "the quick brown fox jumped over the lazy dog.";
       document.write(longestWord(sentence));
</code>```

Body:
I keep getting an error when I input the following into Sublime:

function longestWord(str) {
  var result = str[0];
  str = str.split(' ');

  for (var i = 0; i < str.length; i++) {
    if (str[i].length > result.length) {
      result = str[i];
    }
  }
  return result;
}

var sentence = ["the quick brown fox jumped over the lazy dog."];

console.log(longestWord(sentence));

I get an Uncaught TypeError: str.split is not a function(...)

What am I doing wrong?  Thank you!


问:
C Prints One Char More Without Value
I am trying to print the ASCII values of 3 char-type characters. When I input the first char it doesn't print the value of the char. After the first char it starts to give the value.

```<code>#include <stdio.h>
int main()  {
    char ch;
    int t;
    while(t < 3){
        scanf("%c\n", &ch);
        printf("%c - %d\n", ch,ch);
        t++;
    }
}
</code>```

http://i54.tinypic.com/2mdqb7d.png

答:
I saw this several times, and don't know the root cause, but solution that works is:

scanf("\n%c", &ch);

It probably has something to do with buffered end of line character.

Title: C Prints One Char More Without Value

Body:
I am trying to print the ASCII values of 3 char-type characters. When I input the first char it doesn't print the value of the char. After the first char it starts to give the value.

#include <stdio.h>
int main()  {
    char ch;
    int t;
    while(t < 3){
        scanf("%c\n", &ch);
        printf("%c - %d\n", ch,ch);
        t++;
    }
}

http://i54.tinypic.com/2mdqb7d.png


问:
List of users and the app version in Amplitude tool
I need to find a list of all user using my iOS app and also the version they are on.

Currently, we are using amplitude for analytics.

Is there any ways I can get the list using amplitude.

If not can it be done using fastlane pilot?

答:
OK.  This you can definitely do in Amplitude.

Amplitude screenshot

This simple report will dump out a csv file containing a huge amount of data about your iOS users - including the app. version.

Hope this helps!


问:
Name casing convention across all languages in an Application
I'm build a web app using Javascript (on the browser), C# and Sql Server. Is it a good idea to have a consistent naming convention across all three languages?

For Javscript, it seems to be best practice is to use camelCase, but in C# and Sql Server it's TitleCase.

Problem though is when the Javascript consumes and sends data to C# / Sql server the naming conventions are inconsistent.  So I have to write code to map them.

For example

In Sql I have a table called 'Foo' with columns 'Name', 'EmailAddress'

In C# I have an POCO object called 'Foo' that maps to this table with
  properties 'Name', 'EmailAddress'  and exposes an api endpoint to GET this is
  json
  e.g {"Name": "Joe Bloggs", "EmailAddres":"joe@test.org"}

My Javascripts makes an ajax call to GET this JSON and maps it to its own
  JSON object e.g {"name": data.Name, "emailAddress": data.EmailAddress}

This mapping between column/property naming conventions seems silly to me, and wouldn't be needed if all languages just agreed on casing convention.  Is there a better approach to this?

答:
Add this to your application startup, and it should automatically convert the returned object of your GET to camelCase.

No need to futz with any mappings or stray from the conventions of each environment.

```<code>var formatters = GlobalConfiguration.Configuration.Formatters;
var jsonFormatter = formatters.JsonFormatter;
var settings = jsonFormatter.SerializerSettings;
settings.Formatting = Formatting.Indented;
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
</code>```

See here for more detail: http://odetocode.com/blogs/scott/archive/2013/03/25/asp-net-webapi-tip-3-camelcasing-json.aspx

Body:
Add this to your application startup, and it should automatically convert the returned object of your GET to camelCase.

No need to futz with any mappings or stray from the conventions of each environment.

var formatters = GlobalConfiguration.Configuration.Formatters;
var jsonFormatter = formatters.JsonFormatter;
var settings = jsonFormatter.SerializerSettings;
settings.Formatting = Formatting.Indented;
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();

See here for more detail: http://odetocode.com/blogs/scott/archive/2013/03/25/asp-net-webapi-tip-3-camelcasing-json.aspx


问:
Flask, Python and Socket.io: multithreading app is giving me "RuntimeError: working outside of request context"
I have been developing an app using Flask, Python and Flask-Socket.io library. The problem I have is that the following code will not perform an emit correctly due to some contexts issue

```<code>RuntimeError: working outside of request context
</code>```

I am writing only one python file for the entire program by now. This is my code (test.py):

```<code>from threading import Thread
from flask import Flask, render_template, session, request, jsonify, current_app, copy_current_request_context
from flask.ext.socketio import *

app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)

def somefunction():
    # some tasks
    someotherfunction()

def someotherfunction():
    # some other tasks
    emit('anEvent', jsondata, namespace='/test') # here occurs the error

@socketio.on('connect', namespace='/test')
def setupconnect():
    global someThread
    someThread = Thread(target=somefunction)
    someThread.daemon = True

if __name__ == '__main__':
    socketio.run(app)
</code>```

Here in StackExchange I have been reading some solutions, but they didn't work. I do not know what I am doing wrong.

I have tried adding a with app.app_context(): before my emit:

```<code>def someotherfunction():
    # some other tasks
    with app.app_context():
        emit('anEvent', jsondata, namespace='/test') # same error here
</code>```

Another solution I tried is adding the decorator copy_current_request_context before someotherfunction() but it says that the decorator must be in a local scope. I put it in inside someotherfunction(), first line, but same error.

I would be glad if someone can help me with this. Thanks in advance.

答:
You are using the wrong emit here. You have to use the emit of the socketio object you created. so instead of

emit('anEvent', jsondata, namespace='/test') # here occurs the error

use:

socketio.emit('anEvent', jsondata, namespace='/test') # here occurs the error

Body:
I have been developing an app using Flask, Python and Flask-Socket.io library. The problem I have is that the following code will not perform an emit correctly due to some contexts issue

RuntimeError: working outside of request context

I am writing only one python file for the entire program by now. This is my code (test.py):

from threading import Thread
from flask import Flask, render_template, session, request, jsonify, current_app, copy_current_request_context
from flask.ext.socketio import *

app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)

def somefunction():
    # some tasks
    someotherfunction()

def someotherfunction():
    # some other tasks
    emit('anEvent', jsondata, namespace='/test') # here occurs the error

@socketio.on('connect', namespace='/test')
def setupconnect():
    global someThread
    someThread = Thread(target=somefunction)
    someThread.daemon = True

if __name__ == '__main__':
    socketio.run(app)

Here in StackExchange I have been reading some solutions, but they didn't work. I do not know what I am doing wrong.

I have tried adding a with app.app_context(): before my emit:

def someotherfunction():
    # some other tasks
    with app.app_context():
        emit('anEvent', jsondata, namespace='/test') # same error here

Another solution I tried is adding the decorator copy_current_request_context before someotherfunction() but it says that the decorator must be in a local scope. I put it in inside someotherfunction(), first line, but same error.

I would be glad if someone can help me with this. Thanks in advance.


问:
How to track BigQuery usage by user/service account
I have a BigQuery account which is accessed by many internal and external users/service accounts. Recently, with the growth of bill, we started researching how to increase the visibility of how much cost is going to each user/service account.

I know there is a way to get this info somewhere through the BigQuery API but I was wondering if there is any other easy way to get this info. Has anybody had a similar problem?

Restating the question: how to track how much data each BigQuery user/service account has processed?

答:
Use BigQuery's audit logs (via Stackdriver) to track access and cost details as described in the docs.

A good tip is to export the logs back to BigQuery for analysis.

https://cloud.google.com/bigquery/audit-logs


问:
Magento - Checking if a module is installed?
I have a small piece of code in a template file that I ONLY want to run if a certain module is installed. I found the below code, which you can use to find if a module is active, but I want to know if a module is installed.

```<code>$modules = Mage::getConfig()->getNode('modules')->children();
$modulesArray = (array)$modules;

if($modulesArray['Mage_Paypal']->is('active')) {
    echo "Paypal module is active.";
} else {
    echo "Paypal module is not active.";
}
</code>```

I'm thinking I could maybe get a list of names of all the modules that are installed, and then use

```<code>if (stristr($modulelist, 'Name_Extension'))
</code>```

to show my code only if the referenced extension is installed.

Anyone any ideas how to do that? Or any better solutions?

答:
in the declaration of your module, try adding a depends element, like on this page.
This will probably raise an exception, which you could handle with a try/catch block.

Body:
I have a small piece of code in a template file that I ONLY want to run if a certain module is installed. I found the below code, which you can use to find if a module is active, but I want to know if a module is installed.

$modules = Mage::getConfig()->getNode('modules')->children();
$modulesArray = (array)$modules;

if($modulesArray['Mage_Paypal']->is('active')) {
    echo "Paypal module is active.";
} else {
    echo "Paypal module is not active.";
}

I'm thinking I could maybe get a list of names of all the modules that are installed, and then use

if (stristr($modulelist, 'Name_Extension'))

to show my code only if the referenced extension is installed.

Anyone any ideas how to do that? Or any better solutions?


问:
reverse printing on python 3.x function
```<code>import time
def close_garage_dors():
        a= '_ _ _'
        for i in range(5):
            time.sleep(1)
            print(a)

        return 'Doors are closed'
</code>```

Now my question is: How to open this doors :) Basically how to reverse this function, how to delete 5 lines of _ _ _ ? Any ideas?

答:
If you want to overwrite your console output you have to replace print function with:

```<code>print(a),
</code>```

That comma tell the interpreter to write on console stdout and don't print a new line, otherwise you can use sys.stdout.write:

```<code>import sys
sys.stdout.write(a)
sys.stdout.write('\r')
</code>```

Title: reverse printing on python 3.x function

Body:
import time
def close_garage_dors():
        a= '_ _ _'
        for i in range(5):
            time.sleep(1)
            print(a)

        return 'Doors are closed'

Now my question is: How to open this doors :) Basically how to reverse this function, how to delete 5 lines of _ _ _ ? Any ideas?

Body:
If you want to overwrite your console output you have to replace print function with:

print(a),

That comma tell the interpreter to write on console stdout and don't print a new line, otherwise you can use sys.stdout.write:

import sys
sys.stdout.write(a)
sys.stdout.write('\r')


问:
Groovy XmlSlurper: get value of attribute that has an associated namespace
I have an XML document that contains attributes with qualified names. I want to get the attribute value using XmlSlurper, but trying to access the attribute without specifying the namespace does not work (below is a minimal example).

def rootNode = new XmlSlurper().parseText(
'''<root xmlns:ex="http://example.com">
     <one ex:a1="uno!"/>
     <ex:two>Some text!</ex:two>
   </root>''' )

assert rootNode.one[0].@a1.text() == 'uno!'
```

rootNode.one[0].@a1.text() will yield an empty string. If using rootNode.one[0].'@ex:a1'.text() we get the correct value, but this is dependent on the namespace prefix used in the document - and that can't be relied upon to be the same for other documents, the associated namespace is what matters.

So the question is:
How can XmlSlurper be used to access an attribute value of an attribute that has an associated namespace without the need to specify the namespace prefix?
(it would be OK if supplying the whole namespace is needed)

答:
There is a simpler way:

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
     android:versionCode="500" android:versionName="5.0.0" package="com.my.package"
    android:installLocation="preferExternal" >
...
</manifest >
</code>```

parsing attr with namespace and without:

```<code>def parsedXml = (new XmlSlurper()).parse(android.sourceSets.main.manifest.srcFile)
def pkg_name = parsedXml.@package.text()
def pkg_ver = parsedXml.@'android:versionName'
</code>```

Body:
I have an XML document that contains attributes with qualified names. I want to get the attribute value using XmlSlurper, but trying to access the attribute without specifying the namespace does not work (below is a minimal example).

def rootNode = new XmlSlurper().parseText(
'''<root xmlns:ex="http://example.com">
     <one ex:a1="uno!"/>
     <ex:two>Some text!</ex:two>
   </root>''' )

assert rootNode.one[0].@a1.text() == 'uno!'

rootNode.one[0].@a1.text() will yield an empty string. If using rootNode.one[0].'@ex:a1'.text() we get the correct value, but this is dependent on the namespace prefix used in the document - and that can't be relied upon to be the same for other documents, the associated namespace is what matters.

So the question is:
How can XmlSlurper be used to access an attribute value of an attribute that has an associated namespace without the need to specify the namespace prefix?
(it would be OK if supplying the whole namespace is needed)

Body:
There is a simpler way:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
     android:versionCode="500" android:versionName="5.0.0" package="com.my.package"
    android:installLocation="preferExternal" >
...
</manifest >

parsing attr with namespace and without:

def parsedXml = (new XmlSlurper()).parse(android.sourceSets.main.manifest.srcFile)
def pkg_name = parsedXml.@package.text()
def pkg_ver = parsedXml.@'android:versionName'


问:
Should I catch all my exceptions in the global.asax?
If I am just logging exception details in my web app, do I really need to put in exception handling logic for each tier? Why not just let them all bubble up the stack trace to the global.asax and log them there?</p>

答:
Usually what I do is do a try...catch in the code, but instead of logging on the catch what I do is pass it on with a message stating where the error came from, etc.  Then I use Elmah to catch all of the errors and log them.  </p>

<p>That way you only have to deal with the logging in one area and satisfy the Single Responsiblity Principle, but you have more information available for debugging purposes.  It can also be helpful when you get that data error that only seems to occur with 1 out of 500 users.  </p>

Body:
Usually what I do is do a try...catch in the code, but instead of logging on the catch what I do is pass it on with a message stating where the error came from, etc.  Then I use Elmah to catch all of the errors and log them.

That way you only have to deal with the logging in one area and satisfy the Single Responsiblity Principle, but you have more information available for debugging purposes.  It can also be helpful when you get that data error that only seems to occur with 1 out of 500 users.


问:
ReactNative - Get data from API into List View
First attempt at pulling data from an API into react native, I think im pretty close but I am getting "Cannot read property 'DataSource' of undefined".

https://gist.github.com/ElliotReeve/a15ef765dab8267fd952b6483c0b4a32

Not sure what I am doing wrong?

答:
This is just a guess... but I think you're mixing up RN ListView with native-base. You're setting it up like RN's ListView but then using NB. I don't think you need to set a DataSource if you're using NB and just pass a normal array into ListView as dataArray and they will handle all that for you.

```<code>this.state = {
  appointments: []
}
...
<ListView dataArray={this.state.appointments}>
</code>```

Body:
This is just a guess... but I think you're mixing up RN ListView with native-base. You're setting it up like RN's ListView but then using NB. I don't think you need to set a DataSource if you're using NB and just pass a normal array into ListView as dataArray and they will handle all that for you.

this.state = {
  appointments: []
}
...
<ListView dataArray={this.state.appointments}>