问:
inserting data from parent table to child table in postgres
I want to insert a data from parent table to child table if it isn't already in the child table.</p>

```<code>create table parents(
 c1 varchar  (100) primary key,
  c2 varchar  (100),

);
CREATE TABLE child
(
   c1 varchar (100) PRIMARY KEY,
    c3 varchar (100),

     FOREIGN KEY (c1) REFERENCES parents(c1)
);
</code>```

答:
Assuming, by data, you mean column c1 only, you can insert into child using a select from parent where you can filter the row to those which aren't present in the child table.</p>

```<code>insert into child (c1, c3)
select c1, c2
from parents
where c1 not in (
    select c1 from child
    );
</code>```

Body:
I want to insert a data from parent table to child table if it isn't already in the child table.

create table parents(
 c1 varchar  (100) primary key,
  c2 varchar  (100),

);
CREATE TABLE child
(
   c1 varchar (100) PRIMARY KEY,
    c3 varchar (100),

     FOREIGN KEY (c1) REFERENCES parents(c1)
);

Body:
Assuming, by data, you mean column c1 only, you can insert into child using a select from parent where you can filter the row to those which aren't present in the child table.

insert into child (c1, c3)
select c1, c2
from parents
where c1 not in (
    select c1 from child
    );


来源: stackexchange

问:
Obtaining mean of certain columns with specific names
I'm trying to find the mean of values in certain columns, and append that into a new column.

I have a variable containing a list of character elements, and these elements correspond to certain column names. For example,

```<code>qcs <- list.files(qcDirectory)
str(qcs)
chr [1:5] "201701" "201702" "201703" "201704"
</code>```

Here's an example data table:

```<code>        201701  201702  201703  201704
row1    12      20      50      54
row2    15      23      45      35
row3    16      20      52      58
row4    17      13      47      48
</code>```

For example, I'd like to get the average of the values contained in the columns named "201701" and "201702", so the expected output would be:

```<code>        201701  201702  201703  201704  mean
row1    12      20      50      54      16
row2    15      23      45      35      19
row3    16      20      52      58      18
row4    17      13      47      48      15
</code>```

I can't just apply it to the first x number of columns, because they could appear anywhere in the table. I'm thinking lapply might be the way to go, but I'm not sure how I would get this to work. In plain English, I basically want the function to be, "for all column names that are contained in this variable [qcs], find the mean of those values." Not sure whether I need some sort of a loop, or what. I'm sure the answer is already out there, but I'm a noob and having trouble trying to apply similar posts like this and this. I'm thinking something vaguely like what I have below, which can successfully identify the right columns to operate on, but that's just averaging the values in each column and outputting a list, rather than averaging the values across the rows of the relevant columns and putting them into a new column. Any ideas are appreciated.

```<code>sapply(colnames(datamatrix), function(c) {
  if (c %in% qcs) datamatrix$mean = mean(test1[, c])
})
</code>```

答:
This is what you can do. Store the columns of interest in a vector col as below. Then use apply.

col=c('201701','201702')
df$mean=apply(df[,col],1,mean)

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to find the mean of values in certain columns, and append that into a new column.

I have a variable containing a list of character elements, and these elements correspond to certain column names. For example,

qcs <- list.files(qcDirectory)
str(qcs)
chr [1:5] "201701" "201702" "201703" "201704"

Here's an example data table:

        201701  201702  201703  201704
row1    12      20      50      54
row2    15      23      45      35
row3    16      20      52      58
row4    17      13      47      48

For example, I'd like to get the average of the values contained in the columns named "201701" and "201702", so the expected output would be:

        201701  201702  201703  201704  mean
row1    12      20      50      54      16
row2    15      23      45      35      19
row3    16      20      52      58      18
row4    17      13      47      48      15

I can't just apply it to the first x number of columns, because they could appear anywhere in the table. I'm thinking lapply might be the way to go, but I'm not sure how I would get this to work. In plain English, I basically want the function to be, "for all column names that are contained in this variable [qcs], find the mean of those values." Not sure whether I need some sort of a loop, or what. I'm sure the answer is already out there, but I'm a noob and having trouble trying to apply similar posts like this and this. I'm thinking something vaguely like what I have below, which can successfully identify the right columns to operate on, but that's just averaging the values in each column and outputting a list, rather than averaging the values across the rows of the relevant columns and putting them into a new column. Any ideas are appreciated.

sapply(colnames(datamatrix), function(c) {
  if (c %in% qcs) datamatrix$mean = mean(test1[, c])
})


问:
How can I construct an enum.Enum from a dictionary of values?
I'd like to generate some types at runtime from a config file. For simplity, let's assume I already have the data loaded as a python dictionary:

```<code>color_values = dict(RED = 1, YELLOW = 2, GREEN = 3)
</code>```

How can I transform this into the type (using enum)

```<code>class Color(enum.Enum):
    RED = 1
    YELLOW = 2
    GREEN = 3
</code>```

The following doesn't work

```<code>def make_enum(name, values):
    return type(name, (enum.Enum,), values)
</code>```

```<code>>>> Color = make_enum('Color', color_values)
AttributeError: 'dict' object has no attribute '_member_names'
</code>```

答:
Here's one super-hacky approach that seems to work:

```<code>def make_enum(name, values):
    _k = _v = None
    class TheEnum(enum.Enum):
        nonlocal _k, _v
        for _k, _v in values.items():
            locals()[_k] = _v
    TheEnum.__name__ = name
    return TheEnum
</code>```

We have to use nonlocal there to stop Enum complaining about the keys k and v being duplicated.

Body:
I'd like to generate some types at runtime from a config file. For simplity, let's assume I already have the data loaded as a python dictionary:

color_values = dict(RED = 1, YELLOW = 2, GREEN = 3)

How can I transform this into the type (using enum)

class Color(enum.Enum):
    RED = 1
    YELLOW = 2
    GREEN = 3

The following doesn't work

def make_enum(name, values):
    return type(name, (enum.Enum,), values)

>>> Color = make_enum('Color', color_values)
AttributeError: 'dict' object has no attribute '_member_names'

Body:
Here's one super-hacky approach that seems to work:

def make_enum(name, values):
    _k = _v = None
    class TheEnum(enum.Enum):
        nonlocal _k, _v
        for _k, _v in values.items():
            locals()[_k] = _v
    TheEnum.__name__ = name
    return TheEnum

We have to use nonlocal there to stop Enum complaining about the keys k and v being duplicated.


问:
Errors after updating to Android 3.0 and SDK 27
After Android Studio was released to 3.0 I was forced to update my SDK from 25 to 27 (couple libraries problems).

But now when try to build my app I get next error messages:

```<code>>Information:Gradle tasks [:app:generateDebugSources, :app:generateDebugAndroidTestSources, :app:mockableAndroidJar]
C:\Users\Alice\.gradle\caches\transforms-1\files-1.1\appcompat-v7-27.0.0.aar\63ec32742d97434c1d2e0dbe96345ab9\res\values\values.xml
Error:(252, 5) error: resource android:attr/foregroundInsidePadding is private.
C:\Users\Alice\AndroidStudioProjects\Ghiduldrumetului cu Loco\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml
Error:(941) resource android:attr/foregroundInsidePadding is private.
Error:failed linking references.
Error:java.util.concurrent.ExecutionException: java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:Execution failed for task ':app:processDebugResources'.
> Failed to execute aapt
Information:BUILD FAILED in 16s
Information:7 errors
Information:0 warnings
Information:See complete output in console
</code>```

Any suggestion how to fix it?

答:
Try disabling the AAPT2 by adding android.enableAapt2=false to your gradle.properties file.

Builds may fail while AAPT2 is enabled. Additionally, AAPT2 is currently not compatible with Robelectric. If your build fails due to an AAPT2 resource processing issue or you want to use Roboelectric, you can disable AAPT2 by setting android.enableAapt2=false in your gradle.properties file and restarting the Gradle daemon by running ./gradlew --stop from the command line.

Reference :
https://developer.android.com/studio/build/gradle-plugin-3-0-0.html

Body:
After Android Studio was released to 3.0 I was forced to update my SDK from 25 to 27 (couple libraries problems).

But now when try to build my app I get next error messages:

>Information:Gradle tasks [:app:generateDebugSources, :app:generateDebugAndroidTestSources, :app:mockableAndroidJar]
C:\Users\Alice\.gradle\caches\transforms-1\files-1.1\appcompat-v7-27.0.0.aar\63ec32742d97434c1d2e0dbe96345ab9\res\values\values.xml
Error:(252, 5) error: resource android:attr/foregroundInsidePadding is private.
C:\Users\Alice\AndroidStudioProjects\Ghiduldrumetului cu Loco\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml
Error:(941) resource android:attr/foregroundInsidePadding is private.
Error:failed linking references.
Error:java.util.concurrent.ExecutionException: java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:Execution failed for task ':app:processDebugResources'.
> Failed to execute aapt
Information:BUILD FAILED in 16s
Information:7 errors
Information:0 warnings
Information:See complete output in console

Any suggestion how to fix it?


问:
NSDate - one year ago, dilemma
I'm trying to do something that, for me, is a bit difficult. But I'm sure someone has some insight.

Given a date, say January 17, 2011, I'm trying to figure out the day that corresponds to this date one year ago. So January 17, 2011 is a Monday, and one year ago, this day fell on January 18, 2010 (a Monday as well). It turns out that January 18, 2010 is 354 days before January 17, 2011. I originally thought to just simply subtract 365 days for a non-leap year and 366 days for a leap year, but if you do that in this case, you would get January 17, 2010, which is a Sunday, not a Monday.

So, in Objective-C with NSDate and NSCalendar, how could I implement a function such as:

```<code>-(NSDate *)logicalOneYearAgo:(NSDate *)from {
}
</code>```

In other words, the nth "weekday" of the nth month (where "weekday" is Monday or Tuesday or Wednesday etc)

答:
I can't guarantee this is the most efficient way, but you could do it using NSCalendar and NSDateComponents. Pass your NSDate instance into [yourCalendar components:yourComponents fromDate:yourDate], subtract a year from the components, and then use [yourCalendar dateFromComponents:yourComp].

Sorry for not providing full code, but it's been a while since I've worked with those methods, and I don't want to give you code that won't work.

Title: NSDate - one year ago, dilemma

Body:
I'm trying to do something that, for me, is a bit difficult. But I'm sure someone has some insight.

Given a date, say January 17, 2011, I'm trying to figure out the day that corresponds to this date one year ago. So January 17, 2011 is a Monday, and one year ago, this day fell on January 18, 2010 (a Monday as well). It turns out that January 18, 2010 is 354 days before January 17, 2011. I originally thought to just simply subtract 365 days for a non-leap year and 366 days for a leap year, but if you do that in this case, you would get January 17, 2010, which is a Sunday, not a Monday.

So, in Objective-C with NSDate and NSCalendar, how could I implement a function such as:

-(NSDate *)logicalOneYearAgo:(NSDate *)from {
}

In other words, the nth "weekday" of the nth month (where "weekday" is Monday or Tuesday or Wednesday etc)

ContentLicense: CC BY-SA 2.5


问:
Android - SortedList.indexOf() returns INVALID_POSITION
I have come across a very strange behavior of SortedList. The method indexOf returns INVALID_POSITION even though in the debugger everything seems okay.

Method getWorkingDayItems of adapter workingDayAdapter returns SortedList.

As you can see, the 3rd element of the list is WorkingDay@4678 which is the same object as object workingDay. Yet the method indexOf returns -1.

Could you explain to me, why is this happening? Is there a known or not yet discovered but in the SortedList? Or is there another cause?

Thank you.

EDIT:

After removing overriding of equals method the problem persist.

答:
In my case it's because I modified attribute localStatus of my object after adding items to the list, which is also being used in compare method,
and SortedList uses binary search base on the output of compare method.

Here is my compare method

```<code>@Override
public int compare(SmsWrapper o1, SmsWrapper o2) {
    return o1.localStatus.ordinal() - o2.localStatus.ordinal();
}
</code>```

Hope it help.

Body:
In my case it's because I modified attribute localStatus of my object after adding items to the list, which is also being used in compare method,
and SortedList uses binary search base on the output of compare method.

Here is my compare method

@Override
public int compare(SmsWrapper o1, SmsWrapper o2) {
    return o1.localStatus.ordinal() - o2.localStatus.ordinal();
}

Hope it help.


问:
Get Primary Key Column from ResultSet Java
I am trying to get Primary Key Column(s) of table from ResultSet. Following are the Steps

I followed:

```<code>1. SQL QUERY: Select id,subid,email,empname from Employee
2. Executed this from java.sql.Statement and got the Results in ResultSet.
</code>```

Here is the Interesting Part.

```<code>3. ResultSetMetadata rsmd = rs.getMetadata();
</code>```

Now, if i watch this variable "rsmd" , it is showing primary key flags for relevant column names but I am not able to access it or get it into any variable.

I need help regarding the same.

NOTE: I do not want to use DatabaseMetadata and its getPrimaryKeys() function as it will take an additonal hit into External Database. Also, the ResultSetMetadata object is already having the primary key Information which i just need to fetch.

答:
with @Keerthivasan Approach here is the complete working code. only problem was that answer cannot use the method like that as it is protected method.
here is the working code.

```<code>ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
int count = resultSetMetaData.getColumnCount();
for (int x = 1; x <= count; x++) {

    Method method = null;
    try {
        method = com.mysql.jdbc.ResultSetMetaData.class.getDeclaredMethod("getField", int.class);
        method.setAccessible(true);
        com.mysql.jdbc.Field field = (com.mysql.jdbc.Field) method.invoke(resultSetMetaData, x);

        if (field.isPrimaryKey()) {
            System.out.println("-----------PK---------------------");
        } else {
            System.out.println("+++++++++++++++NPK++++++++++++++++++");
        }
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }

}
</code>```

Body:
I am trying to get Primary Key Column(s) of table from ResultSet. Following are the Steps

I followed:

1. SQL QUERY: Select id,subid,email,empname from Employee
2. Executed this from java.sql.Statement and got the Results in ResultSet.

Here is the Interesting Part.

3. ResultSetMetadata rsmd = rs.getMetadata();

Now, if i watch this variable "rsmd" , it is showing primary key flags for relevant column names but I am not able to access it or get it into any variable.

I need help regarding the same.

NOTE: I do not want to use DatabaseMetadata and its getPrimaryKeys() function as it will take an additonal hit into External Database. Also, the ResultSetMetadata object is already having the primary key Information which i just need to fetch.

Body:
with @Keerthivasan Approach here is the complete working code. only problem was that answer cannot use the method like that as it is protected method.
here is the working code.

ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
int count = resultSetMetaData.getColumnCount();
for (int x = 1; x <= count; x++) {

    Method method = null;
    try {
        method = com.mysql.jdbc.ResultSetMetaData.class.getDeclaredMethod("getField", int.class);
        method.setAccessible(true);
        com.mysql.jdbc.Field field = (com.mysql.jdbc.Field) method.invoke(resultSetMetaData, x);

        if (field.isPrimaryKey()) {
            System.out.println("-----------PK---------------------");
        } else {
            System.out.println("+++++++++++++++NPK++++++++++++++++++");
        }
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }

}


问:
vb.net default date.now formatting vs c# default.Now formatting
I came from me last post

c# change date type format to ddmmyyyy

I have to work in a VB.Net WinForm Application I have a problem with Date or DateTime type.

I usually work with C#, but now I have this problem, I am sure is a common problem that others programmers came acrross.

I have defined in control panel my datetime format like "dd/MM/yyyy". Also y check in Regedit as it says in here

If, In my WinForm, I define a variable like this i C#

DateTime aa = DateTime.Now

DateTime.Now retrieves current date in format "dd/MM/YYYY" as spected.

But if I ask the same to VB.Net like this

```<code>Dim val As New Date
 val = Date.Now
</code>```

val has the current date in format "MM/dd/yyyy"

Even if i set

val = Date.Now.ToString("dd/MM/yyyy")

val keeps format as "MM/dd/yyyy"

Every date I assign to a variable Datetime, it automatically convert format "dd/MM/yyyy" to "MM/dd/yyyy".

How can i configurate VB.Net to accept Datetime type as C# Does? I need it to take it from Control Panel.

答:
There is no actual issue here but the perceived difference is due to the fact that VB supports Date literals where C# does not.  Both C# and VB support literals for numeric types, strings, Booleans, etc.

```<code>var str = "Hello World";
var num = 100;
var flag = true;
</code>```

```<code>Dim str = "Hello World"
Dim num = 100
Dim flag = true
</code>```

Only VB supports literals for dates though.  For instance, in C#, you would have to do something like this for a hard-coded date:

```<code>var dt = new DateTime(1969, 6, 19);
</code>```

You can do basically the same thing in VB:

```<code>Dim dt As New DateTime(1969, 6, 19)
</code>```

but you can also do this:

```<code>Dim dt = #6/19/1969#
</code>```

When you use a date literal in VB, you ALWAYS use M/dd/yyyy format.  It simply couldn't make use of system settings because that would mean that the same code would behave differently on different machines.

Now, when you run a project in the debugger and use the Watch window or the like to view the value of a variable or other expression, the debugger will display a literal value if the type supports it.  If the type doesn't support literals, you will see the result of calling ToString on the object.  That means that the debugger will always show you something in M/dd/yyy format for a DateTime value in a VB project because it's showing you a literal Date, while what it shows you in a C# project depends on your system settings because it's the result of calling ToString on a DateTime.

This is not an issue at all though.  The actual value of the DateTime variables doesn't change.  They don't actually contain a format at all.  They're just numbers in the system.  Format is only an issue when you want to represent the value as text.  When you need to do that, you'll call ToString on your value and that will honour the system settings, whether in VB or C#.

Note that I have used the terms Date and DateTime in this answer.  DateTime is a .NET type while Date is an intrinsic VB data type.  Both languages support literals for their intrinsic data types but only VB has an intrinsic data type for dates, which is why only VB supports literal dates.  Just as int in C# and Integer in VB are aliases for the Int32 type, so Date in VB is an alias for the DateTime type, but there is no equivalent in C#.

Body:
I came from me last post

c# change date type format to ddmmyyyy

I have to work in a VB.Net WinForm Application I have a problem with Date or DateTime type.

I usually work with C#, but now I have this problem, I am sure is a common problem that others programmers came acrross.

I have defined in control panel my datetime format like "dd/MM/yyyy". Also y check in Regedit as it says in here

If, In my WinForm, I define a variable like this i C#

DateTime aa = DateTime.Now

DateTime.Now retrieves current date in format "dd/MM/YYYY" as spected.

But if I ask the same to VB.Net like this

Dim val As New Date
 val = Date.Now

val has the current date in format "MM/dd/yyyy"

Even if i set

val = Date.Now.ToString("dd/MM/yyyy")

val keeps format as "MM/dd/yyyy"

Every date I assign to a variable Datetime, it automatically convert format "dd/MM/yyyy" to "MM/dd/yyyy".

How can i configurate VB.Net to accept Datetime type as C# Does? I need it to take it from Control Panel.

Body:
There is no actual issue here but the perceived difference is due to the fact that VB supports Date literals where C# does not.  Both C# and VB support literals for numeric types, strings, Booleans, etc.

var str = "Hello World";
var num = 100;
var flag = true;

Dim str = "Hello World"
Dim num = 100
Dim flag = true

Only VB supports literals for dates though.  For instance, in C#, you would have to do something like this for a hard-coded date:

var dt = new DateTime(1969, 6, 19);

You can do basically the same thing in VB:

Dim dt As New DateTime(1969, 6, 19)

but you can also do this:

Dim dt = #6/19/1969#

When you use a date literal in VB, you ALWAYS use M/dd/yyyy format.  It simply couldn't make use of system settings because that would mean that the same code would behave differently on different machines.

Now, when you run a project in the debugger and use the Watch window or the like to view the value of a variable or other expression, the debugger will display a literal value if the type supports it.  If the type doesn't support literals, you will see the result of calling ToString on the object.  That means that the debugger will always show you something in M/dd/yyy format for a DateTime value in a VB project because it's showing you a literal Date, while what it shows you in a C# project depends on your system settings because it's the result of calling ToString on a DateTime.

This is not an issue at all though.  The actual value of the DateTime variables doesn't change.  They don't actually contain a format at all.  They're just numbers in the system.  Format is only an issue when you want to represent the value as text.  When you need to do that, you'll call ToString on your value and that will honour the system settings, whether in VB or C#.

Note that I have used the terms Date and DateTime in this answer.  DateTime is a .NET type while Date is an intrinsic VB data type.  Both languages support literals for their intrinsic data types but only VB has an intrinsic data type for dates, which is why only VB supports literal dates.  Just as int in C# and Integer in VB are aliases for the Int32 type, so Date in VB is an alias for the DateTime type, but there is no equivalent in C#.


问:
reading smalltalk code from gst prompt
This is simple GNU Smalltalk question. Sorry, but just could not find how to do this.

I'm playing with gnu smalltalk, I know I can do

```<code>% gst <file-name>
</code>```

but if I already in gst> prompt, how can I read a file into memory (file that contains code), something like TCL source command.

thanks and applogies again for the simple question.

答: Use a package?</p>

Title: reading smalltalk code from gst prompt

Body:
This is simple GNU Smalltalk question. Sorry, but just could not find how to do this.

I'm playing with gnu smalltalk, I know I can do

% gst <file-name>

but if I already in gst> prompt, how can I read a file into memory (file that contains code), something like TCL source command.

thanks and applogies again for the simple question.

Body: Use a package?


问:
NaN as a result of using tapply, when calculating means
Checked a lot of, there are similar questions, but cannot understand one simple thing. I am trying to calculate mean salaries for different baseball positions.

```<code>library(Lahman)
library(tidyverse)

data("Fielding")
data(Salaries)

# First, I need to merge two datasets
merged.df <- merge(Fielding, Salaries, by = "playerID", na.rm = TRUE)
merged.df.2002 <- merged.df[merged.df$yearID.x == "2002",]

# Let's try tapply
mean.salary <- tapply(merged.df.2002$POS, merged.df.2002$salary, mean, na.rm = TRUE)
# So it gives me an error
# In mean.default(X[[i]], ...) :
#  argument is not numeric or logical: returning NA

class(merged.df.2002$POS)
class(merged.df.2002$salary)

# Very likely POS column is factor for some reason.
# Coerce them through
merged.df.2002$POS <- as.numeric(as.character(merged.df.2002$POS))
# Warning message:
# NAs introduced by coercion
merged.df.2002$salary <- as.numeric(as.character(merged.df.2002$salary))
#as.numeric(merged.df.2002$salary)
class(merged.df.2002$salary)

# Let's try tapply again
mean.salary <- tapply(merged.df.2002$POS, merged.df.2002$salary, mean, na.rm
= TRUE)
mean.salary

60000   62500   63500   65000   67000   67500   68000   68750   70000
71000   72500   77500   78000   80000   82000   82500
NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN
NaN     NaN     NaN     NaN     NaN     NaN
</code>```

Any ideas? Many thanks!

答:
Well, it was easy, but I screwed up</p>

```<code>merged.df <- merge(Fielding, Salaries)
# So, my mistake was that I merged only by playerid.

merged.df.2002 <- merged.df[merged.df$yearID == 2002, ]
# we pick 2002 year from the merged dataset

# use tapply for mean
merged.df.mean <- tapply(merged.df.2002$salary, merged.df.2002$POS, mean,
na.rm = TRUE)

#      1B      2B      3B       C      OF       P      SS
# 2543845 1400543 1547836 1787933 2659230 2150887 1979732
</code>```

Body:
Checked a lot of, there are similar questions, but cannot understand one simple thing. I am trying to calculate mean salaries for different baseball positions.

library(Lahman)
library(tidyverse)

data("Fielding")
data(Salaries)

# First, I need to merge two datasets
merged.df <- merge(Fielding, Salaries, by = "playerID", na.rm = TRUE)
merged.df.2002 <- merged.df[merged.df$yearID.x == "2002",]

# Let's try tapply
mean.salary <- tapply(merged.df.2002$POS, merged.df.2002$salary, mean, na.rm = TRUE)
# So it gives me an error
# In mean.default(X[[i]], ...) :
#  argument is not numeric or logical: returning NA

class(merged.df.2002$POS)
class(merged.df.2002$salary)

# Very likely POS column is factor for some reason.
# Coerce them through
merged.df.2002$POS <- as.numeric(as.character(merged.df.2002$POS))
# Warning message:
# NAs introduced by coercion
merged.df.2002$salary <- as.numeric(as.character(merged.df.2002$salary))
#as.numeric(merged.df.2002$salary)
class(merged.df.2002$salary)

# Let's try tapply again
mean.salary <- tapply(merged.df.2002$POS, merged.df.2002$salary, mean, na.rm
= TRUE)
mean.salary

60000   62500   63500   65000   67000   67500   68000   68750   70000
71000   72500   77500   78000   80000   82000   82500
NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN
NaN     NaN     NaN     NaN     NaN     NaN

Any ideas? Many thanks!

Body:
Well, it was easy, but I screwed up

merged.df <- merge(Fielding, Salaries)
# So, my mistake was that I merged only by playerid.

merged.df.2002 <- merged.df[merged.df$yearID == 2002, ]
# we pick 2002 year from the merged dataset

# use tapply for mean
merged.df.mean <- tapply(merged.df.2002$salary, merged.df.2002$POS, mean,
na.rm = TRUE)

#      1B      2B      3B       C      OF       P      SS
# 2543845 1400543 1547836 1787933 2659230 2150887 1979732


问:
get List of values exist more than once in array
I have to get a list of values that exist more than once in an array.
This is current code , but as you can see it's too complicated.

var arr = [1, 2, 3, 4, 2, 3];
var flag = {}
var exist2arr = [];

for(var i = 0; i < arr.length; i++){
  for(var j = 0 ; j < arr.length; j ++){
     if(i !=j && arr[i] == arr[j]){
       if(!flag[arr[i]])
         exist2arr.push(arr[i]);
       flag[arr[i]] = 1;
     }
  }
}
console.log(exist2arr);```

Is there any other way (simple code using javascript built-in function) to achieve this?  Any kind of help appreciate.

答:
A bit hacky, but short and O(n):

var arr = [1, 2, 3, 4, 2, 3, 2, 2]

var a = arr.reduce((r, v) => ((r[v + .1] = r[v + .1] + 1 || 1) - 2 || r.push(v), r), [])

console.log( a )              // [2,3]
console.log({ ...a })         // to show the "hidden" items
console.log({ ...a.slice() }) // .slice() can be used to remove the extra items```

Body:
I have to get a list of values that exist more than once in an array.
This is current code , but as you can see it's too complicated.

var arr = [1, 2, 3, 4, 2, 3];
var flag = {}
var exist2arr = [];

for(var i = 0; i < arr.length; i++){
  for(var j = 0 ; j < arr.length; j ++){
     if(i !=j && arr[i] == arr[j]){
       if(!flag[arr[i]])
         exist2arr.push(arr[i]);
       flag[arr[i]] = 1;
     }
  }
}
console.log(exist2arr);

Is there any other way (simple code using javascript built-in function) to achieve this?  Any kind of help appreciate.


问:
Python code to get a folder structure along with size
Hi I have two blocks of code as below -

```<code>def GetHumanReadable(size,precision=2):
    suffixes=['B','KB','MB','GB','TB']
    suffixIndex = 0
    while size > 1024:
        suffixIndex += 1 #increment the index of the suffix
        size = size/1024.0 #apply the division
    return "%.*f %d"%(precision,size,suffixes[suffixIndex])

import os
def list_files(startpath):
    for root, dirs, files in os.walk(startpath):
        level = root.replace(startpath, '').count(os.sep)
        indent = ' ' * 4 * (level)
        print('{}{}/'.format(indent, os.path.basename(root)))
        subindent = ' ' * 4 * (level + 1)
        for f in sorted(files, key=lambda f: os.path.getsize(root + os.sep + f)):
            converted_size = GetHumanReadable(os.path.getsize(root + os.sep + f))
            print('{}{} - {}B'.format(subindent, f, converted_size))
</code>```

I get the following error when I execute the following -

```<code>list_files(r'C:\Users\Downloads')
</code>```

Error - TypeError: %d format: a number is required, not str

Need a good solution for this. I am mainly looking to get folder/sub-folder along with sizes. The above code currently give size for each file. Modification requested to give size for the folder/subfolders itself. In the end need to write the output in a csv file. Thanks

PS: I dont own any of the above code. All code has been taken from stackoverflow and other similar platforms and then combined.

答:
All you need to do is change %d to %s and remove the B from the end of the print statement in list_files:

```<code>In [227]: def GetHumanReadable(size,precision=2):
     ...:     suffixes=['B','KB','MB','GB','TB']
     ...:     suffixIndex = 0
     ...:     while size > 1024:
     ...:         suffixIndex += 1 #increment the index of the suffix
     ...:         size = size/1024.0 #apply the division
     ...:     return "%.*f %s"%(precision,size,suffixes[suffixIndex])
     ...:
     ...: import os
     ...: def list_files(startpath):
     ...:     for root, dirs, files in os.walk(startpath):
     ...:         level = root.replace(startpath, '').count(os.sep)
     ...:         indent = ' ' * 4 * (level)
     ...:         print('{}{}/'.format(indent, os.path.basename(root)))
     ...:         subindent = ' ' * 4 * (level + 1)
     ...:         for f in sorted(files, key=lambda f: os.path.getsize(root + os.sep + f)):
     ...:             converted_size = GetHumanReadable(os.path.getsize(root + os.sep + f))
     ...:             print('{}{} - {}'.format(subindent, f, converted_size))
     ...: list_files(r'E:\Downloads\test')
test/
    file2.py - 40.00 B
    chap4exercise3.py - 57.00 B
    file1.py - 60.00 B
    run.py - 95.00 B
    largerfile.pdf - 767.08 KB
    __pycache__/
        file1.cpython-36.pyc - 239.00 B
        chap4exercise3.cpython-36.pyc - 253.00 B
</code>```

Body:
Hi I have two blocks of code as below -

def GetHumanReadable(size,precision=2):
    suffixes=['B','KB','MB','GB','TB']
    suffixIndex = 0
    while size > 1024:
        suffixIndex += 1 #increment the index of the suffix
        size = size/1024.0 #apply the division
    return "%.*f %d"%(precision,size,suffixes[suffixIndex])

import os
def list_files(startpath):
    for root, dirs, files in os.walk(startpath):
        level = root.replace(startpath, '').count(os.sep)
        indent = ' ' * 4 * (level)
        print('{}{}/'.format(indent, os.path.basename(root)))
        subindent = ' ' * 4 * (level + 1)
        for f in sorted(files, key=lambda f: os.path.getsize(root + os.sep + f)):
            converted_size = GetHumanReadable(os.path.getsize(root + os.sep + f))
            print('{}{} - {}B'.format(subindent, f, converted_size))

I get the following error when I execute the following -

list_files(r'C:\Users\Downloads')

Error - TypeError: %d format: a number is required, not str

Need a good solution for this. I am mainly looking to get folder/sub-folder along with sizes. The above code currently give size for each file. Modification requested to give size for the folder/subfolders itself. In the end need to write the output in a csv file. Thanks

PS: I dont own any of the above code. All code has been taken from stackoverflow and other similar platforms and then combined.

Body:
All you need to do is change %d to %s and remove the B from the end of the print statement in list_files:

In [227]: def GetHumanReadable(size,precision=2):
     ...:     suffixes=['B','KB','MB','GB','TB']
     ...:     suffixIndex = 0
     ...:     while size > 1024:
     ...:         suffixIndex += 1 #increment the index of the suffix
     ...:         size = size/1024.0 #apply the division
     ...:     return "%.*f %s"%(precision,size,suffixes[suffixIndex])
     ...:
     ...: import os
     ...: def list_files(startpath):
     ...:     for root, dirs, files in os.walk(startpath):
     ...:         level = root.replace(startpath, '').count(os.sep)
     ...:         indent = ' ' * 4 * (level)
     ...:         print('{}{}/'.format(indent, os.path.basename(root)))
     ...:         subindent = ' ' * 4 * (level + 1)
     ...:         for f in sorted(files, key=lambda f: os.path.getsize(root + os.sep + f)):
     ...:             converted_size = GetHumanReadable(os.path.getsize(root + os.sep + f))
     ...:             print('{}{} - {}'.format(subindent, f, converted_size))
     ...: list_files(r'E:\Downloads\test')
test/
    file2.py - 40.00 B
    chap4exercise3.py - 57.00 B
    file1.py - 60.00 B
    run.py - 95.00 B
    largerfile.pdf - 767.08 KB
    __pycache__/
        file1.cpython-36.pyc - 239.00 B
        chap4exercise3.cpython-36.pyc - 253.00 B


问:
HAProxy reqrep with text after last backreference
I am trying to redirect links that point at an old application to a new one. The new application can't handle direct links, so I want to point them to a search, but this search needs to be quoted to work properly. I have tried the following configuration but get 400 Bad Request if I do:

```<code>reqrep ^([^\ :]*)\ /\?pdf=(.*)  \1\ /newpdf?search=%22\2%22
</code>```

The closest I have come is to remove everything after the last backreference, like this:

```<code>reqrep ^([^\ :]*)\ /\?pdf=(.*)  \1\ /newpdf?search=%22\2
</code>```

Is it not possible to put anything after the last backreference?

答:
The problem isn't text after the backreference.  You are overlooking the nature of the string you are manipating:

```<code>GET /page?pdf=foo HTTP/1.1 <<< here
</code>```

After the URI there is a space and the HTTP version.  You're capturing that inside \2.  Separate it into \3, capturing a space and one or more non-space characters, anchored to the end.

```<code>reqrep ^([^\ :]*)\ /\?pdf=(.*)(\ [^\ ]+)$  \1\ /newpdf?search=%22\2%22\3
</code>```

A better solution would be to use fetches and the http-request request modification capabilities to manipulate the query string.

Body:
I am trying to redirect links that point at an old application to a new one. The new application can't handle direct links, so I want to point them to a search, but this search needs to be quoted to work properly. I have tried the following configuration but get 400 Bad Request if I do:

reqrep ^([^\ :]*)\ /\?pdf=(.*)  \1\ /newpdf?search=%22\2%22

The closest I have come is to remove everything after the last backreference, like this:

reqrep ^([^\ :]*)\ /\?pdf=(.*)  \1\ /newpdf?search=%22\2

Is it not possible to put anything after the last backreference?

Body:
The problem isn't text after the backreference.  You are overlooking the nature of the string you are manipating:

GET /page?pdf=foo HTTP/1.1 <<< here

After the URI there is a space and the HTTP version.  You're capturing that inside \2.  Separate it into \3, capturing a space and one or more non-space characters, anchored to the end.

reqrep ^([^\ :]*)\ /\?pdf=(.*)(\ [^\ ]+)$  \1\ /newpdf?search=%22\2%22\3

A better solution would be to use fetches and the http-request request modification capabilities to manipulate the query string.


问:
Clickable div with z-index
I want to make the same design below

But I have a problem with the floating div which is the camera icon.
It should be clickable. I put z-index so it will be on top of the image that will change. I want to make all div to be clickable.

Hope you guys can help me.

Thanks!

here's my code

```<code><article class="RegistrationInfo__Section media">
    <div class="RegistrationInfo__Section--image media-left">
      <div class="field">
        <span class="file-bg">
          <span
            class="icon is-large"
            v-if="formObject.image"
          >
            <img v-if src="~@/assets/images/camera.png">
          </span>

          <img v-else src="~@/assets/images/camera.png">
        </span>
        <div class="file is-boxed">
          <label class="file-label">
            <input
              class="file-input"
              type="file"
              name="image"
              ref="input"
              @change="validateAndProcessImage"
            >
            <span class="file-cta">
              <span class="file-icon">
                <img
                  v-if="formObject.image"
                  :src="`/api/files/${formObject.image}`"
                >
                <img v-else src="~@/assets/images/profile_off.png">
              </span>
            </span>
          </label>
        </div>
        <p v-if="formErrors.imageFiles" class="help is-danger">{{ formErrors.imageFiles[0] }}</p>
      </div>
    </div>
  </article>
</code>```

Here's my SCSS file.

```<code>.RegistrationInfo {
@at-root #{&}__Section {
@at-root #{&}--image {
  margin-right: 2rem;
  .field {
    position: relative;

    .file-bg {
      position: absolute;
      z-index: 1;
      right: -10px;
      width: 50px;
      height: 50px;

      .icon i {
        cursor: pointer;
        margin: auto;
      }
    }

    .file {
      &.is-boxed {
        .file-icon {
          height: 128px;
          width: 128px;
          margin-right: 0;
        }
        .file-cta {
          padding: 0;
          border-radius: 50%;
          justify-content: center;

          img {
            height: 128px;
            width: 128px;
            border-radius: 50%;
            object-fit: cover;
            object-position: top;
          }
        }
      }
    }

    .help {
      max-width: 128px;
    }
  }
}
</code>```

答:
The problem seems to be with the z-index you did set.

By default, all page elements have a z-index of 1 unless otherwise specified. Provided that .file-bg is your camera icon, changing the z-index to 2 would make your div clickable.

Title: Clickable div with z-index

Body:
I want to make the same design below

But I have a problem with the floating div which is the camera icon.
It should be clickable. I put z-index so it will be on top of the image that will change. I want to make all div to be clickable.

Hope you guys can help me.

Thanks!

here's my code

            <input
              class="file-input"
              type="file"
              name="image"
              ref="input"
              @change="validateAndProcessImage"
            >

                <img
                  v-if="formObject.image"
                  :src="`/api/files/${formObject.image}`"
                >

{{ formErrors.imageFiles[0] }}

Here's my SCSS file.

.RegistrationInfo {
@at-root #{&}__Section {
@at-root #{&}--image {
  margin-right: 2rem;
  .field {
    position: relative;

    .file-bg {
      position: absolute;
      z-index: 1;
      right: -10px;
      width: 50px;
      height: 50px;

      .icon i {
        cursor: pointer;
        margin: auto;
      }
    }

    .file {
      &.is-boxed {
        .file-icon {
          height: 128px;
          width: 128px;
          margin-right: 0;
        }
        .file-cta {
          padding: 0;
          border-radius: 50%;
          justify-content: center;

          img {
            height: 128px;
            width: 128px;
            border-radius: 50%;
            object-fit: cover;
            object-position: top;
          }
        }
      }
    }

    .help {
      max-width: 128px;
    }
  }
}


问:
opencv translation vector in known unit
Is there any way to compute translation vector in a known unit like 'mm' or 'cm' between two planar objects using corresponding feature points. If yes, please let me know how can I do that.

So far I've tried with Essential Matrix computation (for non planer objects) and didn't get them in a known unit.

Thanking You in advance!

答:
Only if you know the physical distance between some of those points (at least two) on the plane, so to fix the scale. Otherwise you are out of luck.

Without a reference distance, there is no way to tell whether you are looking at two buildings hundred of yards away, or two matchboxes nearby: this is how miniature visual effects in movies are done.

Title: opencv translation vector in known unit


问:
wsdl.exe Error: Unable to import binding '...' from namespace '...'
When running wsdl.exe on a WSDL I created, I get this error:

Error: Unable to import binding 'SomeBinding' from namespace 'SomeNS'.

Unable to import operation 'someOperation'.

These members may not be derived.

I'm using the document-literal style, and to the best of my knowledge I'm following all the rules.

To sum it up, I have a valid WSDL, but the tool doesn't like it.

What I'm looking for is if someone has lots of experience with the wsdl.exe tool and knows about some secret gotcha that I don't.

答:
I have came across to the same error message. After digging for a while, found out that one can supply xsd files in addition to wsdl file. So included/imported .xsd files in addition to .wsdl at the end of the wsdl command as follows:

wsdl.exe myWebService.wsdl myXsd1.xsd myType1.xsd myXsd2.xsd ...

Wsdl gave some warnings but it did create an ok service interface.

OwnerDisplayName: Ryono

LastEditorDisplayName: Ryono


问:
Enabling Highlight On Click for jQuery Map Highlighting
I am making diagrams using the jQuery Highlight Plugin
(http://davidlynch.org/js/maphilight/docs/) and I currently have the diagram that is clickable and loading content based on the area you are clicking on (like simple tabs).

However, I need the map to highlight on click and disable any other highlighted areas. Right now, I can make the area highlight on click, but not disable any existing highlights. I'd also like to have the diagram switch the content on hover, but that isn't as important right now as the highlight on click.

I have my current version up for a demo:
http://jsfiddle.net/keith/PVpgK/

or the fullscreen result:
http://jsfiddle.net/keith/PVpgK/embedded/result/

Thanks in advance for any help

答:
You need to loop through the other areas and turn off the alwayson to have the last click unhighlight on a new click.  Try something like this:</p>

```<code>  //map clicks
   $(".tabs area").click(function(){

       //AREAS LOOP:
       $(".tabs area").each(function(){
           var d = $(this).data('maphilight') || {};
           if(d.alwaysOn == true){
             d.alwaysOn = false;
           }
         });

//DISPLAY CURRENT LI FUNCTION:
$('.tabs area').mouseover(function(){

     var thisTarget = $(this).attr("href");

    if(thisTarget){
        $('#test').innerHTML = thisTarget;
    }
     $(this).parents(".tabs").find('area.current').removeClass('current');

     $(this).addClass('current');

     $(this).parents(".tabs").nextAll(".tab-content").children(":visible").fadeOut(1, function() {
         $(thisTarget).fadeIn("fast");
     });

});
   //This block is what creates highlighting by trigger the "alwaysOn",
   var data = $(this).data('maphilight') || {};
   data.alwaysOn = true;  //NOTICE I MADE THIS ALWAYS TRUE
   $(this).data('maphilight', data).trigger('alwaysOn.maphilight');
   //there is also "neverOn" in the docs, but not sure how to get it to work

   if ($(this).hasClass("current") == false)
   {
       var thisTarget = $(this).attr("href");

       $(this).parents(".tabs").find('area.current').removeClass('current');

       $(this).addClass('current');

       $(this).parents(".tabs").nextAll(".tab-content").children(":visible").fadeOut(1, function() {
           $(thisTarget).fadeIn("fast");
       });

   }
   return false;
  });
</code>```

Body:
You need to loop through the other areas and turn off the alwayson to have the last click unhighlight on a new click.  Try something like this:

  //map clicks
   $(".tabs area").click(function(){

       //AREAS LOOP:
       $(".tabs area").each(function(){
           var d = $(this).data('maphilight') || {};
           if(d.alwaysOn == true){
             d.alwaysOn = false;
           }
         });

//DISPLAY CURRENT LI FUNCTION:
$('.tabs area').mouseover(function(){

     var thisTarget = $(this).attr("href");

    if(thisTarget){
        $('#test').innerHTML = thisTarget;
    }
     $(this).parents(".tabs").find('area.current').removeClass('current');

     $(this).addClass('current');

     $(this).parents(".tabs").nextAll(".tab-content").children(":visible").fadeOut(1, function() {
         $(thisTarget).fadeIn("fast");
     });

});
   //This block is what creates highlighting by trigger the "alwaysOn",
   var data = $(this).data('maphilight') || {};
   data.alwaysOn = true;  //NOTICE I MADE THIS ALWAYS TRUE
   $(this).data('maphilight', data).trigger('alwaysOn.maphilight');
   //there is also "neverOn" in the docs, but not sure how to get it to work

   if ($(this).hasClass("current") == false)
   {
       var thisTarget = $(this).attr("href");

       $(this).parents(".tabs").find('area.current').removeClass('current');

       $(this).addClass('current');

       $(this).parents(".tabs").nextAll(".tab-content").children(":visible").fadeOut(1, function() {
           $(thisTarget).fadeIn("fast");
       });

   }
   return false;
  });


问:
Laravel how to retrieve name with user_id using angular?
I'm only able to fetch data with title and body attribute, but when i get data for the name it shows up empty when i refresh the page but shows when i submit automatically.

For some reason angularjs is not retrieving the name successfully.

Note: I'm using laravel.

For example here:

Here is the server side:

PostController

```<code>public function getPosts() {

  $posts = Post::with('user')->get();
  $response = new Response(json_encode($posts));
  $response->headers->set('Content-Type', 'application/json');
  return $response;
}

public function storePost(Request $request) {
  $data = request()->validate([
    'title' => 'required|max:120',
    'body' => 'required|max:1000'
  ]);

  $data['user_id'] = auth()->user()->id;
  $data['name'] = auth()->user()->name;

  $post = Post::create($data);

  $response = new Response(json_encode($data));
  $response->headers->set('Content-Type', 'application/json');

  // return redirect('/home')->withMessage('A new post was created.');

  return $response;
}
</code>```

main.js

```<code>$scope.myposts = {};

$scope.addPost = function() {

  $http.post('/auth/post', {
    title: $scope.post.title,
    body: $scope.post.body

  }).then(function(data, status, headers, config) {
    console.log(data);
    $scope.myposts.push(data.data);

  });

  $scope.post.title = '';
  $scope.post.body = '';

};

$scope.deletePost = function(post) {
  var index = $scope.myposts.indexOf(post);

  if (index != -1) {
    $scope.myposts.splice(index, 1);
  }

  $http.delete('auth/post/' + post.id);
};

$scope.getPosts = function() {

  $http.get('/auth/posts').then(function(data) {
    $scope.myposts = data.data;
  }).then(function(data, status, header, config) {});
};
</code>```

HTML:

```<code><div id="mypost" class="col-md-8 panel-default" ng-repeat="post in myposts">
  <div id="eli-style-heading" class="panel-heading">
    <% post.title %>
  </div>
  <div class="panel-body panel">
    <figure>
      <p>
        <% post.body %>
      </p>
      by:
      <p>
        <% post.user.name %>
      </p>

    </figure>
    <span><button ng-click="deletePost(post)">x</button></span>
  </div>
</div>
</code>```

When i first add content without refresh(asynchronously)

on page refresh

above
(different log for different post)

答:
Your reload page is okay since

```<code>$posts = Post::with('user')->get();
</code>```

returns

```<code>{
    "title": "title",
    "body": "body",
    "user":  {
        "name": "name"
    }
}
</code>```

and in your angular you display it by

```<code><% post.user.name %>
</code>```

So the solution to display it when you added is to restructure your json object before pushing to array

```<code>$scope.addPost = function() {

  $http.post('/auth/post', {
    title: $scope.post.title,
    body: $scope.post.body

  }).then(function(data, status, headers, config) {
    console.log(data);

    data.data['user'] = {
        name: data.data.name
    }

    $scope.myposts.push(data.data);

  });

  $scope.post.title = '';
  $scope.post.body = '';

};
</code>```

Body:
I'm only able to fetch data with title and body attribute, but when i get data for the name it shows up empty when i refresh the page but shows when i submit automatically.

For some reason angularjs is not retrieving the name successfully.

Note: I'm using laravel.

For example here:

Here is the server side:

PostController

public function getPosts() {

  $posts = Post::with('user')->get();
  $response = new Response(json_encode($posts));
  $response->headers->set('Content-Type', 'application/json');
  return $response;
}

public function storePost(Request $request) {
  $data = request()->validate([
    'title' => 'required|max:120',
    'body' => 'required|max:1000'
  ]);

  $data['user_id'] = auth()->user()->id;
  $data['name'] = auth()->user()->name;

  $post = Post::create($data);

  $response = new Response(json_encode($data));
  $response->headers->set('Content-Type', 'application/json');

  // return redirect('/home')->withMessage('A new post was created.');

  return $response;
}

main.js

$scope.myposts = {};

$scope.addPost = function() {

  $http.post('/auth/post', {
    title: $scope.post.title,
    body: $scope.post.body

  }).then(function(data, status, headers, config) {
    console.log(data);
    $scope.myposts.push(data.data);

  });

  $scope.post.title = '';
  $scope.post.body = '';

};

$scope.deletePost = function(post) {
  var index = $scope.myposts.indexOf(post);

  if (index != -1) {
    $scope.myposts.splice(index, 1);
  }

  $http.delete('auth/post/' + post.id);
};

$scope.getPosts = function() {

  $http.get('/auth/posts').then(function(data) {
    $scope.myposts = data.data;
  }).then(function(data, status, header, config) {});
};

HTML:

    <% post.title %>

        <% post.body %>

      by:

        <% post.user.name %>

    <button ng-click="deletePost(post)">x</button>

When i first add content without refresh(asynchronously)

on page refresh

above
(different log for different post)

Body:
Your reload page is okay since

$posts = Post::with('user')->get();

returns

{
    "title": "title",
    "body": "body",
    "user":  {
        "name": "name"
    }
}

and in your angular you display it by

<% post.user.name %>

So the solution to display it when you added is to restructure your json object before pushing to array

$scope.addPost = function() {

  $http.post('/auth/post', {
    title: $scope.post.title,
    body: $scope.post.body

  }).then(function(data, status, headers, config) {
    console.log(data);

    data.data['user'] = {
        name: data.data.name
    }

    $scope.myposts.push(data.data);

  });

  $scope.post.title = '';
  $scope.post.body = '';

};


问:
How to track deleted database
Suppose my sql server 2008 with username(sa) and password(testpass),with a instance(mypc).

i am having two computer name system1 and system2. If i am deleting the any database then

how can i track from which system this desired database is deleted.

答:
You can set up a server audit to monitor all CREATE/ALTER/DROP DATABASE events.</p>

```<code>CREATE SERVER AUDIT [DatabaseChanges]
    TO APPLICATION_LOG;

CREATE SERVER AUDIT SPECIFICATION [DatabaseChangesSpec]
FOR SERVER AUDIT [DatabaseChanges]
    ADD (DATABASE_CHANGE_GROUP);
</code>```

Title: How to track deleted database

Body:
You can set up a server audit to monitor all CREATE/ALTER/DROP DATABASE events.

CREATE SERVER AUDIT [DatabaseChanges]
    TO APPLICATION_LOG;

CREATE SERVER AUDIT SPECIFICATION [DatabaseChangesSpec]
FOR SERVER AUDIT [DatabaseChanges]
    ADD (DATABASE_CHANGE_GROUP);


问:
How to join integers intervals in python?
I have used the module intervals (http://pyinterval.readthedocs.io/en/latest/index.html)

And created an interval from a set or start, end tuples:

```<code>intervals = interval.interval([1,8], [7,10], [15,20])
</code>```

Which result in interval([1.0, 10.0], [15.0, 20.0]) as the [1,8] and [7,10] overlaps.

But this module interprets the values of the pairs as real numbers, so two continuous intervals in integers will not be joined together.

Example:

```<code>intervals = interval.interval([1,8], [9,10], [11,20])
</code>```

results in: interval([1.0, 8.0], [9.0, 10.0], [11.0, 20.0])

My question is how can I join this intervals as integers and not as real numbers? And in the last example the result would be interval([1.0, 20.0])

答:
I believe you can use pyintervals for integer intervals too by adding interval([-0.5, 0.5]). With your example you get

```<code>In[40]:  interval([1,8], [9,10], [11,20]) + interval([-0.5, 0.5])
Out[40]: interval([0.5, 20.5])
</code>```

Body:
I have used the module intervals (http://pyinterval.readthedocs.io/en/latest/index.html)

And created an interval from a set or start, end tuples:

intervals = interval.interval([1,8], [7,10], [15,20])

Which result in interval([1.0, 10.0], [15.0, 20.0]) as the [1,8] and [7,10] overlaps.

But this module interprets the values of the pairs as real numbers, so two continuous intervals in integers will not be joined together.

Example:

intervals = interval.interval([1,8], [9,10], [11,20])

results in: interval([1.0, 8.0], [9.0, 10.0], [11.0, 20.0])

My question is how can I join this intervals as integers and not as real numbers? And in the last example the result would be interval([1.0, 20.0])

Body:
I believe you can use pyintervals for integer intervals too by adding interval([-0.5, 0.5]). With your example you get

In[40]:  interval([1,8], [9,10], [11,20]) + interval([-0.5, 0.5])
Out[40]: interval([0.5, 20.5])


问:
I'm trying getting an error when trying to integrate Google Sign In to my Android app: Cannot Resolve Symbol GoogleSignIn
I'm trying to integrate Google Sign In to my Android up but i'm getting an error that the symbol GoogleSignIn cannot be resolved: https://snag.gy/R2Mg3L.jpg

Here is the code and Gradle files for the project; I'm following the instructions provided by Google at: https://developers.google.com/identity/sign-in/android/

```<code>package com.example.GSTest;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.google.android.gms.auth.api.signin.GoogleSignIn;

import com.google.android.gms.auth.api.signin.GoogleSignInOptions;

public class loginActivity extends AppCompatActivity implements View.OnClickListener{

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    // Configure sign-in to request the user's ID, email address, and basic
    // profile. ID and basic profile are included in DEFAULT_SIGN_IN.
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .build();

    // Build a GoogleSignInClient with the options specified by gso.
    mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

    Button gButton = findViewById(R.id.sign_in_button);
    gButton.setOnClickListener(this);
}

@Override
public void onClick(View v){

    switch (v.getId()) {
        case R.id.sign_in_button:
            signIn();
            break;
        // ...
    }

}

private void signIn() {
    Intent signInIntent = mGoogleSignInClient.getSignInIntent();
    startActivityForResult(signInIntent, RC_SIGN_IN);
}

//end of main class
}
</code>```

Gradle (Project):

```<code>// Top-level build file where you can add configuration options common to
all sub-projects/modules.

buildscript {

repositories {
    google()
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.0.0'
    classpath 'com.google.gms:google-services:3.1.0'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
repositories {
    google()
    jcenter()
}
}

task clean(type: Delete) {
delete rootProject.buildDir
}
</code>```

Gradle (Module):

```<code>apply plugin: 'com.android.application'

android {
compileSdkVersion 26
defaultConfig {
    applicationId "com.example.GSTest"
    minSdkVersion 15
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner
"android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
    }
}
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.google.gms:google-services:3.1.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-
core:3.0.1'
apply plugin: 'com.google.gms.google-services'
}
</code>```

答:
Like all import problems, check your dependencies.

You're trying to use code requiring at least the 11.6.0 release of Google Play

Added the GoogleSignInClient and GoogleSignIn classes. GoogleSignInClient provides the entry point for interacting with the Google Sign In API.

Update the version in your Gradle file

Body:
I'm trying to integrate Google Sign In to my Android up but i'm getting an error that the symbol GoogleSignIn cannot be resolved: https://snag.gy/R2Mg3L.jpg

Here is the code and Gradle files for the project; I'm following the instructions provided by Google at: https://developers.google.com/identity/sign-in/android/

package com.example.GSTest;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.google.android.gms.auth.api.signin.GoogleSignIn;

import com.google.android.gms.auth.api.signin.GoogleSignInOptions;

public class loginActivity extends AppCompatActivity implements View.OnClickListener{

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    // Configure sign-in to request the user's ID, email address, and basic
    // profile. ID and basic profile are included in DEFAULT_SIGN_IN.
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .build();

    // Build a GoogleSignInClient with the options specified by gso.
    mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

    Button gButton = findViewById(R.id.sign_in_button);
    gButton.setOnClickListener(this);
}

@Override
public void onClick(View v){

    switch (v.getId()) {
        case R.id.sign_in_button:
            signIn();
            break;
        // ...
    }

}

private void signIn() {
    Intent signInIntent = mGoogleSignInClient.getSignInIntent();
    startActivityForResult(signInIntent, RC_SIGN_IN);
}

//end of main class
}

Gradle (Project):

// Top-level build file where you can add configuration options common to
all sub-projects/modules.

buildscript {

repositories {
    google()
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.0.0'
    classpath 'com.google.gms:google-services:3.1.0'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
repositories {
    google()
    jcenter()
}
}

task clean(type: Delete) {
delete rootProject.buildDir
}

Gradle (Module):

apply plugin: 'com.android.application'

android {
compileSdkVersion 26
defaultConfig {
    applicationId "com.example.GSTest"
    minSdkVersion 15
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner
"android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
    }
}
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.google.gms:google-services:3.1.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-
core:3.0.1'
apply plugin: 'com.google.gms.google-services'
}


答:
Because, your suffixes[suffixIndex] is a string that holds 'KB' string!
so changing

```<code>return "%.*f %d"%(precision,size,suffixes[suffixIndex])
</code>```

to

```<code>return "%.*f %s"%(precision,size,suffixes[suffixIndex])
</code>```

will get the desired output!

To writer the data to file as:

```<code>def list_files(startpath):
    with open('output.txt','w') as file:
        for root, dirs, files in os.walk(startpath):
            level = root.replace(startpath, '').count(os.sep)
            indent = ' ,' * 4 * (level)
            file.write('{}{}/\n'.format(indent, os.path.basename(root)))
            subindent = ' ,' * 4 * (level + 1)
            for f in sorted(files, key=lambda f: os.path.getsize(root + os.sep + f)):
                converted_size = GetHumanReadable(os.path.getsize(root + os.sep + f))
                file.write('{}{},{}\n'.format(subindent, f, converted_size))
</code>```

Title: Python code to get a folder structure along with size

Body:
Because, your suffixes[suffixIndex] is a string that holds 'KB' string!
so changing

return "%.*f %d"%(precision,size,suffixes[suffixIndex])

to

return "%.*f %s"%(precision,size,suffixes[suffixIndex])

will get the desired output!

To writer the data to file as:

def list_files(startpath):
    with open('output.txt','w') as file:
        for root, dirs, files in os.walk(startpath):
            level = root.replace(startpath, '').count(os.sep)
            indent = ' ,' * 4 * (level)
            file.write('{}{}/\n'.format(indent, os.path.basename(root)))
            subindent = ' ,' * 4 * (level + 1)
            for f in sorted(files, key=lambda f: os.path.getsize(root + os.sep + f)):
                converted_size = GetHumanReadable(os.path.getsize(root + os.sep + f))
                file.write('{}{},{}\n'.format(subindent, f, converted_size))


问:
Cannot resolve method 'loadTrustMaterial'
I am using Android studio (in Linux) to make a project and in which I had to write code by which I can accept all the certificates. But the problem I am facing while using TrustSelfSignedStrategy is that when I pass this through builder.loadTrustMaterial, it shows something like Cannot resolve method 'loadTrustMaterial'(null,org.apache.http.conn.TrustSelfSignedStrategy).

A screenshot has been attached. However, the same code is working in Eclipse with the same library.

答:
loadTrustMaterial

```<code> public SSLContextBuilder loadTrustMaterial(KeyStore truststore,
                                  TrustStrategy trustStrategy)
                                    throws NoSuchAlgorithmException,
                                           KeyStoreException
</code>```

You should use TrustStrategy instead of TrustSelfSignedStrategy.

```<code>TrustStrategy trust_stgOBJ = new TrustStrategy()
</code>```

FYI

Moved from org.apache.http.conn.ssl.SSLContexts to
  org.apache.http.ssl.SSLContexts.

Read sslcontextbuilder and SSLContexts deprecated.

Body:
loadTrustMaterial

 public SSLContextBuilder loadTrustMaterial(KeyStore truststore,
                                  TrustStrategy trustStrategy)
                                    throws NoSuchAlgorithmException,
                                           KeyStoreException

You should use TrustStrategy instead of TrustSelfSignedStrategy.

TrustStrategy trust_stgOBJ = new TrustStrategy()

FYI

Moved from org.apache.http.conn.ssl.SSLContexts to
  org.apache.http.ssl.SSLContexts.

Read sslcontextbuilder and SSLContexts deprecated.


问:
Can we replace map with flatMap?
I was trying to find line with maximum words, and i wrote the following lines, to run on spark-shell:

```<code>import java.lang.Math

val counts = textFile.map(line => line.split(" ").size).reduce((a, b) => Math.max(a, b))
</code>```

But since, map is one to one , and flatMap is one to either zero or anything. So i tried replacing map with flatMap, in above code. But its giving error as:

```<code><console>:24: error: type mismatch;
found   : Int
required: TraversableOnce[?]
   val counts = F1.flatMap(s => s.split(" ").size).reduce((a,b)=> Math.max(a,b))
</code>```

If anybody could make me understand the reason, it will really be helpful.

答:
After reading Tired of Null Pointer Exceptions? Consider Using Java SE 8's Optional!'s part about why use flatMap() rather than Map(), I have realized the truly reason why flatMap() can not replace map() is that map() is not a special case of flatMap().

It's true that flatMap() means one-to-many, but that's not the only thing flatMap() does. It can also strip outer Stream() if put it simply.

See the definations of map and flatMap:

```<code>Stream<R> map(Function<? super T, ? extends R> mapper)
Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)
</code>```

the only difference is the type of returned value in inner function. What map() returned is "Stream<'what inner function returned'>", while what flatMap() returned is just "what inner function returned".

So you can say that flatMap() can kick outer Stream() away, but map() can't. This is the most difference in my opinion, and also why map() is not just a special case of flatMap().

ps:

If you really want to make one-to-one with flatMap, then you should change it into one-to-List(one). That means you should add an outer Stream() manually which will be stripped by flatMap() later. After that you'll get the same effect as using map().(Certainly, it's clumsy. So don't do like that.)

Here are examples for Java8, but the same as Scala:

use map():

```<code> list.stream().map(line -> line.split(" ").length)
</code>```

deprecated use flatMap():

```<code>list.stream().flatMap(line -> Arrays.asList(line.split(" ").length).stream())
</code>```

Title: Can we replace map with flatMap?

Body:
I was trying to find line with maximum words, and i wrote the following lines, to run on spark-shell:

import java.lang.Math

val counts = textFile.map(line => line.split(" ").size).reduce((a, b) => Math.max(a, b))

But since, map is one to one , and flatMap is one to either zero or anything. So i tried replacing map with flatMap, in above code. But its giving error as:

<console>:24: error: type mismatch;
found   : Int
required: TraversableOnce[?]
   val counts = F1.flatMap(s => s.split(" ").size).reduce((a,b)=> Math.max(a,b))

If anybody could make me understand the reason, it will really be helpful.

Body:
After reading Tired of Null Pointer Exceptions? Consider Using Java SE 8's Optional!'s part about why use flatMap() rather than Map(), I have realized the truly reason why flatMap() can not replace map() is that map() is not a special case of flatMap().

It's true that flatMap() means one-to-many, but that's not the only thing flatMap() does. It can also strip outer Stream() if put it simply.

See the definations of map and flatMap:

Stream<R> map(Function<? super T, ? extends R> mapper)
Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)

the only difference is the type of returned value in inner function. What map() returned is "Stream<'what inner function returned'>", while what flatMap() returned is just "what inner function returned".

So you can say that flatMap() can kick outer Stream() away, but map() can't. This is the most difference in my opinion, and also why map() is not just a special case of flatMap().

ps:

If you really want to make one-to-one with flatMap, then you should change it into one-to-List(one). That means you should add an outer Stream() manually which will be stripped by flatMap() later. After that you'll get the same effect as using map().(Certainly, it's clumsy. So don't do like that.)

Here are examples for Java8, but the same as Scala:

use map():

 list.stream().map(line -> line.split(" ").length)

deprecated use flatMap():

list.stream().flatMap(line -> Arrays.asList(line.split(" ").length).stream())


问:
Mock import/module with Jest in React application
I am working on a React application and I want to test one module, let's call it B, that depends on another module, let's call it A.

The scenario could be something like this:

moduleA.js

```<code>export function helperFn() {
  return { prop1: 10, prop2: 20 };
}
</code>```

moduleB.js

```<code>import React from 'react';
import { helperFn } from '../moduleA';

export class CustomComp extends React.Component {
  render() {
    const helperObj = helperFn();
    return (
      <div>{helperObj.prop1}</div>
    );
  }
}
</code>```

The core libraries to test my components are Jest and Enzyme. My goal here is to test module B, but I want to test it in isolation and so I want to mock the dependency on moduleA.js.

I know one way would be to inject the helperFn as a prop instead of importing it so during the test I can inject a mock function, but there are modules quite big on this app that have a few dependencies each of them.

Researching a bit I found it is posible to mock a dependecy using Jest, but I tried many things with no success. I tried approaches from this question, also from this post and I have no luck. I also read the Manual Mocks and Mock Functions guides from Jest docs, but I think they are pretty confusing.

I could make it work (i.e. I could mock moduleA.js dependency) using the approach on this post, but I had another problem then. It worked just fine to test moduleB.js, but when I went ahead and test moduleA.js, I had to import moduleA.js in moduleA.test.js and I got the mock while I wanted the real module.

So, I need help to understand how I can mock dependency A in moduleB test file.

I hope I was clear if not let me know and I will add the clarifications you might need.

Thanks in advance !

答:
Indeed you can use jest to mock your dependency. There is some configuration you need to set in order to make it work with import. E.g. configuring babel-jest.

If you already have that configuration then you can mock it like so.

```<code>import React from 'react';
import { shallow } from 'enzyme';
import { helperFn } from '../moduleA';
jest.mock('../moduleA');

describe("CustomComp", () => {
  it("should render component", () => {
    helperFn.mockReturnValueOnce({
      prop1: "dummy"
    });
    const component = shallow(<CustomComp />);
  });
</code>```

You can see a working example here.

Body:
I am working on a React application and I want to test one module, let's call it B, that depends on another module, let's call it A.

The scenario could be something like this:

moduleA.js

export function helperFn() {
  return { prop1: 10, prop2: 20 };
}

moduleB.js

import React from 'react';
import { helperFn } from '../moduleA';

export class CustomComp extends React.Component {
  render() {
    const helperObj = helperFn();
    return (

{helperObj.prop1}

    );
  }
}

The core libraries to test my components are Jest and Enzyme. My goal here is to test module B, but I want to test it in isolation and so I want to mock the dependency on moduleA.js.

I know one way would be to inject the helperFn as a prop instead of importing it so during the test I can inject a mock function, but there are modules quite big on this app that have a few dependencies each of them.

Researching a bit I found it is posible to mock a dependecy using Jest, but I tried many things with no success. I tried approaches from this question, also from this post and I have no luck. I also read the Manual Mocks and Mock Functions guides from Jest docs, but I think they are pretty confusing.

I could make it work (i.e. I could mock moduleA.js dependency) using the approach on this post, but I had another problem then. It worked just fine to test moduleB.js, but when I went ahead and test moduleA.js, I had to import moduleA.js in moduleA.test.js and I got the mock while I wanted the real module.

So, I need help to understand how I can mock dependency A in moduleB test file.

I hope I was clear if not let me know and I will add the clarifications you might need.

Thanks in advance !

Body:
Indeed you can use jest to mock your dependency. There is some configuration you need to set in order to make it work with import. E.g. configuring babel-jest.

If you already have that configuration then you can mock it like so.

import React from 'react';
import { shallow } from 'enzyme';
import { helperFn } from '../moduleA';
jest.mock('../moduleA');

describe("CustomComp", () => {
  it("should render component", () => {
    helperFn.mockReturnValueOnce({
      prop1: "dummy"
    });
    const component = shallow(<CustomComp />);
  });

You can see a working example here.


问:
Error:(246, 5) error: duplicate value for resource 'attr/rippleColor' with config ''
When I upgraded android studio to version 3 I've got this problem:

```<code>Error:(246, 5) error: duplicate value for resource 'attr/rippleColor' with config ''.
</code>```

this is my gradle:

```<code>    android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId "com.faravani.app"
        minSdkVersion 16
        targetSdkVersion 26
        versionCode 4
        versionName "2.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        vectorDrawables.useSupportLibrary = true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.1.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:design:26.1.0'
    testCompile 'junit:junit:4.12'
}
</code>```

please help me i don't know what should I do.

答:
change

```<code>supportLibraryVersion = "25.4.0"
</code>```

to

```<code>supportLibraryVersion = "25.3.1"
</code>```

works for me

Body:
When I upgraded android studio to version 3 I've got this problem:

Error:(246, 5) error: duplicate value for resource 'attr/rippleColor' with config ''.

this is my gradle:

    android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId "com.faravani.app"
        minSdkVersion 16
        targetSdkVersion 26
        versionCode 4
        versionName "2.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        vectorDrawables.useSupportLibrary = true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.1.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:design:26.1.0'
    testCompile 'junit:junit:4.12'
}

please help me i don't know what should I do.

Body:
change

supportLibraryVersion = "25.4.0"

to

supportLibraryVersion = "25.3.1"

works for me


问:
Please Explain meaning of {} syntax for me
I am a newbie and try to learn PHP especially INSERT INTO statement. I'm know that if we insert value for String we must use '' syntax. But i don't understand meaning of {} syntax for "title" and"link". Any guys can explain for me. Thanks a lot.

答:
On Sql side there is no difference between '$title' or '{$title}' . but in php {$title} is a more complete syntax of $title, that allows one to use :

"this is post {$title}s"

"{$object->data}"

"{$array['data']}"

"{$array['data']->obj->plop['test']}"

The curly braces "escape" the PHP variable and are not passed to MySQL. With a simple variable like $title it doesn't make a difference but with something like $post['title'] it does. for more information check this


问:
Sending and receiving byte array in java
I'm having some trouble with my socket programming codes. I have a server tcp that receives the password from client, if it's true, the server will send a file back to client to save, else server will send a byte array with the length is 0.

Then the client will receive the byte array and get the length to compare with 0, if byte length = 0, the client will print out "Wrong password", else it will tell you to enter the file name.

The big problem is the server sent byte array with length = 0 when password is wrong, but client receive byte array with length = 1. I do not know how to solve it....:(

Here is my TCPServer code:

import java.io.*;
import java.net.*;
import java.util.Scanner;

class ServerTCP{
 public static void main (String[] args){
  try{
   ServerSocket ss = new ServerSocket(2018);
   System.out.println("\n(*) Server Socket has been created!");
   while(true){
    Socket s = ss.accept();
    InputStream is = s.getInputStream();
    OutputStream os = s.getOutputStream();
    PrintWriter pw = new PrintWriter(os);
    Scanner sc = new Scanner(is);
    //Receive information from client
    String mail = sc.nextLine();
    String pass = sc.nextLine();
    System.out.println("Password is: " + pass);
    if(matkhau.equals("passtcp")){
     String filegui = "D:/filename.pdf";
     FileInputStream f = new FileInputStream(filegui);
     int lenf = f.available();
     byte b2[] = new byte[lenf];
     f.read(b2);
     f.close();
     os.write(b2);
    }
    else{
     byte b[] = new byte[1];
     int lenb = 0;
     os.write(b);
    }
   }
  }catch(IOException e){
   System.out.println("\n(!)An error occured while creating socket!");
  }
 }
}```
</div>
</div>
</p>

<p>Here is my client code</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>import java.net.*;
import java.io.*;
import java.util.Scanner;

class UdpTcpTest{
 public static void main (String[] args){
  //String matkhau = new String();
  Scanner k = new Scanner(System.in);
    try{
   //Enter TCP Server's ip
   System.out.print("Enter TCP Server's ip: ");
   String ip1 = k.nextLine();
   //Tao socket
   Socket s = new Socket(ip1, 2018);
   InputStream is = s.getInputStream();
   OutputStream os = s.getOutputStream();
   PrintWriter pw = new PrintWriter(os);
   String mail = "yourmail@test.com";
   String password = "matkhaune";
   //send mail and password to server
   pw.println(mail); pw.flush();
   pw.println(password); pw.flush();
   //receive information
   byte brecv[] = new byte[60000];
   int lenfile = is.read(brecv);
   System.out.println("Length = " + lenfile);
   if(lenfile <= 1){
    System.out.println("Wrong password! Length = " + lenfile);
   }
   else{
    //Save file
    System.out.print("Enter file name to save: ");
    String filenamed = k.nextLine();
    FileOutputStream f = new FileOutputStream(filenamed);
    f.write(brecv, 0, lenfile);
    f.close();
    System.out.println("Saving Scuccess!");
    s.close();
   }
  }catch(IOException e){
   System.out.println("Error while excuting!");
  }

 }
}</code>```

答:
I'm having some trouble with my socket programming codes. I have a server tcp that receives the password from client, if it's true, the server will send a file back to client to save, else server will send a byte array with the length is 0.

Impossible.

Then the client will receive the byte array and get the length to compare with 0, if byte length = 0, the client will print out "Wrong password", else it will tell you to enter the file name.

Impossible. You will have to redesign your protocol. You can't send a byte array of zero length over TCP. The minimum is one byte.

The big problem is the server sent byte array with length = 0 when password is wrong

No it didn't. It sent a byte array with length = 1:

```<code>byte b[] = new byte[1]; // Here is your byte array of length 1
int lenb = 0;  // This is unused. Delete.
os.write(b);   // Here you are sending the entire byte array
</code>```

but client receive byte array with length = 1.

That is correct.

I do not know how to solve it....:(

There is nothing here to solve. Your code is working as designed. You just need to adjust your client to test for a 1-byte receive instead of an impossible zero-byte receive:

```<code>int lenfile = is.read(brecv);
System.out.println("Length = " + lenfile);
if(lenfile == 1){
</code>```

Body:
I'm having some trouble with my socket programming codes. I have a server tcp that receives the password from client, if it's true, the server will send a file back to client to save, else server will send a byte array with the length is 0.

Then the client will receive the byte array and get the length to compare with 0, if byte length = 0, the client will print out "Wrong password", else it will tell you to enter the file name.

The big problem is the server sent byte array with length = 0 when password is wrong, but client receive byte array with length = 1. I do not know how to solve it....:(

Here is my TCPServer code:

import java.io.*;
import java.net.*;
import java.util.Scanner;

class ServerTCP{
 public static void main (String[] args){
  try{
   ServerSocket ss = new ServerSocket(2018);
   System.out.println("\n(*) Server Socket has been created!");
   while(true){
    Socket s = ss.accept();
    InputStream is = s.getInputStream();
    OutputStream os = s.getOutputStream();
    PrintWriter pw = new PrintWriter(os);
    Scanner sc = new Scanner(is);
    //Receive information from client
    String mail = sc.nextLine();
    String pass = sc.nextLine();
    System.out.println("Password is: " + pass);
    if(matkhau.equals("passtcp")){
     String filegui = "D:/filename.pdf";
     FileInputStream f = new FileInputStream(filegui);
     int lenf = f.available();
     byte b2[] = new byte[lenf];
     f.read(b2);
     f.close();
     os.write(b2);
    }
    else{
     byte b[] = new byte[1];
     int lenb = 0;
     os.write(b);
    }
   }
  }catch(IOException e){
   System.out.println("\n(!)An error occured while creating socket!");
  }
 }
}

Here is my client code

import java.net.*;
import java.io.*;
import java.util.Scanner;

class UdpTcpTest{
 public static void main (String[] args){
  //String matkhau = new String();
  Scanner k = new Scanner(System.in);
    try{
   //Enter TCP Server's ip
   System.out.print("Enter TCP Server's ip: ");
   String ip1 = k.nextLine();
   //Tao socket
   Socket s = new Socket(ip1, 2018);
   InputStream is = s.getInputStream();
   OutputStream os = s.getOutputStream();
   PrintWriter pw = new PrintWriter(os);
   String mail = "yourmail@test.com";
   String password = "matkhaune";
   //send mail and password to server
   pw.println(mail); pw.flush();
   pw.println(password); pw.flush();
   //receive information
   byte brecv[] = new byte[60000];
   int lenfile = is.read(brecv);
   System.out.println("Length = " + lenfile);
   if(lenfile <= 1){
    System.out.println("Wrong password! Length = " + lenfile);
   }
   else{
    //Save file
    System.out.print("Enter file name to save: ");
    String filenamed = k.nextLine();
    FileOutputStream f = new FileOutputStream(filenamed);
    f.write(brecv, 0, lenfile);
    f.close();
    System.out.println("Saving Scuccess!");
    s.close();
   }
  }catch(IOException e){
   System.out.println("Error while excuting!");
  }

 }
}

Body:
I'm having some trouble with my socket programming codes. I have a server tcp that receives the password from client, if it's true, the server will send a file back to client to save, else server will send a byte array with the length is 0.

Impossible.

Then the client will receive the byte array and get the length to compare with 0, if byte length = 0, the client will print out "Wrong password", else it will tell you to enter the file name.

Impossible. You will have to redesign your protocol. You can't send a byte array of zero length over TCP. The minimum is one byte.

The big problem is the server sent byte array with length = 0 when password is wrong

No it didn't. It sent a byte array with length = 1:

byte b[] = new byte[1]; // Here is your byte array of length 1
int lenb = 0;  // This is unused. Delete.
os.write(b);   // Here you are sending the entire byte array

but client receive byte array with length = 1.

That is correct.

I do not know how to solve it....:(

There is nothing here to solve. Your code is working as designed. You just need to adjust your client to test for a 1-byte receive instead of an impossible zero-byte receive:

int lenfile = is.read(brecv);
System.out.println("Length = " + lenfile);
if(lenfile == 1){


问:
ValueError: Invalid field u'field' in leaf "<osv.ExtendedLeaf: (u'field', u'in', [59]) on object (ctx: )>" - Odoo v8
I have these methods:

```<code>@api.depends('order_lines', 'order_lines.isbn')
def _get_products(self):
    isbn = self.env['product.product']
    for prodtmpl in self.order_lines:
        isbn |= prodtmpl.isbn
    return isbn

@api.model
def _get_act_window_dict(self, name):
    mod_obj = self.env['ir.model.data']
    result = mod_obj.xmlid_to_object(name)
    if not result:
        result = {
            'view_type': 'form',
            'view_mode': 'tree,form',
            'res_model': 'stock.quant',
            'name': 'Stock On Hand',
            'type': 'ir.actions.act_window',
        }
    else:
        result = result[0].read()[0]
    return result

@api.multi
def action_open_isbn(self):
    isbn = self._get_products()
    result = self._get_act_window_dict('stock.product_open_quants')
    result['domain'] = "[('isbn','in',[" + ','.join(map(str, isbn.ids)) + "])]"
    result['context'] = "{'search_default_locationgroup': 1, 'search_default_internal_loc': 1}"
    return result
</code>```

On method get_act_window_dict it should return products on quants, like on Qty On Hand from product.template

But it throws me this:

```<code>Traceback (most recent call last):
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 546, in _handle_exception
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 583, in dispatch
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 319, in _call_function
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\service\model.py", line 118, in wrapper
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 316, in checked_call
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 812, in __call__
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 412, in response_wrap
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\openerp\addons\web\controllers\main.py", line 944, in call_kw
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\openerp\addons\web\controllers\main.py", line 936, in _call_kw
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\api.py", line 268, in wrapper
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\openerp\addons\stock\stock.py", line 331, in read_group
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\api.py", line 268, in wrapper
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\models.py", line 2082, in read_group
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\api.py", line 268, in wrapper
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\models.py", line 4498, in _where_calc
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\osv\expression.py", line 662, in __init__
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\osv\expression.py", line 830, in parse
ValueError: Invalid field u'isbn' in leaf "<osv.ExtendedLeaf: (u'isbn', u'in', [59]) on stock_quant (ctx: )>"
</code>```

I've tried doing this:

```<code>@api.model
def _get_act_window_dict(self, name):
    mod_obj = self.env['ir.model.data']
    result = mod_obj.xmlid_to_object(name)
    if not result:
        result = {
            'view_type': 'form',
            'view_mode': 'tree,form',
            'res_model': 'stock.quant',
            'name': 'Stock On Hand',
            'isbn': 'product_id',
            'type': 'ir.actions.act_window',
        }
    else:
        result = result[0].read()[0]
    return result
</code>```

Adding isbn to the dict result as product_id but same result.

So, any ideas?

PS: This is isbn field on my class:

```<code>    isbn = fields.Many2one('product.product', string="ISBN", domain="[('is_isbn', '=', True)]")
</code>```

Of course it doesn't exist as isbn on stock.quant but it's a Many2one to product so it should pass somehow.

答:
This line:

```<code>result['domain'] = "[('isbn','in',[" + ','.join(map(str, isbn.ids)) + "])]"
</code>```

should be:

```<code>result['domain'] = "[('product_id','in',[" + ','.join(map(str, isbn.ids)) + "])]"
</code>```

No field isbn in stock.quant. Since isbn is object product.product, I think it's just the same with product_id of stock.quant

Body:
I have these methods:

@api.depends('order_lines', 'order_lines.isbn')
def _get_products(self):
    isbn = self.env['product.product']
    for prodtmpl in self.order_lines:
        isbn |= prodtmpl.isbn
    return isbn

@api.model
def _get_act_window_dict(self, name):
    mod_obj = self.env['ir.model.data']
    result = mod_obj.xmlid_to_object(name)
    if not result:
        result = {
            'view_type': 'form',
            'view_mode': 'tree,form',
            'res_model': 'stock.quant',
            'name': 'Stock On Hand',
            'type': 'ir.actions.act_window',
        }
    else:
        result = result[0].read()[0]
    return result

@api.multi
def action_open_isbn(self):
    isbn = self._get_products()
    result = self._get_act_window_dict('stock.product_open_quants')
    result['domain'] = "[('isbn','in',[" + ','.join(map(str, isbn.ids)) + "])]"
    result['context'] = "{'search_default_locationgroup': 1, 'search_default_internal_loc': 1}"
    return result

On method get_act_window_dict it should return products on quants, like on Qty On Hand from product.template

But it throws me this:

Traceback (most recent call last):
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 546, in _handle_exception
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 583, in dispatch
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 319, in _call_function
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\service\model.py", line 118, in wrapper
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 316, in checked_call
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 812, in __call__
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 412, in response_wrap
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\openerp\addons\web\controllers\main.py", line 944, in call_kw
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\openerp\addons\web\controllers\main.py", line 936, in _call_kw
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\api.py", line 268, in wrapper
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\openerp\addons\stock\stock.py", line 331, in read_group
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\api.py", line 268, in wrapper
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\models.py", line 2082, in read_group
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\api.py", line 268, in wrapper
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\models.py", line 4498, in _where_calc
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\osv\expression.py", line 662, in __init__
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\osv\expression.py", line 830, in parse
ValueError: Invalid field u'isbn' in leaf "<osv.ExtendedLeaf: (u'isbn', u'in', [59]) on stock_quant (ctx: )>"

I've tried doing this:

@api.model
def _get_act_window_dict(self, name):
    mod_obj = self.env['ir.model.data']
    result = mod_obj.xmlid_to_object(name)
    if not result:
        result = {
            'view_type': 'form',
            'view_mode': 'tree,form',
            'res_model': 'stock.quant',
            'name': 'Stock On Hand',
            'isbn': 'product_id',
            'type': 'ir.actions.act_window',
        }
    else:
        result = result[0].read()[0]
    return result

Adding isbn to the dict result as product_id but same result.

So, any ideas?

PS: This is isbn field on my class:

    isbn = fields.Many2one('product.product', string="ISBN", domain="[('is_isbn', '=', True)]")

Of course it doesn't exist as isbn on stock.quant but it's a Many2one to product so it should pass somehow.

Body:
This line:

result['domain'] = "[('isbn','in',[" + ','.join(map(str, isbn.ids)) + "])]"

should be:

result['domain'] = "[('product_id','in',[" + ','.join(map(str, isbn.ids)) + "])]"

No field isbn in stock.quant. Since isbn is object product.product, I think it's just the same with product_id of stock.quant