问:
Maven: set release and latest xml tags in the maven-metadata.xml when running mvn install
I am trying to figure out how install a dependency into my local .m2 directory and add the "latest" and "release" tags to the maven-metadata.xml file that is generated when the mvn install command is ran.

Example: below is what's currently happening. Running mvn install will put the dependency into my local .m2 directory but is does not generate the maven-metdata.xml with the "latest" or "release" tags with the specified version.

```<code><?xml version="1.0" encoding="UTF-8"?>
<metadata>
    <groupId>com.foo.bar</groupId>
    <artifactId>foo-bar</artifactId>
    <versioning>
        <versions>
            <version>0.0.0.20-SNAPSHOT</version>
        </versions>
    <lastUpdated>20171207212617</lastUpdated>
  </versioning>
</metadata>
</code>```

Example of what I would like to accomplish is below.

```<code><?xml version="1.0" encoding="UTF-8"?>
<metadata>
    <groupId>com.foo.bar</groupId>
    <artifactId>foo-bar</artifactId>
    <versioning>
        <latest>0.0.0.20-SNAPSHOT</latest>
        <release>0.0.0.20-SNAPSHOT</release>
        <versions>
             <version>0.0.0.20-SNAPSHOT</version>
        </versions>
        <lastUpdated>20171207212617</lastUpdated>
    </versioning>
</metadata>
</code>```

I want this so in the pom file that I plan on using this dependency I can specify the version as "RELEASE" or "LATEST" is maven will pull appropriate version, this way applications don't have to worry about explicitly defining the version in the pom.xml. I am using Maven v3.5.0.

Any help with this would be greatly appreciated. If more information is needed to do not hesitate to ask. Thank you in advance!

答:
Maven is not responsible for setting <latest> for anything but Maven Plugins. <latest> could be set for ordinary artifacts by repository manager. E.g. you can open Nexus, right click on a hosted repository and ask it to Rebuild Metadata.

<release> is usually not set by Maven as well. While it's possible to force Maven to set it via mvn install -DupdateReleaseInfo=true - this really is more for local testing of maven plugins.

Many people who start doing some CI or CD work think in terms of latest artifacts. This is a very common mistake. In general it's recommended to always use strict versions instead of ranges/LATEST/RELEASE/-SNAPSHOT which could resolve in one artifact today and in another artifact tomorrow. This makes your workflow less predictable and reproducible.

If you really want to rely on latest (which again is a bad idea), you can simply use 0.0.0.20-SNAPSHOT version or leverage ranged versions.

Body:
I am trying to figure out how install a dependency into my local .m2 directory and add the "latest" and "release" tags to the maven-metadata.xml file that is generated when the mvn install command is ran.

Example: below is what's currently happening. Running mvn install will put the dependency into my local .m2 directory but is does not generate the maven-metdata.xml with the "latest" or "release" tags with the specified version.

<?xml version="1.0" encoding="UTF-8"?>
<metadata>
    <groupId>com.foo.bar</groupId>
    <artifactId>foo-bar</artifactId>
    <versioning>
        <versions>
            <version>0.0.0.20-SNAPSHOT</version>
        </versions>
    <lastUpdated>20171207212617</lastUpdated>
  </versioning>
</metadata>

Example of what I would like to accomplish is below.

<?xml version="1.0" encoding="UTF-8"?>
<metadata>
    <groupId>com.foo.bar</groupId>
    <artifactId>foo-bar</artifactId>
    <versioning>
        <latest>0.0.0.20-SNAPSHOT</latest>
        <release>0.0.0.20-SNAPSHOT</release>
        <versions>
             <version>0.0.0.20-SNAPSHOT</version>
        </versions>
        <lastUpdated>20171207212617</lastUpdated>
    </versioning>
</metadata>

I want this so in the pom file that I plan on using this dependency I can specify the version as "RELEASE" or "LATEST" is maven will pull appropriate version, this way applications don't have to worry about explicitly defining the version in the pom.xml. I am using Maven v3.5.0.

Any help with this would be greatly appreciated. If more information is needed to do not hesitate to ask. Thank you in advance!


来源: stackexchange

问:
applying a rule once only child selector maybe?
```<code>#mainContent .container{
    background-image:url("/images/index_33.jpg");
    background-repeat:no-repeat;
    padding-left:85px;
    margin-top:10px;
}
</code>```

how can only apply those rules to the first div with a class container?

答:
To "apply those rules to the first div with a class container", you need to be a little more specific div.container, and then use the first-child pseudo class.

```<code>#mainContent div.container:first-child {
    background-image:url("/images/index_33.jpg");
    background-repeat:no-repeat;
    padding-left:85px;
    margin-top:10px;
}
</code>```

From w3scools.com:

The :first-child pseudo-class adds a style to an element that is the first child of another element.

ContentLicense: CC BY-SA 2.5

Body:
#mainContent .container{
    background-image:url("/images/index_33.jpg");
    background-repeat:no-repeat;
    padding-left:85px;
    margin-top:10px;
}

how can only apply those rules to the first div with a class container?

Body:
To "apply those rules to the first div with a class container", you need to be a little more specific div.container, and then use the first-child pseudo class.

#mainContent div.container:first-child {
    background-image:url("/images/index_33.jpg");
    background-repeat:no-repeat;
    padding-left:85px;
    margin-top:10px;
}

From w3scools.com:

The :first-child pseudo-class adds a style to an element that is the first child of another element.


问:
Override django change_form.html template when a third app is overriding it
I am trying to override change_form.html only for one model, so I did as explained in the django documentation and created /templates/my_app_name/my_model_name/change_form.html.

The problem is, it is not working and I am not seeing the extra features that I have added to the change_form template. I am using django_guardian, which also overrides the same template, so my assumption is that this is causing the issue. It is worth mentioning, that before placing the template in the my_app_name/my_model_name/ folder, the features of both templates were visible in the admin interface.

Is there a way to apply this only for 1 model?

答:
The GuardedModelAdmin changes change_form_template to use the template from django-guardian. Try changing it back in your model admin class:

```<code>class MyModelAdmin(GuardedModelAdmin):
    ...
    change_form_template = 'my_app_name/my_model_name/change_form.html'
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The GuardedModelAdmin changes change_form_template to use the template from django-guardian. Try changing it back in your model admin class:

class MyModelAdmin(GuardedModelAdmin):
    ...
    change_form_template = 'my_app_name/my_model_name/change_form.html'


问:
How do I Post user input from javascript to python?
I have an OpenLayers map of the world where a user can click on any country. I want to get the user's selected country sent to a python file where I can use it for more things.

This is the JavaScript portion of the map that deals with user selections.

```<code> if (select !== null) {
      map.addInteraction(select);
      select.on('select', function(e) {
        console.log(e);
        document.getElementById('status').innerHTML = ' ' +
        e.target.getFeatures().item(0).get('name');
        var name = e.target.getFeatures().item(0).get('name');
</code>```

I want to get the variable "name" sent to a python program which I have written where it will be used.

I'm struggling to understand how to do this. I think I need to use JavaScript Post. This is what I have been using but I'm not sure where to put it in my HTML. I'm reading about jquery and Ajax. Should I be using those?

```<code><form action="gresponse" method="post">
<input type="text" id="country" name="country"/>
<input type="submit" value="Go" name"gobtn"/></form>
</code>```

答: You could use the XMLHttpRequest of the Javascript standard library or if you already use jQuery you could use the jquery.ajax method.

Body:
I have an OpenLayers map of the world where a user can click on any country. I want to get the user's selected country sent to a python file where I can use it for more things.

This is the JavaScript portion of the map that deals with user selections.

 if (select !== null) {
      map.addInteraction(select);
      select.on('select', function(e) {
        console.log(e);
        document.getElementById('status').innerHTML = ' ' +
        e.target.getFeatures().item(0).get('name');
        var name = e.target.getFeatures().item(0).get('name');

I want to get the variable "name" sent to a python program which I have written where it will be used.

I'm struggling to understand how to do this. I think I need to use JavaScript Post. This is what I have been using but I'm not sure where to put it in my HTML. I'm reading about jquery and Ajax. Should I be using those?

<form action="gresponse" method="post">
<input type="text" id="country" name="country"/>
<input type="submit" value="Go" name"gobtn"/></form>


问:
MySQL Foreign Key Constraint Error (1215)
I'm trying to run a SQL script to generate my database for a project through MySQL workbench but every time I attempt, I keep getting a 1215 error saying that it cannot add the foreign key constraint.

The error was in reference to the relationship below where I'm attempting to have the id of the faculty entity as a foreign key for a grad_program under the director_id field.

```<code>-- -----------------------------------------------------
-- Table `jupitercollege`.`faculty`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `jupitercollege`.`faculty` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(45) NOT NULL,
  `dept` VARCHAR(10) NOT NULL,
  `email` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE INDEX `email_UNIQUE` (`email` ASC))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `jupitercollege`.`grad_program`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `jupitercollege`.`grad_program` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(45) NOT NULL,
  `dept` VARCHAR(10) NOT NULL,
  `phone` VARCHAR(12) NULL DEFAULT 'UNKNOWN',
  `email` VARCHAR(45) NULL DEFAULT 'UNKNOWN',
  `director_id` INT NOT NULL,
  PRIMARY KEY (`id`),
  INDEX `director_id_idx` (`director_id` ASC),
  UNIQUE INDEX `email_UNIQUE` (`email` ASC),
  UNIQUE INDEX `name_UNIQUE` (`name` ASC),
  CONSTRAINT `director_id`
    FOREIGN KEY (`director_id`)
    REFERENCES `jupitercollege`.`faculty` (`id`)
    ON DELETE SET NULL
    ON UPDATE NO ACTION)
ENGINE = InnoDB;
</code>```

I've seen a lot of posts about this error but none have really been directly applicable to my scenario, unless I misunderstood them. Any aid in rectifying the situation would be appreciated.

答:
Your child table has ON DELETE SET NULL. MySql 5.6 documentation states

If you specify a SET NULL action, make sure that you have not declared
  the columns in the child table as NOT NULL.

Your director_id column has a not null constraint. Remove that constraint or remove the ON DELETE clause.

https://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html

Body:
I'm trying to run a SQL script to generate my database for a project through MySQL workbench but every time I attempt, I keep getting a 1215 error saying that it cannot add the foreign key constraint.

The error was in reference to the relationship below where I'm attempting to have the id of the faculty entity as a foreign key for a grad_program under the director_id field.

-- -----------------------------------------------------
-- Table `jupitercollege`.`faculty`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `jupitercollege`.`faculty` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(45) NOT NULL,
  `dept` VARCHAR(10) NOT NULL,
  `email` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE INDEX `email_UNIQUE` (`email` ASC))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `jupitercollege`.`grad_program`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `jupitercollege`.`grad_program` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(45) NOT NULL,
  `dept` VARCHAR(10) NOT NULL,
  `phone` VARCHAR(12) NULL DEFAULT 'UNKNOWN',
  `email` VARCHAR(45) NULL DEFAULT 'UNKNOWN',
  `director_id` INT NOT NULL,
  PRIMARY KEY (`id`),
  INDEX `director_id_idx` (`director_id` ASC),
  UNIQUE INDEX `email_UNIQUE` (`email` ASC),
  UNIQUE INDEX `name_UNIQUE` (`name` ASC),
  CONSTRAINT `director_id`
    FOREIGN KEY (`director_id`)
    REFERENCES `jupitercollege`.`faculty` (`id`)
    ON DELETE SET NULL
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

I've seen a lot of posts about this error but none have really been directly applicable to my scenario, unless I misunderstood them. Any aid in rectifying the situation would be appreciated.


问:
SQL: Joins with an OR?
I'm trying to pull data from two tables, and I've been reading up on JOINs both here and on Google, but nothing seems to be working properly.

What I need is to pull from a customer table and a customertype table. Here's the customer table layout:

```<code>CustomerID: int PRIMARY KEY UNIQUE
Customername: varstring
Customeraddress: varstring
Customertype: int
Customerdescription: text
</code>```

Example:

```<code>CustomerID: 1
CustomernName: John Smith
Customeraddress: 1 Fake St., New York, New York, 11111
Customertype: 1
Customerdescription: Customer makes a monthly purchase of this and that.
</code>```

Here's the customertype layout:

```<code>TypeID: int PRIMARY KEY UNIQUE
Typetitle: varstring
Typedescription: text
</code>```

Example:

```<code>TypeID: 1
Typetitle: In good standing
Typedescription: These customers are in good standing and owe nothing.
</code>```

The Type field in the customer table obviously should correspond with the Type field in the customertype table. So, if I need to know all John Smith's data, I want, in one query:

```<code>CustomerID: 1
Customername: John Smith
Customeraddress: 1 Fake St. New York, New York, 11111
Typetitle: In good standing
Customerdescription: Customer makes a monthly purchase of this and that.
</code>```

The snag is, sometimes the Customertype is 0, which doesn't correspond to any record in the customertype table. Their type is undefined.

I've read about JOINs in various places, but I can't seem to make a query that will handle both where the CustomerID=the TypeID or where the CustomerID=0. Does anyone have any suggestions or know what the query would be?

答:
You can use an OR expression in your join clause. In your case, you will need to do a left join. Something like...

```<code>SELECT * FROM Customer LEFT JOIN Type ON Customer.Customertype = Type.TypeID OR Customer.Customertype = 0
</code>```

Title: SQL: Joins with an OR?

Body:
I'm trying to pull data from two tables, and I've been reading up on JOINs both here and on Google, but nothing seems to be working properly.

What I need is to pull from a customer table and a customertype table. Here's the customer table layout:

CustomerID: int PRIMARY KEY UNIQUE
Customername: varstring
Customeraddress: varstring
Customertype: int
Customerdescription: text

Example:

CustomerID: 1
CustomernName: John Smith
Customeraddress: 1 Fake St., New York, New York, 11111
Customertype: 1
Customerdescription: Customer makes a monthly purchase of this and that.

Here's the customertype layout:

TypeID: int PRIMARY KEY UNIQUE
Typetitle: varstring
Typedescription: text

Example:

TypeID: 1
Typetitle: In good standing
Typedescription: These customers are in good standing and owe nothing.

The Type field in the customer table obviously should correspond with the Type field in the customertype table. So, if I need to know all John Smith's data, I want, in one query:

CustomerID: 1
Customername: John Smith
Customeraddress: 1 Fake St. New York, New York, 11111
Typetitle: In good standing
Customerdescription: Customer makes a monthly purchase of this and that.

The snag is, sometimes the Customertype is 0, which doesn't correspond to any record in the customertype table. Their type is undefined.

I've read about JOINs in various places, but I can't seem to make a query that will handle both where the CustomerID=the TypeID or where the CustomerID=0. Does anyone have any suggestions or know what the query would be?

Body:
You can use an OR expression in your join clause. In your case, you will need to do a left join. Something like...

SELECT * FROM Customer LEFT JOIN Type ON Customer.Customertype = Type.TypeID OR Customer.Customertype = 0


问:
Pandas Resample on Date Columns
I have a dataframe with dates as columns. I'd like to average the values from daily to a monthly level. I've tried with Time Grouper and Resample, but it doesn't like the columns names are strings and I can seem to figure out how to make columns into something like a DatetimeIndex.

My starting dataframe:

```<code>import pandas as pd

df = pd.DataFrame(data=[[1,2,3,4],[5,6,7,8]],
                  columns=['2013-01-01', '2013-01-02', '2013-02-03', '2013-02-04'],
                  index=['A', 'B'])
</code>```

Desired Output:

```<code>   2013-01-01  2013-02-01
A         1.5         3.5
B         5.6         7.5
</code>```

答:
First, convert column index to datetime with pd.to_datetime, then use T and groupby with pd.Grouper (note pd.TimeGerouper is deprecated use pd.Grouper):

```<code>df.columns = pd.to_datetime(df.columns)
df.T.groupby(by=pd.Grouper(freq='MS')).mean().T
</code>```

Output:

```<code>   2013-01-01  2013-02-01
A         1.5         3.5
B         5.5         7.5
</code>```

Title: Pandas Resample on Date Columns

Body:
I have a dataframe with dates as columns. I'd like to average the values from daily to a monthly level. I've tried with Time Grouper and Resample, but it doesn't like the columns names are strings and I can seem to figure out how to make columns into something like a DatetimeIndex.

My starting dataframe:

import pandas as pd

df = pd.DataFrame(data=[[1,2,3,4],[5,6,7,8]],
                  columns=['2013-01-01', '2013-01-02', '2013-02-03', '2013-02-04'],
                  index=['A', 'B'])

Desired Output:

   2013-01-01  2013-02-01
A         1.5         3.5
B         5.6         7.5

Body:
First, convert column index to datetime with pd.to_datetime, then use T and groupby with pd.Grouper (note pd.TimeGerouper is deprecated use pd.Grouper):

df.columns = pd.to_datetime(df.columns)
df.T.groupby(by=pd.Grouper(freq='MS')).mean().T

Output:

   2013-01-01  2013-02-01
A         1.5         3.5
B         5.5         7.5


问:
my android studio wont rebuild . Unable to start the daemon process
Error:Unable to start the daemon process.
This problem might be caused by incorrect configuration of the daemon.
For example, an unrecognized jvm option is used.
Please refer to the user guide chapter on the daemon at https://docs.gradle.org/2.14.1/userguide/gradle_daemon.html

Please read the following process output to find out more:

OpenJDK 64-Bit Server VM warning: ignoring option MaxPermSize=256m; support was removed in 8.0

答: if you are using windows, try killing the java processes with task manager and doing a "Revalidate caches and restart" on android studio</p>


问:
Is it recommended practice to include extension method within the static class itself?
I have:

```<code>public static class DataManager
{
    private static Dictionary<string, DataTable> dataTables;

    //    extension method
    public static DataTable GetTable ( this string TableName )
    {
        return dataTables[ TableName ];
    }

}
</code>```

I didn't want to expose the Dictionary collection, and this is the way I thought to accomplish this task. In my calling method:

```<code>DataTable GetTable (string TableName)
{
    return TableName.GetTable();
}
</code>```

Is there another way I should, or could do this? Or is this acceptable?

答: I don't think that this is a good idea because, your method does not operate on a string (what the extension method would state), it operates on DataManager. So just use a static method in this case.

Body:
I have:

public static class DataManager
{
    private static Dictionary<string, DataTable> dataTables;

    //    extension method
    public static DataTable GetTable ( this string TableName )
    {
        return dataTables[ TableName ];
    }

}

I didn't want to expose the Dictionary collection, and this is the way I thought to accomplish this task. In my calling method:

DataTable GetTable (string TableName)
{
    return TableName.GetTable();
}

Is there another way I should, or could do this? Or is this acceptable?


问:
How to use C++ Builder OPENARRAY in a custom function
I would like to use OPENARRAY (or an alternative, if you have one) to pass multiple placeholder variables into my function. I know that it can be used for String::Format in this way:

```<code>UnicodeString Text1 = "abc";
int Num2 = 1;
String::Format("Some %s and %d", OPENARRAY(TVarRec, (Text1, Num2));
</code>```

What I would like is to use Text1 and Text2 variables in something like this:

```<code>MyFunction("Some %Txt1 and %Num2", OPENARRAY(TVarRec, ("%Txt1", Text1, "%Num2", Num2));
</code>```

Or perhaps:

```<code>MyFunction(OPENARRAY(TVarRec, ("Some %Txt1 and %Num2", "%Txt1", Text1, "%Num2", Num2));
</code>```

So it would accept the text and replace the placeholder variables with appropriate variable content.

What I don't know is how do I read OPENARRAY parameter content from MyFunction.

So the function would look like:

```<code>UnicodeString MyFunction(UnicodeString Txt, ?WHAT-HERE?)
{
// read openarray here and replace vars
return StringReplace(Txt, ?WHAT-HERE?);
}
</code>```

So I don't know how do I accept the OPENARRAY variables. Also, if you have an alternative solution to passing placeholder, variable in similar manner (without the use of C++11), that would also be welcome.

答:
When passing a Delphi-style Open Array to a function, two things are actually passed:

a pointer to the first element of the array

the index of the last element of the array (NOT the length of the array, as you might expect!).

So, in your example, you can declare your function like this:

```<code>UnicodeString MyFunction(UnicodeString Txt, const TVarRec *Values, const int Values_High)
</code>```

And then loop through the array using normal pointer arithmetic.

TVarRec can hold many different data types, so you have to look at its VType field to know what kind of data it is actually referencing, and then access the appropriate data field.  Some values (integers and single characters) are stored directly in the TVarRec itself, while others (strings and other class types) are referenced by pointer instead.

For example:

```<code>UnicodeString MyFunction(UnicodeString Txt, const TVarRec *Values, const int Values_High)
{
    if (((Values_High + 1) % 2) != 0)
        throw Exception("uneven number of values!");

    for (int index = 0; index <= Values_High; index += 2)
    {
        String OldValue, NewValue;

        switch (Values[index].VType)
        {
            case vtString:
                OldValue = * static_cast<const ShortString*>(Values[index].VString);
                break;

            case vtPChar:
                OldValue = Values[index].VPChar;
                break;

            case vtPWideChar:
                OldValue = Values[index].VPWideChar;
                break;

            case vtAnsiString:
                OldValue = * static_cast<const AnsiString*>(Values[index].VAnsiString);
                break;

            case vtWideString:
                OldValue = * static_cast<const WideString*>(Values[index].VWideString);
                break;

            case vtUnicodeString:
                OldValue = * static_cast<const UnicodeString*>(Values[index].VUnicodeString);
                break;

            default:
                throw Exception("illegal value type at index %d!", ARRAYOFCONST(( index )) );
        }

        switch (Values[index+1].VType)
        {
            case vtInteger:
                NewValue = Values[index+1].VInteger;
                break;

            case vtBoolean:
                NewValue = Values[index+1].VBoolean;
                break;

            case vtChar:
                NewValue = Values[index+1].VChar;
                break;

            case vtExtended:
                NewValue = * static_cast<const Extended*>(Values[index+1].VExtended);
                break;

            case vtString:
                NewValue = * static_cast<const ShortString*>(Values[index+1].VString);
                break;

            case vtPChar:
                NewValue = Values[index+1].VPChar;
                break;

            case vtWideChar:
                NewValue = Values[index+1].VWideChar;
                break;

            case vtPWideChar:
                NewValue = Values[index+1].VPWideChar;
                break;

            case vtAnsiString:
                NewValue = * static_cast<const AnsiString*>(Values[index+1].VAnsiString);
                break;

            case vtCurrency:
                NewValue = * static_cast<const Currency*>(Values[index+1].VCurrency);
                break;

            case vtVariant:
                NewValue = * static_cast<const Variant*>(Values[index+1].VVariant);
                break;

            case vtWideString:
                NewValue = * static_cast<const WideString*>(Values[index+1].VWideString);
                break;

            case vtInt64:
                NewValue = * static_cast<const __int64*>(Values[index+1].VInt64);
                break;

            case vtUnicodeString:
                NewValue = * static_cast<const UnicodeString*>(Values[index+1].VUnicodeString);
                break;

            default:
                throw Exception("illegal value type at index %d!", ARRAYOFCONST(( index )) );
        }

        Txt = StringReplace(Txt, OldValue, NewValue, TReplaceFlags() << rfReplaceAll);
    }

    return Txt;
}
</code>```

```<code>MyFunction("Some %Txt1 and %Num2", OPENARRAY(TVarRec, ("%Txt1", Text1, "%Num2", Num2)) );
</code>```

On a side note, when a function takes an open array of TVarRec values, you should use the ARRAYOFCONST() macro instead of the OPENARRAY() macro directly, eg:

```<code>String::Format("Some %s and %d", ARRAYOFCONST(( Text1, Num2 )) );
</code>```

```<code>MyFunction("Some %Txt1 and %Num2", ARRAYOFCONST(( "%Txt1", Text1, "%Num2", Num2 )) );
</code>```

Body:
I would like to use OPENARRAY (or an alternative, if you have one) to pass multiple placeholder variables into my function. I know that it can be used for String::Format in this way:

UnicodeString Text1 = "abc";
int Num2 = 1;
String::Format("Some %s and %d", OPENARRAY(TVarRec, (Text1, Num2));

What I would like is to use Text1 and Text2 variables in something like this:

MyFunction("Some %Txt1 and %Num2", OPENARRAY(TVarRec, ("%Txt1", Text1, "%Num2", Num2));

Or perhaps:

MyFunction(OPENARRAY(TVarRec, ("Some %Txt1 and %Num2", "%Txt1", Text1, "%Num2", Num2));

So it would accept the text and replace the placeholder variables with appropriate variable content.

What I don't know is how do I read OPENARRAY parameter content from MyFunction.

So the function would look like:

UnicodeString MyFunction(UnicodeString Txt, ?WHAT-HERE?)
{
// read openarray here and replace vars
return StringReplace(Txt, ?WHAT-HERE?);
}

So I don't know how do I accept the OPENARRAY variables. Also, if you have an alternative solution to passing placeholder, variable in similar manner (without the use of C++11), that would also be welcome.

Body:
When passing a Delphi-style Open Array to a function, two things are actually passed:

a pointer to the first element of the array

the index of the last element of the array (NOT the length of the array, as you might expect!).

So, in your example, you can declare your function like this:

UnicodeString MyFunction(UnicodeString Txt, const TVarRec *Values, const int Values_High)

And then loop through the array using normal pointer arithmetic.

TVarRec can hold many different data types, so you have to look at its VType field to know what kind of data it is actually referencing, and then access the appropriate data field.  Some values (integers and single characters) are stored directly in the TVarRec itself, while others (strings and other class types) are referenced by pointer instead.

For example:

UnicodeString MyFunction(UnicodeString Txt, const TVarRec *Values, const int Values_High)
{
    if (((Values_High + 1) % 2) != 0)
        throw Exception("uneven number of values!");

    for (int index = 0; index <= Values_High; index += 2)
    {
        String OldValue, NewValue;

        switch (Values[index].VType)
        {
            case vtString:
                OldValue = * static_cast<const ShortString*>(Values[index].VString);
                break;

            case vtPChar:
                OldValue = Values[index].VPChar;
                break;

            case vtPWideChar:
                OldValue = Values[index].VPWideChar;
                break;

            case vtAnsiString:
                OldValue = * static_cast<const AnsiString*>(Values[index].VAnsiString);
                break;

            case vtWideString:
                OldValue = * static_cast<const WideString*>(Values[index].VWideString);
                break;

            case vtUnicodeString:
                OldValue = * static_cast<const UnicodeString*>(Values[index].VUnicodeString);
                break;

            default:
                throw Exception("illegal value type at index %d!", ARRAYOFCONST(( index )) );
        }

        switch (Values[index+1].VType)
        {
            case vtInteger:
                NewValue = Values[index+1].VInteger;
                break;

            case vtBoolean:
                NewValue = Values[index+1].VBoolean;
                break;

            case vtChar:
                NewValue = Values[index+1].VChar;
                break;

            case vtExtended:
                NewValue = * static_cast<const Extended*>(Values[index+1].VExtended);
                break;

            case vtString:
                NewValue = * static_cast<const ShortString*>(Values[index+1].VString);
                break;

            case vtPChar:
                NewValue = Values[index+1].VPChar;
                break;

            case vtWideChar:
                NewValue = Values[index+1].VWideChar;
                break;

            case vtPWideChar:
                NewValue = Values[index+1].VPWideChar;
                break;

            case vtAnsiString:
                NewValue = * static_cast<const AnsiString*>(Values[index+1].VAnsiString);
                break;

            case vtCurrency:
                NewValue = * static_cast<const Currency*>(Values[index+1].VCurrency);
                break;

            case vtVariant:
                NewValue = * static_cast<const Variant*>(Values[index+1].VVariant);
                break;

            case vtWideString:
                NewValue = * static_cast<const WideString*>(Values[index+1].VWideString);
                break;

            case vtInt64:
                NewValue = * static_cast<const __int64*>(Values[index+1].VInt64);
                break;

            case vtUnicodeString:
                NewValue = * static_cast<const UnicodeString*>(Values[index+1].VUnicodeString);
                break;

            default:
                throw Exception("illegal value type at index %d!", ARRAYOFCONST(( index )) );
        }

        Txt = StringReplace(Txt, OldValue, NewValue, TReplaceFlags() << rfReplaceAll);
    }

    return Txt;
}

MyFunction("Some %Txt1 and %Num2", OPENARRAY(TVarRec, ("%Txt1", Text1, "%Num2", Num2)) );

On a side note, when a function takes an open array of TVarRec values, you should use the ARRAYOFCONST() macro instead of the OPENARRAY() macro directly, eg:

String::Format("Some %s and %d", ARRAYOFCONST(( Text1, Num2 )) );

MyFunction("Some %Txt1 and %Num2", ARRAYOFCONST(( "%Txt1", Text1, "%Num2", Num2 )) );


答:
you can make use of pd.PeriodIndex:</p>

```<code>In [145]: df.groupby(pd.PeriodIndex(df.columns, freq='M'), axis=1).mean()
Out[145]:
   2013-01  2013-02
A      1.5      3.5
B      5.5      7.5
</code>```

Title: Pandas Resample on Date Columns

Body:
you can make use of pd.PeriodIndex:

In [145]: df.groupby(pd.PeriodIndex(df.columns, freq='M'), axis=1).mean()
Out[145]:
   2013-01  2013-02
A      1.5      3.5
B      5.5      7.5


问:
How to fix warning that function 'node_form' is not found?
I am writing a drupal module.
In my module i have the following:

In my .module file I have:

```<code>function mymodule_managment_menu(){
$items = array();
$items['management/edit'] = array(
    'title' => 'Add Node',
    'page callback' => 'display_add',
    'access callback' => 'user_access',
    'file' => 'file.inc',
  );
  return $items;
}
</code>```

in my file.inc i have:

```<code>function uc_am_display_edit()
{
  global $user;
  $node = array('uid' => $user->uid, 'name' => (isset($user->name) ? $user->name : ''), 'type' => 'track', 'language' => '');
  $output = drupal_get_form('track_node_form', $node);
  return $output;
}
</code>```

when i go to http://myhost/management/edit i get the following warnning message:

warning: call_user_func_array()
  expects parameter 1 to be a valid
  callback, function 'node_form' not
  found or invalid function name in
  /var/www/includes/form.inc on line
  378.

when debugging i get to form.inc:378 which is:

```<code>  $form = call_user_func_array(isset($callback) ? $callback : $form_id, $args);
</code>```

where my $callback = 'node_form'.
but still it is not defined.
of course, when i go to http://myhost/node/add/track i get the properly designed form i want.
when i debug it, i go throw thte same path of code, with the same variables value, and node_form is declared.
so my guess here is that my module is loaded before the node module, but just writing that makes doubt it, since the node module is a core module.
tried to increase my module weight value to 11 - didnt help.
please help...

答: The function node_form is defined in modules/node/node.pages.inc. That file is not loaded by default. You have to load it manually using module_load_include in your page callback.</p>

Body:
I am writing a drupal module.
In my module i have the following:

In my .module file I have:

function mymodule_managment_menu(){
$items = array();
$items['management/edit'] = array(
    'title' => 'Add Node',
    'page callback' => 'display_add',
    'access callback' => 'user_access',
    'file' => 'file.inc',
  );
  return $items;
}

in my file.inc i have:

function uc_am_display_edit()
{
  global $user;
  $node = array('uid' => $user->uid, 'name' => (isset($user->name) ? $user->name : ''), 'type' => 'track', 'language' => '');
  $output = drupal_get_form('track_node_form', $node);
  return $output;
}

when i go to http://myhost/management/edit i get the following warnning message:

warning: call_user_func_array()
  expects parameter 1 to be a valid
  callback, function 'node_form' not
  found or invalid function name in
  /var/www/includes/form.inc on line
  378.

when debugging i get to form.inc:378 which is:

  $form = call_user_func_array(isset($callback) ? $callback : $form_id, $args);

where my $callback = 'node_form'.
but still it is not defined.
of course, when i go to http://myhost/node/add/track i get the properly designed form i want.
when i debug it, i go throw thte same path of code, with the same variables value, and node_form is declared.
so my guess here is that my module is loaded before the node module, but just writing that makes doubt it, since the node module is a core module.
tried to increase my module weight value to 11 - didnt help.
please help...


问:
Nested conditional throwing an error
I have a column of integers from three digits to five digits.  I want to output a column of six characters (czCode) with the appropriate number of leading zeros depending on the input integer.

```<code>a <- seq(100, 50000, 1)
df1 <- data.frame(a)
View(df1)

myZero <- '0'
dblZero <- '00'
triZero <- '000'

a <- mutate(a, czCode = as.character(a))

df1$a <- ifelse(df1$a < 1000, paste(triZero, df1$czCode, sep = ""),
                ifelse(df1$a >= 1000 & df1$a < 10000, paste(dblZero, df1$czCode, sep = ""),
                ifelse(df1$a >= 10000, paste(myZero, df1$a, sep = "")),
                ))
</code>```

So 100 would output as "000100"

and 1000 would output as "001000"

and 10000 would output as "010000"

But I keep getting the following error:

Error in ifelse(df1$a >= 1000 & df1$a < 10000, paste(dblZero, df1$czCode,  :

      unused argument ()

答:
While suchait explained the reason for the encountered error message, there is a better way to convert a number to character with leading zeros:

```<code>sprintf("%06i", 10^(2:4))
</code>```

```<code>[1] "000100" "001000" "010000"
</code>```

The conversion specification %06i tells sprintf() to convert integer and "integerish" values using a field width of 6 characters and to pad to field width with leading zeros.

By the way, paste0(x, y) is a short-cut for paste(x, y, sep = "").

Title: Nested conditional throwing an error

Body:
I have a column of integers from three digits to five digits.  I want to output a column of six characters (czCode) with the appropriate number of leading zeros depending on the input integer.

a <- seq(100, 50000, 1)
df1 <- data.frame(a)
View(df1)

myZero <- '0'
dblZero <- '00'
triZero <- '000'

a <- mutate(a, czCode = as.character(a))

df1$a <- ifelse(df1$a < 1000, paste(triZero, df1$czCode, sep = ""),
                ifelse(df1$a >= 1000 & df1$a < 10000, paste(dblZero, df1$czCode, sep = ""),
                ifelse(df1$a >= 10000, paste(myZero, df1$a, sep = "")),
                ))

So 100 would output as "000100"

and 1000 would output as "001000"

and 10000 would output as "010000"

But I keep getting the following error:

Error in ifelse(df1$a >= 1000 & df1$a < 10000, paste(dblZero, df1$czCode,  :

      unused argument ()

Body:
While suchait explained the reason for the encountered error message, there is a better way to convert a number to character with leading zeros:

sprintf("%06i", 10^(2:4))

[1] "000100" "001000" "010000"

The conversion specification %06i tells sprintf() to convert integer and "integerish" values using a field width of 6 characters and to pad to field width with leading zeros.

By the way, paste0(x, y) is a short-cut for paste(x, y, sep = "").


问:
Make categories from string in XML data
I looked everywhere but I don't see anything specific to the thing I am trying to achieve, especially with iOS/swift. I would like to make age categories from the XML parser request I am calling in my app.

The age information will have to be called from the  tag in the xml data:

```<code><item>
<description>ANTHONY JOHNSON, Age: 17 From: PEORIA, IL</description></item>
</code>```

I already have a call to get the description tag in full:

```<code>func parser(_ parser: XMLParser, didEndElement elementName: String,
 namespaceURI: String?, qualifiedName qName: String?) {

 if elementName == "description" {
        self.person.desc = self.foundCharacters; }

     if elementName == "item" {
tempData.desc = self.person.desc; }
</code>```

Item class:

```<code> class Item {
  var desc = "";
}
</code>```

I just need to make categories from the age value only. I plan on using them with an enum:

```<code>enum ageCategories: String {

    case ageUnder10 = "Age 10 and under"
    case age10Plus = "Age 10-15"
    case age15Plus = "Age 15+"
}
</code>```

My questions are:

Do I make a call in the XML parser to get the ages? How would I organize the call to get the ages part of the description string only and put them in categories?

OR

Is there an easier way to call just the ages from the string I have already called in the XML parser and then make categories with that? i.e: replacingOccurrences(range searchRange:"Age")

答:
Your question boils down to finding an age in the description string. The following shows one solution using Scanner. This code assumes that the age will be a number after the text "Age:".

```<code>let desc = "ANTHONY JOHNSON, Age: 17 From: PEORIA, IL"
var ageRange: ageCategories? = nil

let scanner = Scanner(string: desc)
if scanner.scanUpTo("Age:", into: nil) && scanner.scanString("Age:", into: nil) {
    var age = 0
    if scanner.scanInt(&age) {
        switch age {
        case 0..<10:
            ageRange = .AgeUnder10
        case 10..<15:
            ageRange = .Age10Plus
        case 15...:
            ageRange = .Age15Plus
        default:
            break
        }
    }
}

if let ageRange = ageRange {
    print("Found age range of \(ageRange)")
} else {
    print("No valid age found")
}
</code>```

Adjust the ranges in the case statements to match your actual needs. The strings you are assigning to your enum values are ambiguous. Is 10 supposed to be .AgeUnder10 or .Age10Plus?

FYI - enum values should start with lowercase letters and the enum name should start with uppercase. So your enum should be:

```<code>enum AgeCategories: String {
    case ageUnder10 = "Age under 10"
    case age10Plus = "Age 10-14"
    case age15Plus = "Age 15+"
}
</code>```

Title: Make categories from string in XML data

Body:
I looked everywhere but I don't see anything specific to the thing I am trying to achieve, especially with iOS/swift. I would like to make age categories from the XML parser request I am calling in my app.

The age information will have to be called from the  tag in the xml data:

<item>
<description>ANTHONY JOHNSON, Age: 17 From: PEORIA, IL</description></item>

I already have a call to get the description tag in full:

func parser(_ parser: XMLParser, didEndElement elementName: String,
 namespaceURI: String?, qualifiedName qName: String?) {

 if elementName == "description" {
        self.person.desc = self.foundCharacters; }

     if elementName == "item" {
tempData.desc = self.person.desc; }

Item class:

 class Item {
  var desc = "";
}

I just need to make categories from the age value only. I plan on using them with an enum:

enum ageCategories: String {

    case ageUnder10 = "Age 10 and under"
    case age10Plus = "Age 10-15"
    case age15Plus = "Age 15+"
}

My questions are:

Do I make a call in the XML parser to get the ages? How would I organize the call to get the ages part of the description string only and put them in categories?

OR

Is there an easier way to call just the ages from the string I have already called in the XML parser and then make categories with that? i.e: replacingOccurrences(range searchRange:"Age")

Body:
Your question boils down to finding an age in the description string. The following shows one solution using Scanner. This code assumes that the age will be a number after the text "Age:".

let desc = "ANTHONY JOHNSON, Age: 17 From: PEORIA, IL"
var ageRange: ageCategories? = nil

let scanner = Scanner(string: desc)
if scanner.scanUpTo("Age:", into: nil) && scanner.scanString("Age:", into: nil) {
    var age = 0
    if scanner.scanInt(&age) {
        switch age {
        case 0..<10:
            ageRange = .AgeUnder10
        case 10..<15:
            ageRange = .Age10Plus
        case 15...:
            ageRange = .Age15Plus
        default:
            break
        }
    }
}

if let ageRange = ageRange {
    print("Found age range of \(ageRange)")
} else {
    print("No valid age found")
}

Adjust the ranges in the case statements to match your actual needs. The strings you are assigning to your enum values are ambiguous. Is 10 supposed to be .AgeUnder10 or .Age10Plus?

FYI - enum values should start with lowercase letters and the enum name should start with uppercase. So your enum should be:

enum AgeCategories: String {
    case ageUnder10 = "Age under 10"
    case age10Plus = "Age 10-14"
    case age15Plus = "Age 15+"
}


问:
Difference between inheritance and creating new class
What is the difference between these two:

```<code>class Machine {
    public int x = 2;
}

class Car {
    public void start(Machine myMachine) {
         myMachine.x = 10;
    }
}
</code>```

And:

```<code>class Machine {
    public int x = 2;
}

class Car extends Machine {
    public void start() {
        super.x = 10;
    }
}
</code>```

In the first example, I'm creating a new kind of object with the Car class, and I can use variable x from the Machine class.

In the second example I'm inheriting from the Machine class to the Car class, so I can use variables from Machine in Car.

But I don't know when should I use first the one instead of the second one, which is better, and so on.

Could someone explain the difference?

答:
Use inheritance when one class needs to be a type of some other class because they share some properties. So in this case a Car might be a type of Machine and perhaps define or extend variables or functions that are in Machine.

If a class only needed to access or use a Machine object (its variables or functions) it would be better to use your first example. Perhaps if you wanted a MachineManager or MachineList class for example.

ContentLicense: CC BY-SA 4.0

Body:
What is the difference between these two:

class Machine {
    public int x = 2;
}

class Car {
    public void start(Machine myMachine) {
         myMachine.x = 10;
    }
}

And:

class Machine {
    public int x = 2;
}

class Car extends Machine {
    public void start() {
        super.x = 10;
    }
}

In the first example, I'm creating a new kind of object with the Car class, and I can use variable x from the Machine class.

In the second example I'm inheriting from the Machine class to the Car class, so I can use variables from Machine in Car.

But I don't know when should I use first the one instead of the second one, which is better, and so on.

Could someone explain the difference?


答:
The first is sometimes called a 'Uses a' relationship, as in 'the car uses a machine', while the second is sometimes called an 'is-a' relationship, as in 'the car is a machine'. This second relationship is called inheritance.. There is a third broad type, the 'has-a' relationship that you've not shown here:

```<code>class Machine {}
class Car {
    Machine machine;
}
</code>```

The first relationship is a lot easier to understand than the second. Typically we only model the second if we want to substitute one sub-class (Car in your example) with another derived from the same parent (Machine).

Title: Difference between inheritance and creating new class

Body:
The first is sometimes called a 'Uses a' relationship, as in 'the car uses a machine', while the second is sometimes called an 'is-a' relationship, as in 'the car is a machine'. This second relationship is called inheritance.. There is a third broad type, the 'has-a' relationship that you've not shown here:

class Machine {}
class Car {
    Machine machine;
}

The first relationship is a lot easier to understand than the second. Typically we only model the second if we want to substitute one sub-class (Car in your example) with another derived from the same parent (Machine).


问:
Partial update on an postgres upsert violates constraint
I want to be able to upsert partially inside postgres (9.5), but it seems that a partial upsert fails when not all of the constraint is fulfilled (such as the not null constraint)

Here is an example of the scenario and error

```<code>CREATE TABLE jobs (
    id integer PRIMARY KEY,
    employee_name TEXT NOT NULL,
    address TEXT NOT NULL,
    phone_number TEXT
);

CREATE OR REPLACE FUNCTION upsert_job(job JSONB)
RETURNS VOID AS $$
BEGIN
INSERT INTO jobs AS origin VALUES(
    (job->>'id')::INTEGER,
    job->>'employee_name'::TEXT,
    job->>'address'::TEXT,
    job->>'phone_number'::TEXT
) ON CONFLICT (id) DO UPDATE SET
    employee_name = COALESCE(EXCLUDED.employee_name, origin.employee_name),
    address = COALESCE(EXCLUDED.address, origin.address),
    phone_number = COALESCE(EXCLUDED.phone_number, origin.phone_number);
END;
$$ LANGUAGE PLPGSQL SECURITY DEFINER;

--Full insert (OK)
SELECT upsert_job('{"id" : 1, "employee_name" : "AAA", "address" : "City, x street no.y", "phone_number" : "123456789"}'::jsonb);

--Partial update that fulfills constraint (Ok)
SELECT upsert_job('{"id" : 1,  "employee_name" : "BBB", "address" : "City, x street no.y"}'::jsonb);

--Partial update that doesn't fulfill constraint (FAILS)
SELECT upsert_job('{"id" : 1,  "phone_number" : "12345"}'::jsonb);

--ERROR:  null value in column "employee_name" violates not-null constraint
--DETAIL:  Failing row contains (1, null, null, 12345).
</code>```

How do I go around approaching this ?

答:
To think of it another way, what if the id didn't already exist?  You can't insert just a phone number as it would have no name/address but that's exactly what you are telling it to do.  So the constraint gets mad and it fails because an upsert tries to insert first and then updates if the insert fails.  But your insert didn't get past the constraint check to see if it already existed.

What you can do instead if you want partials is tell it how to handle partials that would violate the constraints.  Something like this (this is NOT complete and doesn't handle all partial data scenarios):

```<code>CREATE OR REPLACE FUNCTION upsert_job(job JSONB)
RETURNS VOID AS $$
BEGIN
IF (job->>'phone_number' IS NOT NULL
    AND job->>'employee_name' IS NOT NULL
    AND job->>'address' IS NOT NULL) THEN
    INSERT INTO jobs AS origin VALUES(
        (job->>'id')::INTEGER,
        job->>'employee_name'::TEXT,
        job->>'address'::TEXT,
        job->>'phone_number'::TEXT
    ) ON CONFLICT (id) DO UPDATE SET
        employee_name = COALESCE(EXCLUDED.employee_name, origin.employee_name),
        address = COALESCE(EXCLUDED.address, origin.address),
        phone_number = COALESCE(EXCLUDED.phone_number, origin.phone_number);
ELSIF (job->>'phone_number' IS NOT NULL AND (job->>'employee_name' IS NULL AND job->>'address' IS NULL)) THEN
    UPDATE jobs SET phone_number=job->>'phone_number'::TEXT
    WHERE id=(job->>'id')::INTEGER;
END IF;

END;
$$ LANGUAGE PLPGSQL SECURITY DEFINER;
</code>```

Body:
I want to be able to upsert partially inside postgres (9.5), but it seems that a partial upsert fails when not all of the constraint is fulfilled (such as the not null constraint)

Here is an example of the scenario and error

CREATE TABLE jobs (
    id integer PRIMARY KEY,
    employee_name TEXT NOT NULL,
    address TEXT NOT NULL,
    phone_number TEXT
);

CREATE OR REPLACE FUNCTION upsert_job(job JSONB)
RETURNS VOID AS $$
BEGIN
INSERT INTO jobs AS origin VALUES(
    (job->>'id')::INTEGER,
    job->>'employee_name'::TEXT,
    job->>'address'::TEXT,
    job->>'phone_number'::TEXT
) ON CONFLICT (id) DO UPDATE SET
    employee_name = COALESCE(EXCLUDED.employee_name, origin.employee_name),
    address = COALESCE(EXCLUDED.address, origin.address),
    phone_number = COALESCE(EXCLUDED.phone_number, origin.phone_number);
END;
$$ LANGUAGE PLPGSQL SECURITY DEFINER;

--Full insert (OK)
SELECT upsert_job('{"id" : 1, "employee_name" : "AAA", "address" : "City, x street no.y", "phone_number" : "123456789"}'::jsonb);

--Partial update that fulfills constraint (Ok)
SELECT upsert_job('{"id" : 1,  "employee_name" : "BBB", "address" : "City, x street no.y"}'::jsonb);

--Partial update that doesn't fulfill constraint (FAILS)
SELECT upsert_job('{"id" : 1,  "phone_number" : "12345"}'::jsonb);

--ERROR:  null value in column "employee_name" violates not-null constraint
--DETAIL:  Failing row contains (1, null, null, 12345).

How do I go around approaching this ?

Body:
To think of it another way, what if the id didn't already exist?  You can't insert just a phone number as it would have no name/address but that's exactly what you are telling it to do.  So the constraint gets mad and it fails because an upsert tries to insert first and then updates if the insert fails.  But your insert didn't get past the constraint check to see if it already existed.

What you can do instead if you want partials is tell it how to handle partials that would violate the constraints.  Something like this (this is NOT complete and doesn't handle all partial data scenarios):

CREATE OR REPLACE FUNCTION upsert_job(job JSONB)
RETURNS VOID AS $$
BEGIN
IF (job->>'phone_number' IS NOT NULL
    AND job->>'employee_name' IS NOT NULL
    AND job->>'address' IS NOT NULL) THEN
    INSERT INTO jobs AS origin VALUES(
        (job->>'id')::INTEGER,
        job->>'employee_name'::TEXT,
        job->>'address'::TEXT,
        job->>'phone_number'::TEXT
    ) ON CONFLICT (id) DO UPDATE SET
        employee_name = COALESCE(EXCLUDED.employee_name, origin.employee_name),
        address = COALESCE(EXCLUDED.address, origin.address),
        phone_number = COALESCE(EXCLUDED.phone_number, origin.phone_number);
ELSIF (job->>'phone_number' IS NOT NULL AND (job->>'employee_name' IS NULL AND job->>'address' IS NULL)) THEN
    UPDATE jobs SET phone_number=job->>'phone_number'::TEXT
    WHERE id=(job->>'id')::INTEGER;
END IF;

END;
$$ LANGUAGE PLPGSQL SECURITY DEFINER;


问:
How to create a XFS-formatted disk/folder
I am playing around with ScyllaDB in docker. To have ScyllaDB operate most efficient in docker production setup it needs a XFS-formatted disk.

Do you know how to create a XFS container volumes, file of disk - in Linux and MacOs?

Thanks

答:
The best way to do that is to create a partition or LVM volume, and then format it with xfs normally, using some tool like mkfs.xfs.

Once you are done, you can use the -v flag in docker to pass that to your container.


问:
Unable to purchase IAP as sandbox user
I am having a problem trying to purchase an IAP as a sandbox user. It's not the sandbox account that's the problem. It's the fact that my var products = [SKProduct]() array in IAPService.swift is empty.

Inside my StoreViewController.swift (which also stores my Game Center leaderboards):

```<code>class StoreViewController: UIViewController, GKGameCenterControllerDelegate {

    @IBAction func purchase(_ sender: UIButton) {
        IAPService.shared.purchase(product: .nonConsumable)
    }

    ...

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        IAPService.shared.getProducts()

        print(IAPService.shared.products) // This is an empty array?

        authenticateLocalPlayer() // Related to Game Center
    }
}
</code>```

Inside my IAPProducts.swift

```<code>enum IAPProducts: String {
    case nonConsumable = "com.nameofgame.nameofproduct"
}
</code>```

Inside my IAPService.swift

```<code>import Foundation
import StoreKit

class IAPService: NSObject {

    private override init() {}
    static let shared = IAPService()

    var products = [SKProduct]()
    let paymentQueue = SKPaymentQueue.default()

    func getProducts() {
        let products: Set = [IAPProducts.nonConsumable.rawValue,
                             ]

        let request = SKProductsRequest(productIdentifiers: products)
        request.delegate = self
        request.start()
        paymentQueue.add(self)
    }

    func purchase(product: IAPProducts) {
        guard let productToPurchase = products.filter({ $0.productIdentifier == product.rawValue }).first else { return }

        let payment = SKPayment(product: productToPurchase)
        paymentQueue.add(payment)
    }
}

extension IAPService: SKProductsRequestDelegate {
    func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
        products = response.products
    }
}

extension IAPService: SKPaymentTransactionObserver {
    func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        for transaction in transactions {

            switch transaction.transactionState {
            case .purchased:

                if transaction.payment.productIdentifier == IAPProducts.nonConsumable.rawValue {
                    print("IAP Purchased")
                }
                break

            case .failed:
                SKPaymentQueue.default().finishTransaction(transaction)
                print(transaction.error!)
                break

            default: break
            }
        }
    }
}
</code>```

Things I've done several things to try and solve the problem:

Changed the Set in IAPService to an NSSet. This doesn't work because the set of Strings in let request = SKProductsRequest(productIdentifiers: products) cannot be converted to an NSSet.

Checked multiple times that my BundleIDs match on Xcode and iTunes Connect. I've also done this check with the Product IDs to make sure there's a match between the IAP ID in iTunes Connect and the IAPProducts enum.

I added this IAP on iTunes Connect 3 days ago, and I've checked that all my contracts for paid apps are in effect.

Please help me with this issue. Thanks.

答:
From the SKProductsRequest documentation

Note

Be sure to keep a strong reference to the request object; otherwise, the system might deallocate the request before it can complete.

Since you are creating your SKProductsRequest instance as a local variable, it is being released as soon as the getProducts function returns, before the delegate method can be called.

You need to use a property to hold a strong reference to your products request:

```<code>class IAPService: NSObject {

    private override init() {}
    static let shared = IAPService()

    var products = [SKProduct]()
    var request: SKProductsRequest?
    let paymentQueue = SKPaymentQueue.default()

    func getProducts() {
        let products: Set = [IAPProducts.nonConsumable.rawValue,
                             ]

        self.request = SKProductsRequest(productIdentifiers: products)
        request?.delegate = self
        request?.start()
        paymentQueue.add(self)
    }

    func purchase(product: IAPProducts) {
        guard let productToPurchase = products.filter({ $0.productIdentifier == product.rawValue }).first else { return }

        let payment = SKPayment(product: productToPurchase)
        paymentQueue.add(payment)
    }
}

extension IAPService: SKProductsRequestDelegate {
    func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
        if !response.invalidProductIdentifiers.isEmpty {
            print("Invalid products identifiers received")
        }
        products = response.products
        self.request = nil
    }

    func request(_ request: SKRequest, didFailWithError error:Error) {
        print("Product request failed: \(error.localizedDescription)")
    }
}
</code>```

Title: Unable to purchase IAP as sandbox user

Body:
I am having a problem trying to purchase an IAP as a sandbox user. It's not the sandbox account that's the problem. It's the fact that my var products = [SKProduct]() array in IAPService.swift is empty.

Inside my StoreViewController.swift (which also stores my Game Center leaderboards):

class StoreViewController: UIViewController, GKGameCenterControllerDelegate {

    @IBAction func purchase(_ sender: UIButton) {
        IAPService.shared.purchase(product: .nonConsumable)
    }

    ...

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        IAPService.shared.getProducts()

        print(IAPService.shared.products) // This is an empty array?

        authenticateLocalPlayer() // Related to Game Center
    }
}

Inside my IAPProducts.swift

enum IAPProducts: String {
    case nonConsumable = "com.nameofgame.nameofproduct"
}

Inside my IAPService.swift

import Foundation
import StoreKit

class IAPService: NSObject {

    private override init() {}
    static let shared = IAPService()

    var products = [SKProduct]()
    let paymentQueue = SKPaymentQueue.default()

    func getProducts() {
        let products: Set = [IAPProducts.nonConsumable.rawValue,
                             ]

        let request = SKProductsRequest(productIdentifiers: products)
        request.delegate = self
        request.start()
        paymentQueue.add(self)
    }

    func purchase(product: IAPProducts) {
        guard let productToPurchase = products.filter({ $0.productIdentifier == product.rawValue }).first else { return }

        let payment = SKPayment(product: productToPurchase)
        paymentQueue.add(payment)
    }
}

extension IAPService: SKProductsRequestDelegate {
    func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
        products = response.products
    }
}

extension IAPService: SKPaymentTransactionObserver {
    func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        for transaction in transactions {

            switch transaction.transactionState {
            case .purchased:

                if transaction.payment.productIdentifier == IAPProducts.nonConsumable.rawValue {
                    print("IAP Purchased")
                }
                break

            case .failed:
                SKPaymentQueue.default().finishTransaction(transaction)
                print(transaction.error!)
                break

            default: break
            }
        }
    }
}

Things I've done several things to try and solve the problem:

Changed the Set in IAPService to an NSSet. This doesn't work because the set of Strings in let request = SKProductsRequest(productIdentifiers: products) cannot be converted to an NSSet.

Checked multiple times that my BundleIDs match on Xcode and iTunes Connect. I've also done this check with the Product IDs to make sure there's a match between the IAP ID in iTunes Connect and the IAPProducts enum.

I added this IAP on iTunes Connect 3 days ago, and I've checked that all my contracts for paid apps are in effect.

Please help me with this issue. Thanks.

Body:
From the SKProductsRequest documentation

Note

Be sure to keep a strong reference to the request object; otherwise, the system might deallocate the request before it can complete.

Since you are creating your SKProductsRequest instance as a local variable, it is being released as soon as the getProducts function returns, before the delegate method can be called.

You need to use a property to hold a strong reference to your products request:

class IAPService: NSObject {

    private override init() {}
    static let shared = IAPService()

    var products = [SKProduct]()
    var request: SKProductsRequest?
    let paymentQueue = SKPaymentQueue.default()

    func getProducts() {
        let products: Set = [IAPProducts.nonConsumable.rawValue,
                             ]

        self.request = SKProductsRequest(productIdentifiers: products)
        request?.delegate = self
        request?.start()
        paymentQueue.add(self)
    }

    func purchase(product: IAPProducts) {
        guard let productToPurchase = products.filter({ $0.productIdentifier == product.rawValue }).first else { return }

        let payment = SKPayment(product: productToPurchase)
        paymentQueue.add(payment)
    }
}

extension IAPService: SKProductsRequestDelegate {
    func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
        if !response.invalidProductIdentifiers.isEmpty {
            print("Invalid products identifiers received")
        }
        products = response.products
        self.request = nil
    }

    func request(_ request: SKRequest, didFailWithError error:Error) {
        print("Product request failed: \(error.localizedDescription)")
    }
}


问:
I need two website one database?
i have a hosting and wordpress design and want to know how to make 2 websites use

just one database ?
can anyone help me, do i have to change the wp_options ?

```<code>$table_prefix = ‘wp_’;
define(‘CUSTOM_USER_TABLE’, $table_prefix.’global_users’);
define(‘CUSTOM_USER_META_TABLE’, $table_prefix.’global_usermeta’);

define(‘WP_ALLOW_MULTISITE’, true);
</code>```

答: You can use the same "wp-config" when you want to "mirror" the page. If you simply want to host two WordPress websites from the same database you need to change the $table_prefix in the "wp-config".

Title: I need two website one database?

Body:
i have a hosting and wordpress design and want to know how to make 2 websites use

just one database ?
can anyone help me, do i have to change the wp_options ?

$table_prefix = ‘wp_’;
define(‘CUSTOM_USER_TABLE’, $table_prefix.’global_users’);
define(‘CUSTOM_USER_META_TABLE’, $table_prefix.’global_usermeta’);

define(‘WP_ALLOW_MULTISITE’, true);


问:
How do I invoke a private static method using reflection (Java)?
I would like to invoke a private static method. I have its name. I've heard it can be done using Java reflection mechanism. How can I do it?

EDIT: One problem I encountered when trying to invoke the method is how to specify the type of its argument. My method receives one argument and its type is Map. Therefore I cannot do Map<User, String>.TYPE (In run time there's no such a thing as Map because of Java Type erasure). Is there another way to get the method?

答:
Invoke main from reflection tutorial</p>

```<code>import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;

public class InvokeMain {
    public static void main(String... args) {
    try {
        Class<?> c = Class.forName(args[0]);
        Class[] argTypes = new Class[] { String[].class };
        Method main = c.getDeclaredMethod("main", argTypes);
        String[] mainArgs = Arrays.copyOfRange(args, 1, args.length);
        System.out.format("invoking %s.main()%n", c.getName());
        main.invoke(null, (Object)mainArgs);

        // production code should handle these exceptions more gracefully
    } catch (ClassNotFoundException x) {
        x.printStackTrace();
    } catch (NoSuchMethodException x) {
        x.printStackTrace();
    } catch (IllegalAccessException x) {
        x.printStackTrace();
    } catch (InvocationTargetException x) {
        x.printStackTrace();
    }
    }
}
</code>```

Body:
Invoke main from reflection tutorial

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;

public class InvokeMain {
    public static void main(String... args) {
    try {
        Class<?> c = Class.forName(args[0]);
        Class[] argTypes = new Class[] { String[].class };
        Method main = c.getDeclaredMethod("main", argTypes);
        String[] mainArgs = Arrays.copyOfRange(args, 1, args.length);
        System.out.format("invoking %s.main()%n", c.getName());
        main.invoke(null, (Object)mainArgs);

        // production code should handle these exceptions more gracefully
    } catch (ClassNotFoundException x) {
        x.printStackTrace();
    } catch (NoSuchMethodException x) {
        x.printStackTrace();
    } catch (IllegalAccessException x) {
        x.printStackTrace();
    } catch (InvocationTargetException x) {
        x.printStackTrace();
    }
    }
}


问:
How to count in multiple columns a variable
I am working on a Crystal Report and cannot figure out a way to do this in Crystal or MSSQL

I have a table with usernames that get recorded when an activity is completed in a web app like below

```<code>UID Approved    Denied  Moved   Pended
1   Tom         null    null    Bill
2   null        null    Bill    null
3   Bill        null    Tom     null
4   null        Tom     null    null
5   Tom         null    Bill    Bill
6   null        Bill    Bill    null
7   Tom         null    null    Bill
</code>```

I need to produce a productivity report like below

```<code>        Approved    Denied  Moved   Pended
Tom     3           1       1       0
Bill    1           1       3       3
</code>```

I am not sure how to group the counts by the names that are in the data?

答:
SQL Fiddle Demo

First get all user into a temp table then group all aggregations into one table

```<code>--Get all users

SELECT *
INTO #Tbl_User
FROM (

SELECT DISTINCT Approved as [User]
FROM MY_TABLE

UNION

SELECT  DISTINCT Denied  as [User]
FROM MY_TABLE

UNION

SELECT DISTINCT  Moved as [User]
FROM MY_TABLE

UNION

SELECT DISTINCT Pended  as [User]
FROm MY_TABLE) AS T1 WHERE T1.User IS NOT NULL

--Group results

SELECT T1.[User], ISNULL(T2.Approved,0)  Approved, ISNULL(T3.Denied,0) Denied, ISNULL(T4.Moved,0) Moved, ISNULL(T5.Pended,0) Pended
FROM #Tbl_User AS T1 INNER JOIN (
SELECT Approved as [User],Count(*) as Approved
FROM MY_TABLE
GROUP BY Approved) AS T2 ON T1.[User] =T2.[User]
LEFT JOIN (
SELECT Denied as [User],Count(*) as Denied
FROM MY_TABLE
GROUP BY Denied) AS T3 ON T1.[User] =T3.[User]
LEFT JOIN (
SELECT Moved as [User],Count(*) as Moved
FROM MY_TABLE
GROUP BY Moved) AS T4 ON T1.[User] =T4.[User]
LEFT JOIN (
SELECT Pended as [User],Count(*) as Pended
FROM MY_TABLE
GROUP BY Pended) AS T5 ON T1.[User] =T5.[User]
</code>```

Body:
I am working on a Crystal Report and cannot figure out a way to do this in Crystal or MSSQL

I have a table with usernames that get recorded when an activity is completed in a web app like below

UID Approved    Denied  Moved   Pended
1   Tom         null    null    Bill
2   null        null    Bill    null
3   Bill        null    Tom     null
4   null        Tom     null    null
5   Tom         null    Bill    Bill
6   null        Bill    Bill    null
7   Tom         null    null    Bill

I need to produce a productivity report like below

        Approved    Denied  Moved   Pended
Tom     3           1       1       0
Bill    1           1       3       3

I am not sure how to group the counts by the names that are in the data?

Body:
SQL Fiddle Demo

First get all user into a temp table then group all aggregations into one table

--Get all users

SELECT *
INTO #Tbl_User
FROM (

SELECT DISTINCT Approved as [User]
FROM MY_TABLE

UNION

SELECT  DISTINCT Denied  as [User]
FROM MY_TABLE

UNION

SELECT DISTINCT  Moved as [User]
FROM MY_TABLE

UNION

SELECT DISTINCT Pended  as [User]
FROm MY_TABLE) AS T1 WHERE T1.User IS NOT NULL

--Group results

SELECT T1.[User], ISNULL(T2.Approved,0)  Approved, ISNULL(T3.Denied,0) Denied, ISNULL(T4.Moved,0) Moved, ISNULL(T5.Pended,0) Pended
FROM #Tbl_User AS T1 INNER JOIN (
SELECT Approved as [User],Count(*) as Approved
FROM MY_TABLE
GROUP BY Approved) AS T2 ON T1.[User] =T2.[User]
LEFT JOIN (
SELECT Denied as [User],Count(*) as Denied
FROM MY_TABLE
GROUP BY Denied) AS T3 ON T1.[User] =T3.[User]
LEFT JOIN (
SELECT Moved as [User],Count(*) as Moved
FROM MY_TABLE
GROUP BY Moved) AS T4 ON T1.[User] =T4.[User]
LEFT JOIN (
SELECT Pended as [User],Count(*) as Pended
FROM MY_TABLE
GROUP BY Pended) AS T5 ON T1.[User] =T5.[User]


问:
Dynamically adding attributes without changing the java object
I want to add another new attributes the an field without changing the java
object.

```<code><field  attribute1 = "1"  attribute2 = "2"  attribute3 = "3"> value</filed>

@XmlRootElement(name = "field ")
public class Field
{
    @XmlAttribute(name="attribute1")
    private String attribute1;

    @XmlAttribute(name="attribute2")
    private String attribute2;

    @XmlAttribute(name="attribute3")
    private String attribute3;
}
</code>```

If I want to add a new attribute 4  to the XMLwithout changing the Field class(adding new field to the class and recompile).

Is there a way to do that?

答:
If your want the Java class to be able to store any attribute, you need a Map to store the attribute name/value pairs, and you need to annotate that field with @XmlAnyAttribute.

Here is example code:

```<code>@XmlRootElement(name = "field")
@XmlAccessorType(XmlAccessType.FIELD)
public class Field {
    @XmlAttribute(name="attribute1")
    String attribute1;

    @XmlAttribute(name="attribute2")
    String attribute2;

    @XmlAttribute(name="attribute3")
    String attribute3;

    @XmlAnyAttribute
    Map<String, String> attributes;
}
</code>```

Test

```<code>String xml = "<field attribute1=\"A\"" +
                   " attribute2=\"B\"" +
                   " attribute3=\"C\"" +
                   " attribute4=\"D\"" +
                   " foo=\"Bar\" />";
JAXBContext jaxbContext = JAXBContext.newInstance(Field.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Field field = (Field) unmarshaller.unmarshal(new StringReader(xml));
System.out.println("field.attribute1 = " + field.attribute1);
System.out.println("field.attribute2 = " + field.attribute2);
System.out.println("field.attribute3 = " + field.attribute3);
System.out.println("field.attributes = " + field.attributes);
</code>```

Output

field.attribute1 = A
field.attribute2 = B
field.attribute3 = C
field.attributes = {attribute4=D, foo=Bar}
```

<p>As you can see, the two "extra" attributes were added to the map.</p>

<p>If you run the same test but without any attributes, i.e. with <code>xml = "<field/>";</code>, you get:</p>

<pre class="lang-none prettyprint-override"><code>field.attribute1 = null
field.attribute2 = null
field.attribute3 = null
field.attributes = null
</code>```

The attributes field is left unassigned, i.e. null. It is not an empty map.

Body:
I want to add another new attributes the an field without changing the java
object.

<field  attribute1 = "1"  attribute2 = "2"  attribute3 = "3"> value</filed>

@XmlRootElement(name = "field ")
public class Field
{
    @XmlAttribute(name="attribute1")
    private String attribute1;

    @XmlAttribute(name="attribute2")
    private String attribute2;

    @XmlAttribute(name="attribute3")
    private String attribute3;
}

If I want to add a new attribute 4  to the XMLwithout changing the Field class(adding new field to the class and recompile).

Is there a way to do that?

Body:
If your want the Java class to be able to store any attribute, you need a Map to store the attribute name/value pairs, and you need to annotate that field with @XmlAnyAttribute.

Here is example code:

@XmlRootElement(name = "field")
@XmlAccessorType(XmlAccessType.FIELD)
public class Field {
    @XmlAttribute(name="attribute1")
    String attribute1;

    @XmlAttribute(name="attribute2")
    String attribute2;

    @XmlAttribute(name="attribute3")
    String attribute3;

    @XmlAnyAttribute
    Map<String, String> attributes;
}

Test

String xml = "<field attribute1=\"A\"" +
                   " attribute2=\"B\"" +
                   " attribute3=\"C\"" +
                   " attribute4=\"D\"" +
                   " foo=\"Bar\" />";
JAXBContext jaxbContext = JAXBContext.newInstance(Field.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Field field = (Field) unmarshaller.unmarshal(new StringReader(xml));
System.out.println("field.attribute1 = " + field.attribute1);
System.out.println("field.attribute2 = " + field.attribute2);
System.out.println("field.attribute3 = " + field.attribute3);
System.out.println("field.attributes = " + field.attributes);

Output

field.attribute1 = A
field.attribute2 = B
field.attribute3 = C
field.attributes = {attribute4=D, foo=Bar}

As you can see, the two "extra" attributes were added to the map.

If you run the same test but without any attributes, i.e. with xml = "<field/>";, you get:

field.attribute1 = null
field.attribute2 = null
field.attribute3 = null
field.attributes = null

The attributes field is left unassigned, i.e. null. It is not an empty map.


问:
How to access screen display’s DPI settings via javascript?
Is there a way to access the screen display's DPI settings in a Javascript function?

I am trying to position a HTML panel on the page and when the user's DPI is set to large (120), it throws the position off.  I need to be able to know what the DPI is so I can adjust the position accordingly.

答:
Firstly, to help with the possible (and very common) confusion with the term DPI (dots per inch):

DPI isn't exactly a part of "display settings". It's (mis)used in two different contexts:

The native pixels per inch of a display (or video). It determines how small the pixels are. You can have the same 1024x768 resolution on both a 14" laptop screen and a 17" LCD monitor. The former would roughly be 1280/14 = 91 DPI and the latter would roughly be 1280/17 = 75 DPI. The DPI of a screen is immutable; it can't be changed with display settings. More...

The dots per inch painted on paper during printing. This is the number of side-by-side dots a printer/photocopier/fax machine can imprint within an inch of paper. Most printers can be set to print at a lower DPI, by just printing each dot as two, four, etc. dots. More...

When printing an image, there are many things that affect the final dimensions of the image on paper:

The dimensions of the source image -- this is the amount of pixels or data there is.

The DPI of the source image. This value determines how the dimensions should be interpreted when printing the image.

If the source image doesn't have embedded DPI information (a JPEG can have one, a GIF never does), the program that's being used may have settings to specify a DPI. This could be an image viewer/editor or even a web browser.

The zoom factor that's typically specified in a print dialog.

The current DPI setting of the printer.

The physical (max) DPI of the printer.

The bottom line is, the image that you're printing will effectively get resampled (reduced or enlarged) to match the final DPI that's used in the print process. Any of the parties involed may be causing this (the program, the print driver, the printer).

Now, coming back to your question. No, you can't determine the DPI of the screen, because it's not in software domain. It's a hardware domain term, describing how large a monitor a user could afford to buy. Update: I initially wrote this answer back in 2009, with my understanding of the current technologies. As @thure pointed out, you can now (since 2012?) use the window.matchMedia function to determine the DPI of the screen.

If you're trying to achieve precision in printing an HTML layout, as others have suggested, your CSS should use print dimensions like em, pt or pc instead of px. However, the final outcome might still depend on the browser using. If converting your HTML to PDF (or generating PDF from scratch) is an option for you, printing a PDF would give you the truest WYSIWYG both on screen and paper.

Misunderstandings about dpi

DPI, PPI, Pixels - Facts and Fallacies

OwnerDisplayName: Yttrium

OwnerDisplayName: Ates Goral

LastEditorDisplayName: Ates Goral


问:
jquery ui checkbox button state
If I have a group of checkbox buttons, what is the correct way to determine the button state?

Right now I do this:

```<code>$('#group label').each(function() {
    if ($(this).attr('aria-pressed') == 'true') {
        /* Do something */
    }
});
</code>```

But sometimes no checkbox buttons are checked and some still have aria-pressed = true.  I don't understand it.

答: Use .is(':checked') on the jQuery object containing your checkbox to test if it's checked.

Title: jquery ui checkbox button state

Body:
If I have a group of checkbox buttons, what is the correct way to determine the button state?

Right now I do this:

$('#group label').each(function() {
    if ($(this).attr('aria-pressed') == 'true') {
        /* Do something */
    }
});

But sometimes no checkbox buttons are checked and some still have aria-pressed = true.  I don't understand it.


问:
How to create a sequence that increases its step in R
I'm trying to create a sequence that increases its step by one at each interval, but can't manage to do that.

I would like my result to look like this:

```<code>vec <- c(1,3,6,10,15,21,28,36,45,55)
</code>```

So basically, starting from 1, each index is equal to the precedent plus a number that is increasing by 1 step by step, something like

```<code>[i]=[i-1]+seq(from=i, to=10, by=1)
</code>```

but of course this is not the correct notation.

How would you set this up in order to get something like shown in vec? I imagine some loop is necessary in order to have an indices in a vector exponentially increasing.

答:
This is called the Triangular Number Sequence and has the form:

Tn = 1 + 2 + 3 + 4 + 5 + ... + n

This can be created with the cumsum function in R:

```<code>cumsum(1:10)
# [1]  1  3  6 10 15 21 28 36 45 55
</code>```

or something like this if you prefer recursion:

```<code>tri_num = function(n){
  if(n <= 1){
    return(1)
  }else{
    return(n+tri_num(n-1))
  }
}

sapply(1:10, tri_num)
</code>```

Body:
I'm trying to create a sequence that increases its step by one at each interval, but can't manage to do that.

I would like my result to look like this:

vec <- c(1,3,6,10,15,21,28,36,45,55)

So basically, starting from 1, each index is equal to the precedent plus a number that is increasing by 1 step by step, something like

[i]=[i-1]+seq(from=i, to=10, by=1)

but of course this is not the correct notation.

How would you set this up in order to get something like shown in vec? I imagine some loop is necessary in order to have an indices in a vector exponentially increasing.

Body:
This is called the Triangular Number Sequence and has the form:

Tn = 1 + 2 + 3 + 4 + 5 + ... + n

This can be created with the cumsum function in R:

cumsum(1:10)
# [1]  1  3  6 10 15 21 28 36 45 55

or something like this if you prefer recursion:

tri_num = function(n){
  if(n <= 1){
    return(1)
  }else{
    return(n+tri_num(n-1))
  }
}

sapply(1:10, tri_num)


问:
JavaFX slows down backend
This is a school project. We built a JavaFX GUI to take inputs for an algorithm. The algorithm runs only 45 minutes in stand-alone mode. However, when calling from JavaFX GUI, the running time is doubled. Any idea what might cause this? Also, the JavaFX GUI consumes about 400 Mb memory, is this normal?

Any help is appreciated.

Yulian

答:
The algorithm and the GUI draw calls are competing for memory and this will create a slowdown for both the algorithm and the gui.

Allocate more memory for the java runtime to fix this

Title: JavaFX slows down backend


问:
convert 3 columns data frame to matrix
I have the following input:

```<code>A   B   0
A   C   1
B   C   1
</code>```

Which I would like to convert to a 3x3 matrix:

```<code>    A   B   C
A   0   0   1
B   0   0   1
C   1   1   0
</code>```

How should I do this in R? The above is just to give an idea of what I aim to do. Below is my data. I cut this down to 15 obs but my dataset has 500 and the ticker set are the same for ticker1 and ticker2. Thus I would want an n x n matrix.

```<code>ticker1 ticker2 edge
AEPI    AVAV    0.044210322
AEPI    BOKF    0.008021954
AEPI    CMSB    0.001986887
AEPI    RON     0.006777085
AEPI    CAKE    0.045002911
APPL    COH     0.042760407
APPL    SWZA    0.040913242
APPL    DRIV    0.047699102
APPL    CXP     0.014103206
MSCR    FIVN    0.008781475
MSCR    HOS     0.040222645
MSCR    HDSN    0.010454853
MSCR    IPWR    0.003376232
MSCR    KELYB   0.000755429
</code>```

答:
Another way with igraph and data from @akrun

```<code>df1 <- structure(list(v1 = c("A", "A", "B"), v2 = c("B", "C", "C"),
                      v3 = c(0L, 1L, 1L)), .Names = c("v1", "v2", "v3"), class = "data.frame", row.names = c(NA, -3L))

library(igraph)

g=graph.data.frame(df1,directed=FALSE)
get.adjacency(g,attr='v3',spars=FALSE)
</code>```

Edit 1

```<code>    df2 <- read.table(text="ticker1 ticker2 edge
               AEPI    AVAV    0.044210322
               AEPI    BOKF    0.008021954
               AEPI    CMSB    0.001986887
               AEPI    RON     0.006777085
               AEPI    CAKE    0.045002911
               APPL    COH     0.042760407
               APPL    SWZA    0.040913242
               APPL    DRIV    0.047699102
               APPL    CXP     0.014103206
               MSCR    FIVN    0.008781475
               MSCR    HOS     0.040222645
               MSCR    HDSN    0.010454853
               MSCR    IPWR    0.003376232
               MSCR    KELYB   0.000755429",header=TRUE)

g=graph.data.frame(df2,directed=FALSE)
get.adjacency(g,attr='edge',spars=FALSE)
</code>```

Title: convert 3 columns data frame to matrix

Body:
I have the following input:

A   B   0
A   C   1
B   C   1

Which I would like to convert to a 3x3 matrix:

    A   B   C
A   0   0   1
B   0   0   1
C   1   1   0

How should I do this in R? The above is just to give an idea of what I aim to do. Below is my data. I cut this down to 15 obs but my dataset has 500 and the ticker set are the same for ticker1 and ticker2. Thus I would want an n x n matrix.

ticker1 ticker2 edge
AEPI    AVAV    0.044210322
AEPI    BOKF    0.008021954
AEPI    CMSB    0.001986887
AEPI    RON     0.006777085
AEPI    CAKE    0.045002911
APPL    COH     0.042760407
APPL    SWZA    0.040913242
APPL    DRIV    0.047699102
APPL    CXP     0.014103206
MSCR    FIVN    0.008781475
MSCR    HOS     0.040222645
MSCR    HDSN    0.010454853
MSCR    IPWR    0.003376232
MSCR    KELYB   0.000755429

Body:
Another way with igraph and data from @akrun

df1 <- structure(list(v1 = c("A", "A", "B"), v2 = c("B", "C", "C"),
                      v3 = c(0L, 1L, 1L)), .Names = c("v1", "v2", "v3"), class = "data.frame", row.names = c(NA, -3L))

library(igraph)

g=graph.data.frame(df1,directed=FALSE)
get.adjacency(g,attr='v3',spars=FALSE)

Edit 1

    df2 <- read.table(text="ticker1 ticker2 edge
               AEPI    AVAV    0.044210322
               AEPI    BOKF    0.008021954
               AEPI    CMSB    0.001986887
               AEPI    RON     0.006777085
               AEPI    CAKE    0.045002911
               APPL    COH     0.042760407
               APPL    SWZA    0.040913242
               APPL    DRIV    0.047699102
               APPL    CXP     0.014103206
               MSCR    FIVN    0.008781475
               MSCR    HOS     0.040222645
               MSCR    HDSN    0.010454853
               MSCR    IPWR    0.003376232
               MSCR    KELYB   0.000755429",header=TRUE)

g=graph.data.frame(df2,directed=FALSE)
get.adjacency(g,attr='edge',spars=FALSE)


问:
android:dither="true" does not dither, what's wrong?
I've been trying to get android to dither the background image of an activity - so far without success. I have no clue what's wrong.

This is what I did:

The root element of my activity layout is a LinearLayout:

```<code><LinearLayout android:id="@+id/AbsoluteLayout01"
android:layout_width="fill_parent" android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:gravity="center_horizontal"
android:background="@drawable/background_dither">
</code>```

where I added @drawable/background_dither as the background image.
I put an XML file "background_dither.xml" in drawable-hdpi with the following content:

```<code><?xml version="1.0" encoding="utf-8"?>
<bitmap
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/backimg"
android:src="@drawable/background"
android:dither="true"
android:antialias="true" />
</code>```

which references the actual image background.png in drawable-hdpi. The image, which includes a large color gradient, does show up, but with heavy color banding. From what I've learned from the SDK, this can be mitigated by using the /above proxy image definition together with specifying android:dither="true". This however, has absolutely no effect.

What am I missing to get dithering working?

EDIT: Uploaded the sources here

EDIT2: After none of the suggested methods helped to get rid of color banding, after reading this blog post from Romain Guy  I had the idea to check whether my PNG background has an alpha channel. It didn't. After adding one, android actually seems to use RGB8888, as said in the post and the banding is gone (also for 2.2). Still wondering why the other methods didn't work.

EDIT3: One has to make sure that the PNG not only has an alpha channel, but also at least one pixel that has an alpha value != FF, otherwise the android build tools will again strip that bitmap down to an indexed palette without alpha channel.

答:
A lot of folks having the same problem report that setting setDither(true) on your drawable resource in the Java code works when the XML attribute does not.  In this case, if you can get a reference to your LinearLayout in the onCreate method, try

linearLayout.getBackground().setDither(true).

An alternative would be to try setting a different pixel format as described here:

https://web.archive.org/web/20180903190558/http://stuffthathappens.com/blog/2010/06/04/android-color-banding/

Good luck!

Body:
I've been trying to get android to dither the background image of an activity - so far without success. I have no clue what's wrong.

This is what I did:

The root element of my activity layout is a LinearLayout:

<LinearLayout android:id="@+id/AbsoluteLayout01"
android:layout_width="fill_parent" android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:gravity="center_horizontal"
android:background="@drawable/background_dither">

where I added @drawable/background_dither as the background image.
I put an XML file "background_dither.xml" in drawable-hdpi with the following content:

<?xml version="1.0" encoding="utf-8"?>
<bitmap
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/backimg"
android:src="@drawable/background"
android:dither="true"
android:antialias="true" />

which references the actual image background.png in drawable-hdpi. The image, which includes a large color gradient, does show up, but with heavy color banding. From what I've learned from the SDK, this can be mitigated by using the /above proxy image definition together with specifying android:dither="true". This however, has absolutely no effect.

What am I missing to get dithering working?

EDIT: Uploaded the sources here

EDIT2: After none of the suggested methods helped to get rid of color banding, after reading this blog post from Romain Guy  I had the idea to check whether my PNG background has an alpha channel. It didn't. After adding one, android actually seems to use RGB8888, as said in the post and the banding is gone (also for 2.2). Still wondering why the other methods didn't work.

EDIT3: One has to make sure that the PNG not only has an alpha channel, but also at least one pixel that has an alpha value != FF, otherwise the android build tools will again strip that bitmap down to an indexed palette without alpha channel.


问:
InversifyJS: dependency instantiation per HTTP Request
I'm using Inversify.JS in a project with Express. I would like to create a connection to a Neo4J Database, and this process has two objets:

The driver object - Could be shared across the application and created one time only

The session object - Each HTTP request should create a session against the driver, whose lifecyle is the same as the http request lifecycle (as long as the request ends, the connection is destroyed)

Without Insersify.JS, this problem is solved using a simple algorithm:

```<code>exports.getSession = function (context) { // 'context' is the http request
  if(context.neo4jSession) {
    return context.neo4jSession;
  }
  else {
    context.neo4jSession = driver.session();
    return context.neo4jSession;
  }
};
</code>```

(example: https://github.com/neo4j-examples/neo4j-movies-template/blob/master/api/neo4j/dbUtils.js#L13-L21)

To create a static dependency for the driver, I can inject a constant:

container.bind<DbDriver>("DbDriver").toConstantValue(new Neo4JDbDriver());

How can I create a dependency instantiated only once per request and retrieve them from the container?

I suspect I must invoke the container on a middleware like this:

```<code>this._express.use((request, response, next) => {
    // get the container and create an instance of the Neo4JSession for the request lifecycle
    next();
});
</code>```

Thanks in advance.

答:
I see two solutions to your problem.

use inRequestScope() for DbDriver dependency. (available since 4.5.0 version). It will work if you use single composition root for one http request. In other words you call container.get() only once per http request.

create child container, attach it to response.locals._container and register DbDriver as singleton.

```<code>let appContainer = new Container()
appContainer.bind(SomeDependencySymbol).to(SomeDependencyImpl);

function injectContainerMiddleware(request, response, next) {
     let requestContainer = appContainer.createChildContainer();
     requestContainer.bind<DbDriver>("DbDriver").toConstantValue(new Neo4JDbDriver());
     response.locals._container = requestContainer;
     next();
}

express.use(injectContainerMiddleware); //insert injectContainerMiddleware before any other request handler functions
</code>```

In this example you can retrieve DbDriver from response.locals._container in any request handler/middleware function registered after injectContainerMiddleware and you will get the same instance of DbDriver

This will work, but I'm not sure how performant it is. Additionally I guess that you may need to somehow dispose requestContainer (unbind all dependencies and remove reference to parent container) after http request is done.

Body:
I'm using Inversify.JS in a project with Express. I would like to create a connection to a Neo4J Database, and this process has two objets:

The driver object - Could be shared across the application and created one time only

The session object - Each HTTP request should create a session against the driver, whose lifecyle is the same as the http request lifecycle (as long as the request ends, the connection is destroyed)

Without Insersify.JS, this problem is solved using a simple algorithm:

exports.getSession = function (context) { // 'context' is the http request
  if(context.neo4jSession) {
    return context.neo4jSession;
  }
  else {
    context.neo4jSession = driver.session();
    return context.neo4jSession;
  }
};

(example: https://github.com/neo4j-examples/neo4j-movies-template/blob/master/api/neo4j/dbUtils.js#L13-L21)

To create a static dependency for the driver, I can inject a constant:

container.bind<DbDriver>("DbDriver").toConstantValue(new Neo4JDbDriver());

How can I create a dependency instantiated only once per request and retrieve them from the container?

I suspect I must invoke the container on a middleware like this:

this._express.use((request, response, next) => {
    // get the container and create an instance of the Neo4JSession for the request lifecycle
    next();
});

Thanks in advance.

Body:
I see two solutions to your problem.

use inRequestScope() for DbDriver dependency. (available since 4.5.0 version). It will work if you use single composition root for one http request. In other words you call container.get() only once per http request.

create child container, attach it to response.locals._container and register DbDriver as singleton.

let appContainer = new Container()
appContainer.bind(SomeDependencySymbol).to(SomeDependencyImpl);

function injectContainerMiddleware(request, response, next) {
     let requestContainer = appContainer.createChildContainer();
     requestContainer.bind<DbDriver>("DbDriver").toConstantValue(new Neo4JDbDriver());
     response.locals._container = requestContainer;
     next();
}

express.use(injectContainerMiddleware); //insert injectContainerMiddleware before any other request handler functions

In this example you can retrieve DbDriver from response.locals._container in any request handler/middleware function registered after injectContainerMiddleware and you will get the same instance of DbDriver

This will work, but I'm not sure how performant it is. Additionally I guess that you may need to somehow dispose requestContainer (unbind all dependencies and remove reference to parent container) after http request is done.


问:
Parameters will not be used with Invoke-Command remotely, -computername comes back null
I would like to know how to pass parameters with the Invoke-Command to be used within a script to run remotely.

```<code>enter code here
Param(
[string]$cname = (Read-Host "Computer Name?") ,
[string]$event = (Read-Host "What event?") ,
[string]$eventfilter = (Read-Host "What key word are you looking for?") '
[string]$amount = (Read-Host "How many events do you want to see?")
)
Invoke-Command -cn $cname -ScriptBlock {Get-EventLog -cn $cname -LogName $event -Message "*$eventfilter*" -Newest $amount | FT -Wrap}
</code>```

I would like to know if this is possible and what I would need to do to fix this script?
Thanks

答:
```<code>$cname = Read-Host "Computer Name?"
$event = Read-Host "What event?"
$eventfilter = Read-Host "What key word are you looking for?"
$amount = Read-Host "How many events do you want to see?"

Invoke-Command -cn $cname -ScriptBlock {Get-EventLog -cn $using:cname -LogName $using:event -Message "*$eventfilter*" -Newest $using:amount | FT -Wrap}
</code>```

Body:
I would like to know how to pass parameters with the Invoke-Command to be used within a script to run remotely.

enter code here
Param(
[string]$cname = (Read-Host "Computer Name?") ,
[string]$event = (Read-Host "What event?") ,
[string]$eventfilter = (Read-Host "What key word are you looking for?") '
[string]$amount = (Read-Host "How many events do you want to see?")
)
Invoke-Command -cn $cname -ScriptBlock {Get-EventLog -cn $cname -LogName $event -Message "*$eventfilter*" -Newest $amount | FT -Wrap}

I would like to know if this is possible and what I would need to do to fix this script?
Thanks