问:
getCropAndSetWallpaperIntent() Content Uri Error
I am getting this error when using getCropAndSetWallpaperIntent() in android

```<code>D/Exception: java.lang.IllegalArgumentException: Cannot use passed URI to set wallpaper; check that the type returned by ContentProvider matches image/*
</code>```

But when I check for the type of Content using ContentResolver I am getting

D/CONTENT TYPE:: IS: image/jpeg

then why is Wallpaper Manager is giving me content error ?

Here is the code I am using to get Image URI

```<code>    public Uri getImageUri(Context inContext, Bitmap inImage) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    tempPath = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
    Log.d("URI OF SET IMAGE", tempPath);
    ContentResolver cr = this.getContentResolver();
    Log.d("CONTENT TYPE: ", "IS: " + cr.getType(Uri.parse(tempPath)));
    return Uri.parse(tempPath);
}
</code>```

Any ideas ?

答:
Having the same issue. It seems it is Oreo related.
On older versions of Android works fine.

For now I've done this

```<code>try {
  val intent = manager.getCropAndSetWallpaperIntent((Uri.parse(path)))
}
catch (e: Throwable) {
  AlertDialog.Builder(this)
    .setTitle("Oops")
    .setMessage("${e.localizedMessage}\n\nThe photo has been saved to your Pictures folder. Try setting it as wallpaper manually.")
    .setPositiveButton("OK", null)
    .show()
}
</code>```

Body:
I am getting this error when using getCropAndSetWallpaperIntent() in android

D/Exception: java.lang.IllegalArgumentException: Cannot use passed URI to set wallpaper; check that the type returned by ContentProvider matches image/*

But when I check for the type of Content using ContentResolver I am getting

D/CONTENT TYPE:: IS: image/jpeg

then why is Wallpaper Manager is giving me content error ?

Here is the code I am using to get Image URI

    public Uri getImageUri(Context inContext, Bitmap inImage) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    tempPath = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
    Log.d("URI OF SET IMAGE", tempPath);
    ContentResolver cr = this.getContentResolver();
    Log.d("CONTENT TYPE: ", "IS: " + cr.getType(Uri.parse(tempPath)));
    return Uri.parse(tempPath);
}

Any ideas ?

Body:
Having the same issue. It seems it is Oreo related.
On older versions of Android works fine.

For now I've done this

try {
  val intent = manager.getCropAndSetWallpaperIntent((Uri.parse(path)))
}
catch (e: Throwable) {
  AlertDialog.Builder(this)
    .setTitle("Oops")
    .setMessage("${e.localizedMessage}\n\nThe photo has been saved to your Pictures folder. Try setting it as wallpaper manually.")
    .setPositiveButton("OK", null)
    .show()
}


来源: stackexchange

问:
Does postgresql release (advisory) locks after a DISCARD ALL; command?
Does postgresql release (advisory) locks after a DISCARD ALL; command?

It seems like it doesn't from this mail discussion I found. But I was wondering if anyone could tell me if this was changed or fixed in a new release since nov 2008?

答:
https://www.postgresql.org/docs/current/static/sql-discard.html

Releases all temporary resources associated with the current session
  and resets the session to its initial state. Currently, this has the
  same effect as executing the following sequence of statements:

```<code>SET SESSION AUTHORIZATION DEFAULT;
RESET ALL;
DEALLOCATE ALL;
CLOSE ALL;
UNLISTEN *;
SELECT pg_advisory_unlock_all();
DISCARD PLANS;
DISCARD SEQUENCES;
DISCARD TEMP;
</code>```

supposedly?..

ContentLicense: CC BY-SA 3.0

Body:
https://www.postgresql.org/docs/current/static/sql-discard.html

Releases all temporary resources associated with the current session
  and resets the session to its initial state. Currently, this has the
  same effect as executing the following sequence of statements:

SET SESSION AUTHORIZATION DEFAULT;
RESET ALL;
DEALLOCATE ALL;
CLOSE ALL;
UNLISTEN *;
SELECT pg_advisory_unlock_all();
DISCARD PLANS;
DISCARD SEQUENCES;
DISCARD TEMP;

supposedly?..


问:
SQL-Server select rows that different between 3 columns
I have table with 3 columns.
For example:
Table test

```<code>test1|test2|test3
-----------------
ab   |a    |aba
----------------
a    |b    |aa
----------------
b    |a    |ba
</code>```

I want all rows that column test1 + test2 not equal test3

Continue from above example: I want to get just the row 2 with the columns a|b|aa.

I try the follwing code:

```<code>select distinct * from DB.dbo.test l where (l.test1+ l.test2) <> l.test3;
</code>```

But it doesn't work well.
It's return me all the rows

What am I missing?

Thanks

答:
Seems like you have leading spaces:

```<code>CREATE TABLE T (test1 varchar(40), test2 varchar(40), test3 varchar(40));

INSERT INTO T VALUES
('ab ', 'a', 'aba'),
('a ', 'b', 'aa'),
('b ', 'a', 'ba');

SELECT *
FROM T
WHERE RTRIM(LTRIM(Test1)) + RTRIM(LTRIM(Test2)) != RTRIM(LTRIM(Test3));
</code>```

Demo

Body:
I have table with 3 columns.
For example:
Table test

test1|test2|test3
-----------------
ab   |a    |aba
----------------
a    |b    |aa
----------------
b    |a    |ba

I want all rows that column test1 + test2 not equal test3

Continue from above example: I want to get just the row 2 with the columns a|b|aa.

I try the follwing code:

select distinct * from DB.dbo.test l where (l.test1+ l.test2) <> l.test3;

But it doesn't work well.
It's return me all the rows

What am I missing?

Thanks

Body:
Seems like you have leading spaces:

CREATE TABLE T (test1 varchar(40), test2 varchar(40), test3 varchar(40));

INSERT INTO T VALUES
('ab ', 'a', 'aba'),
('a ', 'b', 'aa'),
('b ', 'a', 'ba');

SELECT *
FROM T
WHERE RTRIM(LTRIM(Test1)) + RTRIM(LTRIM(Test2)) != RTRIM(LTRIM(Test3));

Demo


问:
How can i get android toolbar menu group
In some pages of stackoverflow said that you can get menu goup with menu.findItem(R.id.groupId) but always return null and i want to know how can i get menu group

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto">
     <group android:id="@+id/fdp_m_group_normal">
         <item android:id="@+id/fdp_m_today"
               app:actionLayout="@layout/menu_today"
               app:showAsAction="always|withText"
               android:orderInCategory="100"
               android:title="today"/>
         <item android:id="@+id/fdp_m_tomorrow"
               app:actionLayout="@layout/menu_tomorrow"
               app:showAsAction="always|withText"
               android:orderInCategory="101"
               android:title="tomorrow"/>
         <item android:id="@+id/fdp_m_after"
               app:actionLayout="@layout/menu_after"
               app:showAsAction="always|withText"
               android:orderInCategory="102"
               android:title="after"/>
     </group>
     <group android:id="@+id/fdp_m_group_range">
         <item android:id="@+id/fdp_m_plus1"
               app:actionLayout="@layout/menu_plus1"
               app:showAsAction="always|withText"
               android:orderInCategory="103"
               android:title="+1"/>
         <item android:id="@+id/fdp_m_plus2"
               app:actionLayout="@layout/menu_plus2"
               app:showAsAction="always|withText"
               android:orderInCategory="104"
               android:title="+2"/>
         <item android:id="@+id/fdp_m_plus3"
               app:actionLayout="@layout/menu_plus3"
               app:showAsAction="always|withText"
               android:orderInCategory="105"
               android:title="+3"/>
    </group>
 </menu>
</code>```

and my java code for accessing menu

```<code>    @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.fdp_menu, menu);

        // Below line always return null
        MenuItem mGroupOne = menu.findItem(R.id.fdp_m_group_normal);

        super.onCreateOptionsMenu(menu, inflater);
    }
</code>```

答: Getting group using findItem does return null. I am assuming you only need it for visibility. Try using menu.setGroupVisible(R.id,false);</p>

Body:
In some pages of stackoverflow said that you can get menu goup with menu.findItem(R.id.groupId) but always return null and i want to know how can i get menu group

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto">
     <group android:id="@+id/fdp_m_group_normal">
         <item android:id="@+id/fdp_m_today"
               app:actionLayout="@layout/menu_today"
               app:showAsAction="always|withText"
               android:orderInCategory="100"
               android:title="today"/>
         <item android:id="@+id/fdp_m_tomorrow"
               app:actionLayout="@layout/menu_tomorrow"
               app:showAsAction="always|withText"
               android:orderInCategory="101"
               android:title="tomorrow"/>
         <item android:id="@+id/fdp_m_after"
               app:actionLayout="@layout/menu_after"
               app:showAsAction="always|withText"
               android:orderInCategory="102"
               android:title="after"/>
     </group>
     <group android:id="@+id/fdp_m_group_range">
         <item android:id="@+id/fdp_m_plus1"
               app:actionLayout="@layout/menu_plus1"
               app:showAsAction="always|withText"
               android:orderInCategory="103"
               android:title="+1"/>
         <item android:id="@+id/fdp_m_plus2"
               app:actionLayout="@layout/menu_plus2"
               app:showAsAction="always|withText"
               android:orderInCategory="104"
               android:title="+2"/>
         <item android:id="@+id/fdp_m_plus3"
               app:actionLayout="@layout/menu_plus3"
               app:showAsAction="always|withText"
               android:orderInCategory="105"
               android:title="+3"/>
    </group>
 </menu>

and my java code for accessing menu

    @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.fdp_menu, menu);

        // Below line always return null
        MenuItem mGroupOne = menu.findItem(R.id.fdp_m_group_normal);

        super.onCreateOptionsMenu(menu, inflater);
    }


问:
SQL ALTER TABLE foreign key
I have a problem with adding foreign keys with alter table command. I don't know how to make it so it works.

I need to add ISIK_ID and STAADION_ID to ISIK_STAADIONIL table as foreign key.

Here is my code:

```<code>    CREATE TABLE ISIK(
    ISIK_ID INT NOT NULL,
    EESNIMI VARCHAR(25) NOT NULL,
    PEREKONNANIMI VARCHAR(25) NOT NULL,
    ISIKUKOOD VARCHAR(20),
    KODAKONDSUS VARCHAR(30),
    SUGU CHAR(1) NOT NULL,
    HARIDUSTASE CHAR(1) NOT NULL,
    TELEFONI_NR VARCHAR(20),
    SYNNIPAEV DATE,
    CONSTRAINT ISIK_ID_PK PRIMARY KEY (ISIK_ID)
    );

    CREATE TABLE ISIK_STAADIONIL(
    ISIK_STAADIONIL_ID INT NOT NULL,
    CONSTRAINT ISIK__STAADIONIL_ID_PK PRIMARY KEY (ISIK_STAADIONIL_ID),
    ALATES TIMESTAMP,
    KUNI TIMESTAMP
    );

    CREATE TABLE STAADION(
    STAADION_ID INT NOT NULL,
    NIMETUS VARCHAR(20),
    KIRJELDUS VARCHAR(100),
    ASUKOHT VARCHAR(50),
    SUURUS VARCHAR(20),
    MAHUTAVUS INT,
    EHITATUD VARCHAR(20),
    EHITAJA VARCHAR(20),
    CONSTRAINT STAADION_ID_PK PRIMARY KEY (STAADION_ID)
    );

ALTER TABLE ISIK_STAADIONIL
ADD CONSTRAINT ISIK_ID_FK
FOREIGN KEY(ISIK_ID)
REFERENCES ISIK(ID);
</code>```

答:
You need to add the columns first (to the table) before you can create FK constraints using them.

```<code>CREATE TABLE ISIK_STAADIONIL(
    ISIK_STAADIONIL_ID INT NOT NULL,
    CONSTRAINT ISIK__STAADIONIL_ID_PK PRIMARY KEY (ISIK_STAADIONIL_ID),
    ALATES TIMESTAMP,
    KUNI TIMESTAMP,
    ISIK_ID INT,
    STAADION_ID INT
);
</code>```

And then your ALTER statement should work fine.

UPDATE

Changing the table-design slightly would make more sense, as per following. The logic is that ISIK_ID and STAADION_ID would together be sufficient to determine uniqueness in the ISIK_STAADIONIL table, so a separate ID is redundant:

```<code>CREATE TABLE ISIK_STAADIONIL(
    ISIK_ID INT NOT NULL,
    STAADION_ID INT NOT NULL,
    CONSTRAINT ISIK__STAADIONIL_ID_PK PRIMARY KEY (ISIK_ID, STAADION_ID),
    ALATES TIMESTAMP,
    KUNI TIMESTAMP
);
</code>```

Title: SQL ALTER TABLE foreign key

Body:
I have a problem with adding foreign keys with alter table command. I don't know how to make it so it works.

I need to add ISIK_ID and STAADION_ID to ISIK_STAADIONIL table as foreign key.

Here is my code:

    CREATE TABLE ISIK(
    ISIK_ID INT NOT NULL,
    EESNIMI VARCHAR(25) NOT NULL,
    PEREKONNANIMI VARCHAR(25) NOT NULL,
    ISIKUKOOD VARCHAR(20),
    KODAKONDSUS VARCHAR(30),
    SUGU CHAR(1) NOT NULL,
    HARIDUSTASE CHAR(1) NOT NULL,
    TELEFONI_NR VARCHAR(20),
    SYNNIPAEV DATE,
    CONSTRAINT ISIK_ID_PK PRIMARY KEY (ISIK_ID)
    );

    CREATE TABLE ISIK_STAADIONIL(
    ISIK_STAADIONIL_ID INT NOT NULL,
    CONSTRAINT ISIK__STAADIONIL_ID_PK PRIMARY KEY (ISIK_STAADIONIL_ID),
    ALATES TIMESTAMP,
    KUNI TIMESTAMP
    );

    CREATE TABLE STAADION(
    STAADION_ID INT NOT NULL,
    NIMETUS VARCHAR(20),
    KIRJELDUS VARCHAR(100),
    ASUKOHT VARCHAR(50),
    SUURUS VARCHAR(20),
    MAHUTAVUS INT,
    EHITATUD VARCHAR(20),
    EHITAJA VARCHAR(20),
    CONSTRAINT STAADION_ID_PK PRIMARY KEY (STAADION_ID)
    );

ALTER TABLE ISIK_STAADIONIL
ADD CONSTRAINT ISIK_ID_FK
FOREIGN KEY(ISIK_ID)
REFERENCES ISIK(ID);

Body:
You need to add the columns first (to the table) before you can create FK constraints using them.

CREATE TABLE ISIK_STAADIONIL(
    ISIK_STAADIONIL_ID INT NOT NULL,
    CONSTRAINT ISIK__STAADIONIL_ID_PK PRIMARY KEY (ISIK_STAADIONIL_ID),
    ALATES TIMESTAMP,
    KUNI TIMESTAMP,
    ISIK_ID INT,
    STAADION_ID INT
);

And then your ALTER statement should work fine.

UPDATE

Changing the table-design slightly would make more sense, as per following. The logic is that ISIK_ID and STAADION_ID would together be sufficient to determine uniqueness in the ISIK_STAADIONIL table, so a separate ID is redundant:

CREATE TABLE ISIK_STAADIONIL(
    ISIK_ID INT NOT NULL,
    STAADION_ID INT NOT NULL,
    CONSTRAINT ISIK__STAADIONIL_ID_PK PRIMARY KEY (ISIK_ID, STAADION_ID),
    ALATES TIMESTAMP,
    KUNI TIMESTAMP
);


问:
How can I check if a string contains an hexadecimal value in VBScript?
Is there a function in VBScript to check if a string contains a valid hexadecimal value?

For Example:

```<code>Dim x : x = IsHexadecimal("2AF3") 'x = True

Dim y : y = IsHexadecimal("X2M3") 'y = False
</code>```

答:
I realise this is an old thread, but here is my solution.
It is based on vbscript's built-in IsNumeric function that can identify a hex string provided it is preceded by &h

```<code>function is_hex(str_hex)
  is_hex = IsNumeric("&h" & str_hex)
end function
</code>```

Body:
Is there a function in VBScript to check if a string contains a valid hexadecimal value?

For Example:

Dim x : x = IsHexadecimal("2AF3") 'x = True

Dim y : y = IsHexadecimal("X2M3") 'y = False

Body:
I realise this is an old thread, but here is my solution.
It is based on vbscript's built-in IsNumeric function that can identify a hex string provided it is preceded by &h

function is_hex(str_hex)
  is_hex = IsNumeric("&h" & str_hex)
end function


问:
atlassian plugin sdk: maven dependency of dependency not resolving
Currently I am developing a JAVA plugin for (Atlassian) Bitbucket. But I'm fairly new to Maven, and it's dependency management.

Right now I have the following dependency declaration in my pom.xml

```<code><dependency>
    <groupId>org.telegram</groupId>
    <artifactId>telegrambots</artifactId>
    <version>2.4.4.5</version>
</dependency>
</code>```

But when I try to run (using atlas-run), I will get the following error when the system tries to enable the plugin:

[INFO] [talledLocalContainer] 2017-09-18 17:43:40,422 ERROR [spring-startup] c.a.plugin.osgi.factory.OsgiPlugin Detected an error (BundleException) enabling the plugin 'com.atlassian.bitbucket.plugin.HotfixMes.HotfixMes-Plugin' : Unresolved constraint in bundle com.atlassian.bitbucket.plugin.HotfixMes.Plugin [32]: Unable to resolve 32.0: missing requirement [32.0] osgi.wiring.package; (osgi.wiring.package=com.sun.jdi).  This error usually occurs when your plugin imports a package from another bundle with a specific version constraint and either the bundle providing that package doesn't meet those version constraints, or there is no bundle available that provides the specified package. For more details on how to fix this, see https://developer.atlassian.com/x/mQAN

Trying to read this, it looks like the dependency com.sun.jdi is not loading. This is what I don't get:

Firstly: this works when I have a "clean" java application without it being a Bitbucket plugin. So no dependency issues there

I can not find which "sub-dependency" would need it, but I am sure that it has something to do with the org.telegram.telegrambots, since the error only occurs when I have that dependency enabled.

Could somebody point me in the right direction ?

答:
It's very important to specify the scope of dependencies in jira plugin development, so please try the following:</p>

```<code><dependency>
    <groupId>org.telegram</groupId>
    <artifactId>telegrambots</artifactId>
    <version>2.4.4.5</version>
    <scope>provided</scope>
</dependency>
</code>```

Body:
Currently I am developing a JAVA plugin for (Atlassian) Bitbucket. But I'm fairly new to Maven, and it's dependency management.

Right now I have the following dependency declaration in my pom.xml

<dependency>
    <groupId>org.telegram</groupId>
    <artifactId>telegrambots</artifactId>
    <version>2.4.4.5</version>
</dependency>

But when I try to run (using atlas-run), I will get the following error when the system tries to enable the plugin:

[INFO] [talledLocalContainer] 2017-09-18 17:43:40,422 ERROR [spring-startup] c.a.plugin.osgi.factory.OsgiPlugin Detected an error (BundleException) enabling the plugin 'com.atlassian.bitbucket.plugin.HotfixMes.HotfixMes-Plugin' : Unresolved constraint in bundle com.atlassian.bitbucket.plugin.HotfixMes.Plugin [32]: Unable to resolve 32.0: missing requirement [32.0] osgi.wiring.package; (osgi.wiring.package=com.sun.jdi).  This error usually occurs when your plugin imports a package from another bundle with a specific version constraint and either the bundle providing that package doesn't meet those version constraints, or there is no bundle available that provides the specified package. For more details on how to fix this, see https://developer.atlassian.com/x/mQAN

Trying to read this, it looks like the dependency com.sun.jdi is not loading. This is what I don't get:

Firstly: this works when I have a "clean" java application without it being a Bitbucket plugin. So no dependency issues there

I can not find which "sub-dependency" would need it, but I am sure that it has something to do with the org.telegram.telegrambots, since the error only occurs when I have that dependency enabled.

Could somebody point me in the right direction ?

Body:
It's very important to specify the scope of dependencies in jira plugin development, so please try the following:

<dependency>
    <groupId>org.telegram</groupId>
    <artifactId>telegrambots</artifactId>
    <version>2.4.4.5</version>
    <scope>provided</scope>
</dependency>


问:
How read line by line txt file in odoo 9
```<code>my_file = fields.Binary(string='My txt file')

@api.one
def read_file(self):

    filename = self.my_file.decode('base64')
    print(filename)
</code>```

Print return all data in file!

```<code>1  TEST  100

2  TEST2  200

3  TEST3  300

4  TEST4  400
</code>```

I want get row 1 eg. ('number':1,'name':TEST,'price':100)

答:
Try this example:</p>

```<code>lines = filename.split('\n')
for line in lines:
    print(str(line.split()))
</code>```

Body:
my_file = fields.Binary(string='My txt file')

@api.one
def read_file(self):

    filename = self.my_file.decode('base64')
    print(filename)

Print return all data in file!

1  TEST  100

2  TEST2  200

3  TEST3  300

4  TEST4  400

I want get row 1 eg. ('number':1,'name':TEST,'price':100)

Body:
Try this example:

lines = filename.split('\n')
for line in lines:
    print(str(line.split()))


问:
python regex- positive lookahead
```<code>str='filename=1817616353&realname=Arguments%20for%20&%20against%20protection%20.pdf&code2=pds'
ptn='(?<=realname=).+(?=&)'
re.search(ptn,str).group()
</code>```

well, when i run this code i'm expecting to get

```<code>'Arguments%20for%20'
</code>```

as the match, but instead it gives me

```<code>'Arguments%20for%20&%20against%20protection%20.pdf'
</code>```

i thought the match should occur at the first occurrence of '&', which is right after 'for%20' part, so i have no idea why it's going all the way down to 'pdf'. what am i doing wrong?

答:
Use a negated character class instead of .+:

```<code>In [5]: ptn='(?<=realname=)[^&]+(?=&)'

In [6]: re.search(ptn,str).group()
Out[6]: 'Arguments%20for%20'
</code>```

Although you can use a non greedy quantifier by adding ? at the trailing of .*, but using a negated character class will give you a better performance in this case:

```<code>In [7]: ptn='(?<=realname=).+?(?=&)'

In [9]: %timeit re.search(ptn,str).group()
1000000 loops, best of 3: 1.46 us per loop

In [10]: ptn='(?<=realname=)[^&]+(?=&)'

In [11]: %timeit re.search(ptn,str).group()
1000000 loops, best of 3: 1.18 us per loop
</code>```

For more info read the following post regard the difference between non-greedy quantifier and negated character classes. Which would be better non-greedy regex or negated character class?

Title: python regex- positive lookahead

Body:
str='filename=1817616353&realname=Arguments%20for%20&%20against%20protection%20.pdf&code2=pds'
ptn='(?<=realname=).+(?=&)'
re.search(ptn,str).group()

well, when i run this code i'm expecting to get

'Arguments%20for%20'

as the match, but instead it gives me

'Arguments%20for%20&%20against%20protection%20.pdf'

i thought the match should occur at the first occurrence of '&', which is right after 'for%20' part, so i have no idea why it's going all the way down to 'pdf'. what am i doing wrong?

Body:
Use a negated character class instead of .+:

In [5]: ptn='(?<=realname=)[^&]+(?=&)'

In [6]: re.search(ptn,str).group()
Out[6]: 'Arguments%20for%20'

Although you can use a non greedy quantifier by adding ? at the trailing of .*, but using a negated character class will give you a better performance in this case:

In [7]: ptn='(?<=realname=).+?(?=&)'

In [9]: %timeit re.search(ptn,str).group()
1000000 loops, best of 3: 1.46 us per loop

In [10]: ptn='(?<=realname=)[^&]+(?=&)'

In [11]: %timeit re.search(ptn,str).group()
1000000 loops, best of 3: 1.18 us per loop

For more info read the following post regard the difference between non-greedy quantifier and negated character classes. Which would be better non-greedy regex or negated character class?


问:
How do I calculate a trendline for a graph?
Google is not being my friend - it's been a long time since my stats class in college...I need to calculate the start and end points for a trendline on a graph - is there an easy way to do this? (working in C# but whatever language works for you)</p>

答:
Thanks to all for your help - I was off this issue for a couple of days and just came back to it - was able to cobble this together - not the most elegant code, but it works for my purposes - thought I'd share if anyone else encounters this issue:</p>

```<code>public class Statistics
{
    public Trendline CalculateLinearRegression(int[] values)
    {
        var yAxisValues = new List<int>();
        var xAxisValues = new List<int>();

        for (int i = 0; i < values.Length; i++)
        {
            yAxisValues.Add(values[i]);
            xAxisValues.Add(i + 1);
        }

        return new Trendline(yAxisValues, xAxisValues);
    }
}

public class Trendline
{
    private readonly IList<int> xAxisValues;
    private readonly IList<int> yAxisValues;
    private int count;
    private int xAxisValuesSum;
    private int xxSum;
    private int xySum;
    private int yAxisValuesSum;

    public Trendline(IList<int> yAxisValues, IList<int> xAxisValues)
    {
        this.yAxisValues = yAxisValues;
        this.xAxisValues = xAxisValues;

        this.Initialize();
    }

    public int Slope { get; private set; }
    public int Intercept { get; private set; }
    public int Start { get; private set; }
    public int End { get; private set; }

    private void Initialize()
    {
        this.count = this.yAxisValues.Count;
        this.yAxisValuesSum = this.yAxisValues.Sum();
        this.xAxisValuesSum = this.xAxisValues.Sum();
        this.xxSum = 0;
        this.xySum = 0;

        for (int i = 0; i < this.count; i++)
        {
            this.xySum += (this.xAxisValues[i]*this.yAxisValues[i]);
            this.xxSum += (this.xAxisValues[i]*this.xAxisValues[i]);
        }

        this.Slope = this.CalculateSlope();
        this.Intercept = this.CalculateIntercept();
        this.Start = this.CalculateStart();
        this.End = this.CalculateEnd();
    }

    private int CalculateSlope()
    {
        try
        {
            return ((this.count*this.xySum) - (this.xAxisValuesSum*this.yAxisValuesSum))/((this.count*this.xxSum) - (this.xAxisValuesSum*this.xAxisValuesSum));
        }
        catch (DivideByZeroException)
        {
            return 0;
        }
    }

    private int CalculateIntercept()
    {
        return (this.yAxisValuesSum - (this.Slope*this.xAxisValuesSum))/this.count;
    }

    private int CalculateStart()
    {
        return (this.Slope*this.xAxisValues.First()) + this.Intercept;
    }

    private int CalculateEnd()
    {
        return (this.Slope*this.xAxisValues.Last()) + this.Intercept;
    }
}
</code>```

OwnerDisplayName: matt

ContentLicense: CC BY-SA 2.5

Body:
Thanks to all for your help - I was off this issue for a couple of days and just came back to it - was able to cobble this together - not the most elegant code, but it works for my purposes - thought I'd share if anyone else encounters this issue:

public class Statistics
{
    public Trendline CalculateLinearRegression(int[] values)
    {
        var yAxisValues = new List<int>();
        var xAxisValues = new List<int>();

        for (int i = 0; i < values.Length; i++)
        {
            yAxisValues.Add(values[i]);
            xAxisValues.Add(i + 1);
        }

        return new Trendline(yAxisValues, xAxisValues);
    }
}

public class Trendline
{
    private readonly IList<int> xAxisValues;
    private readonly IList<int> yAxisValues;
    private int count;
    private int xAxisValuesSum;
    private int xxSum;
    private int xySum;
    private int yAxisValuesSum;

    public Trendline(IList<int> yAxisValues, IList<int> xAxisValues)
    {
        this.yAxisValues = yAxisValues;
        this.xAxisValues = xAxisValues;

        this.Initialize();
    }

    public int Slope { get; private set; }
    public int Intercept { get; private set; }
    public int Start { get; private set; }
    public int End { get; private set; }

    private void Initialize()
    {
        this.count = this.yAxisValues.Count;
        this.yAxisValuesSum = this.yAxisValues.Sum();
        this.xAxisValuesSum = this.xAxisValues.Sum();
        this.xxSum = 0;
        this.xySum = 0;

        for (int i = 0; i < this.count; i++)
        {
            this.xySum += (this.xAxisValues[i]*this.yAxisValues[i]);
            this.xxSum += (this.xAxisValues[i]*this.xAxisValues[i]);
        }

        this.Slope = this.CalculateSlope();
        this.Intercept = this.CalculateIntercept();
        this.Start = this.CalculateStart();
        this.End = this.CalculateEnd();
    }

    private int CalculateSlope()
    {
        try
        {
            return ((this.count*this.xySum) - (this.xAxisValuesSum*this.yAxisValuesSum))/((this.count*this.xxSum) - (this.xAxisValuesSum*this.xAxisValuesSum));
        }
        catch (DivideByZeroException)
        {
            return 0;
        }
    }

    private int CalculateIntercept()
    {
        return (this.yAxisValuesSum - (this.Slope*this.xAxisValuesSum))/this.count;
    }

    private int CalculateStart()
    {
        return (this.Slope*this.xAxisValues.First()) + this.Intercept;
    }

    private int CalculateEnd()
    {
        return (this.Slope*this.xAxisValues.Last()) + this.Intercept;
    }
}

LastEditorDisplayName: matt


问:
Should I avoid Alternative Control Syntax?
As a mostly self-taught programmer, I have never really had anyone explain why certain things should or should not be used. One example (which I picked up years ago and use quite often) is the alternative control structure syntax:

```<code>x = (y == true) ? "foo" : "bar";
</code>```

I personally find this syntax easy to follow, especially for short, concise code, but I don't see it get a lot of use "in the wild" so I'd like to know if it's bad practice to use this over a more traditional if ... else structure?

Thanks in advance.

答:
The conditional operator should be pretty familiar to most devs. Actually, I would use simply:

```<code>x = y ? "foo" : "bar";
</code>```

which I find pretty easy to follow. The ==true / ==false seems (IMO) overkill for bools. A more common "olde world" usage is:

```<code>if(12345 == someVar) {...} // etc
</code>```

This "const == variable" is to avoid the issue of "=" vs "==", but since C# doesn't treat numbers as booleans, it is very rare that this is an issue, and it is more common (in C#) to see the clearer:

```<code>if(someVar == 12345) {...} // etc
</code>```

Since if you miss the extra = it usually won't compile.

OwnerDisplayName: Chris

Body:
As a mostly self-taught programmer, I have never really had anyone explain why certain things should or should not be used. One example (which I picked up years ago and use quite often) is the alternative control structure syntax:

x = (y == true) ? "foo" : "bar";

I personally find this syntax easy to follow, especially for short, concise code, but I don't see it get a lot of use "in the wild" so I'd like to know if it's bad practice to use this over a more traditional if ... else structure?

Thanks in advance.

Body:
The conditional operator should be pretty familiar to most devs. Actually, I would use simply:

x = y ? "foo" : "bar";

which I find pretty easy to follow. The ==true / ==false seems (IMO) overkill for bools. A more common "olde world" usage is:

if(12345 == someVar) {...} // etc

This "const == variable" is to avoid the issue of "=" vs "==", but since C# doesn't treat numbers as booleans, it is very rare that this is an issue, and it is more common (in C#) to see the clearer:

if(someVar == 12345) {...} // etc

Since if you miss the extra = it usually won't compile.

OwnerDisplayName: Marc Gravell


问:
struct.unpack not returning strings
Here is my code (py3.1):

```<code>def get_string(self,chars):
    return struct.unpack("{}s".format(chars),self.get_bin(chars))
</code>```

b'MESH' is going in, (b'MESH',) is coming out. Why am I not getting a string?

答:
This works:

```<code>return struct.unpack("{}s".format(chars),self.get_bin(chars))[0].decode('ASCII')
</code>```

But does not explain why unpack() neglects to do this itself. I'll leave the question open until that's answered.

Edit: Jason's improvement:

```<code>return self.get_bin(chars).decode('ASCII')
</code>```

Makes a mockery of struct really...

Title: struct.unpack not returning strings

Body:
Here is my code (py3.1):

def get_string(self,chars):
    return struct.unpack("{}s".format(chars),self.get_bin(chars))

b'MESH' is going in, (b'MESH',) is coming out. Why am I not getting a string?

Body:
This works:

return struct.unpack("{}s".format(chars),self.get_bin(chars))[0].decode('ASCII')

But does not explain why unpack() neglects to do this itself. I'll leave the question open until that's answered.

Edit: Jason's improvement:

return self.get_bin(chars).decode('ASCII')

Makes a mockery of struct really...


问:
How to take screenshot of UIScrollView visible area?
How do I take a 1:1 screenshot of UIScrollView visible area? The content may be larger or smaller than UIScrollView bounds as well as half-hidden (I've implemented custom scrolling for smaller content, so it's not in the top-left corner).
I've achieved desired result on simulator, but not on device itself:</p>

```<code>-(UIImage *)imageFromCombinedContext:(UIView *)background {
      UIImage *image;
      CGRect vis = background.bounds;
      CGSize size = vis.size;
      UIGraphicsBeginImageContext(size);
      [background.layer affineTransform];
      [background.layer renderInontext:UIGraphicsGetCurrentContext()];
      image = UIGraphicsGetImageFromCurrentImageContext();
      UIGraphicsEndImageContext();
      CGImageRef imref = CGImageCreateWithImageInRect([image CGImage], vis);
      image = [UIImage imageWithCGImage:imref];
      CGImageRelease(imref);
      return image;
}
</code>```

答:
Update swift 3+, 4 on @Concuror code</p>

```<code>func getImage(fromCombinedContext background: UIView) -> UIImage {
        var image: UIImage?
        let size: CGSize = view.frame.size
        UIGraphicsBeginImageContext(size)
        background.layer.affineTransform()
        view.layer.render(in: UIGraphicsGetCurrentContext()!)
        image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        let imgRef = image?.cgImage?.cropping(to: background.frame)
        image = UIImage(cgImage: imgRef!)
        // CGImageRelease(imgRef!) // Removing on Swift - 'CGImageRelease' is unavailable: Core Foundation objects are automatically memory managed
        return image ?? UIImage()
    }
</code>```

Body:
How do I take a 1:1 screenshot of UIScrollView visible area? The content may be larger or smaller than UIScrollView bounds as well as half-hidden (I've implemented custom scrolling for smaller content, so it's not in the top-left corner).
I've achieved desired result on simulator, but not on device itself:

-(UIImage *)imageFromCombinedContext:(UIView *)background {
      UIImage *image;
      CGRect vis = background.bounds;
      CGSize size = vis.size;
      UIGraphicsBeginImageContext(size);
      [background.layer affineTransform];
      [background.layer renderInontext:UIGraphicsGetCurrentContext()];
      image = UIGraphicsGetImageFromCurrentImageContext();
      UIGraphicsEndImageContext();
      CGImageRef imref = CGImageCreateWithImageInRect([image CGImage], vis);
      image = [UIImage imageWithCGImage:imref];
      CGImageRelease(imref);
      return image;
}

Body:
Update swift 3+, 4 on @Concuror code

func getImage(fromCombinedContext background: UIView) -> UIImage {
        var image: UIImage?
        let size: CGSize = view.frame.size
        UIGraphicsBeginImageContext(size)
        background.layer.affineTransform()
        view.layer.render(in: UIGraphicsGetCurrentContext()!)
        image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        let imgRef = image?.cgImage?.cropping(to: background.frame)
        image = UIImage(cgImage: imgRef!)
        // CGImageRelease(imgRef!) // Removing on Swift - 'CGImageRelease' is unavailable: Core Foundation objects are automatically memory managed
        return image ?? UIImage()
    }


问:
Dialogflow(api.ai) with different intents but having similar type of questions confusing api.ai
enter image description hereI am creating a chat bot android application using api.ai(Dialog flow),I have two intents with similar type of questions.
For ex.
Intent 1:  No_of_user_creating_leads
       Q:  Number of user creating leads today?

Intent 2:  No_of_user_creating_visits
       Q:  Number of user creating leads today?

where user,leads and today is entities.
when i want to ask second number questions it is triggering to first intent instead of second.
is there any way to resolve this problem

答: Hi you have to set context and create separate intents. In intent1 set output context as intent1 and in intent2 set output context as intent2, now create 2 separate intents like intent1-question with user says Number of user creating leads today? and with input context as intent1 and create the other intent with the name intent2-question with user says Number of user creating leads today? and set the input context as intent2. please refer https://dialogflow.com/docs/contexts


问:
How to create a mutli-step radial gradient Fragment shader
I'm using some shader code to create multi-step linear gradients by mixing colors. It works great. I have a radial shader which uses distance. Works fine but I dont know to adapt it to multi-step.

How could I approach it?

Linear Gradient http://glslsandbox.com/e#39992.0

```<code>uniform float time;
uniform vec2 mouse;
uniform vec2 resolution;

void main( void ) {

    float y = gl_FragCoord.y / resolution.y;

    vec4 white = vec4(1.0, 1.0, 1.0, 1.0);
    vec4 red = vec4(1.0, 0.0, 0.0, 1.0);
    vec4 blue = vec4(0.0, 0.0, 1.0, 1.0);
    vec4 green = vec4(0.0, 1.0, 0.0, 1.0);
    float step1 = 0.0;
    float step2 = 0.33;
    float step3 = 0.66;
    float step4 = 1.0;

    vec4 color = mix(white, red, smoothstep(step1, step2, y));
    color = mix(color, blue, smoothstep(step2, step3, y));
    color = mix(color, green, smoothstep(step3, step4, y));

    gl_FragColor = color;

}
</code>```

Simple radial gradient https://www.shadertoy.com/view/4tjSWh

```<code>void mainImage( out vec4 fragColor, in vec2 fragCoord )
{

    float d = distance(iResolution.xy*0.5,fragCoord.xy)*(sin(1.0)+1.5)*0.003;
    fragColor = mix(vec4(1.0, 1.0, 1.0, 1.0), vec4(0.0, 0.0, 0.0, 1.0), d);
}
</code>```

答:
You simply have to calcualte the distance from the current fragment to the center of the viewport. For this you have to calculate the fragment position in normalized device coordinates. You can use the distance to the center in the same way, as you did it with the y coordinate in the "strip" shader:

```<code>vec2 pos_ndc = 2.0 * gl_FragCoord.xy / resolution.xy - 1.0;
float dist = length(pos_ndc);
</code>```

Your shader should look somehow like this:

```<code>void main()
{
    vec2 pos_ndc = 2.0 * gl_FragCoord.xy / resolution.xy - 1.0;
    float dist = length(pos_ndc);

    vec4 white = vec4(1.0, 1.0, 1.0, 1.0);
    vec4 red = vec4(1.0, 0.0, 0.0, 1.0);
    vec4 blue = vec4(0.0, 0.0, 1.0, 1.0);
    vec4 green = vec4(0.0, 1.0, 0.0, 1.0);
    float step1 = 0.0;
    float step2 = 0.33;
    float step3 = 0.66;
    float step4 = 1.0;

    vec4 color = mix(white, red, smoothstep(step1, step2, dist));
    color = mix(color, blue, smoothstep(step2, step3, dist));
    color = mix(color, green, smoothstep(step3, step4, dist));

    gl_FragColor = color;
}
</code>```

Preview:

See the code snippet:

var ShaderProgram = {};
  ShaderProgram.Create = function( shaderList ) {
      var shaderObjs = [];
      for ( var i_sh = 0; i_sh < shaderList.length; ++ i_sh ) {
          var shderObj = this.CompileShader( shaderList[i_sh].source, shaderList[i_sh].stage );
          if ( shderObj == 0 )
              return 0;
          shaderObjs.push( shderObj );
      }
      var progObj = this.LinkProgram( shaderObjs )
      if ( progObj != 0 ) {
          progObj.attribIndex = {};
          var noOfAttributes = gl.getProgramParameter( progObj, gl.ACTIVE_ATTRIBUTES );
          for ( var i_n = 0; i_n < noOfAttributes; ++ i_n ) {
              var name = gl.getActiveAttrib( progObj, i_n ).name;
              progObj.attribIndex[name] = gl.getAttribLocation( progObj, name );
          }
          progObj.unifomLocation = {};
          var noOfUniforms = gl.getProgramParameter( progObj, gl.ACTIVE_UNIFORMS );
          for ( var i_n = 0; i_n < noOfUniforms; ++ i_n ) {
              var name = gl.getActiveUniform( progObj, i_n ).name;
              progObj.unifomLocation[name] = gl.getUniformLocation( progObj, name );
          }
      }
      return progObj;
  }
  ShaderProgram.AttributeIndex = function( progObj, name ) { return progObj.attribIndex[name]; }
  ShaderProgram.UniformLocation = function( progObj, name ) { return progObj.unifomLocation[name]; }
  ShaderProgram.Use = function( progObj ) { gl.useProgram( progObj ); }
  ShaderProgram.SetUniformI1  = function( progObj, name, val ) { if(progObj.unifomLocation[name]) gl.uniform1i( progObj.unifomLocation[name], val ); }
  ShaderProgram.SetUniformF1  = function( progObj, name, val ) { if(progObj.unifomLocation[name]) gl.uniform1f( progObj.unifomLocation[name], val ); }
  ShaderProgram.SetUniformF2  = function( progObj, name, arr ) { if(progObj.unifomLocation[name]) gl.uniform2fv( progObj.unifomLocation[name], arr ); }
  ShaderProgram.SetUniformF3  = function( progObj, name, arr ) { if(progObj.unifomLocation[name]) gl.uniform3fv( progObj.unifomLocation[name], arr ); }
  ShaderProgram.SetUniformF4  = function( progObj, name, arr ) { if(progObj.unifomLocation[name]) gl.uniform4fv( progObj.unifomLocation[name], arr ); }
  ShaderProgram.SetUniformM33 = function( progObj, name, mat ) { if(progObj.unifomLocation[name]) gl.uniformMatrix3fv( progObj.unifomLocation[name], false, mat ); }
  ShaderProgram.SetUniformM44 = function( progObj, name, mat ) { if(progObj.unifomLocation[name]) gl.uniformMatrix4fv( progObj.unifomLocation[name], false, mat ); }
  ShaderProgram.CompileShader = function( source, shaderStage ) {
      var shaderScript = document.getElementById(source);
      if (shaderScript) {
        source = "";
        var node = shaderScript.firstChild;
        while (node) {
          if (node.nodeType == 3) source += node.textContent;
          node = node.nextSibling;
        }
      }
      var shaderObj = gl.createShader( shaderStage );
      gl.shaderSource( shaderObj, source );
      gl.compileShader( shaderObj );
      var status = gl.getShaderParameter( shaderObj, gl.COMPILE_STATUS );
      if ( !status ) alert(gl.getShaderInfoLog(shaderObj));
      return status ? shaderObj : 0;
  }
  ShaderProgram.LinkProgram = function( shaderObjs ) {
      var prog = gl.createProgram();
      for ( var i_sh = 0; i_sh < shaderObjs.length; ++ i_sh )
          gl.attachShader( prog, shaderObjs[i_sh] );
      gl.linkProgram( prog );
      status = gl.getProgramParameter( prog, gl.LINK_STATUS );
      if ( !status ) alert("Could not initialise shaders");
      gl.useProgram( null );
      return status ? prog : 0;
  }

  function drawScene(){

      var canvas = document.getElementById( "ogl-canvas" );
      var vp = [canvas.width, canvas.height];

      gl.viewport( 0, 0, canvas.width, canvas.height );
      gl.enable( gl.DEPTH_TEST );
      gl.clearColor( 0.0, 0.0, 0.0, 1.0 );
      gl.clear( gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT );
      ShaderProgram.Use( progDraw );
      ShaderProgram.SetUniformF2( progDraw, "resolution", [256.0, 256.0] )
      gl.enableVertexAttribArray( progDraw.inPos );
      gl.bindBuffer( gl.ARRAY_BUFFER, bufObj.pos );
      gl.vertexAttribPointer( progDraw.inPos, 2, gl.FLOAT, false, 0, 0 );
      gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, bufObj.inx );
      gl.drawElements( gl.TRIANGLES, bufObj.inx.len, gl.UNSIGNED_SHORT, 0 );
      gl.disableVertexAttribArray( progDraw.pos );
  }

  var gl;
  var prog;
  var bufObj = {};
  function sceneStart() {

      var canvas = document.getElementById( "ogl-canvas");
      gl = canvas.getContext( "experimental-webgl" );
      if ( !gl )
        return;

      progDraw = ShaderProgram.Create(
        [ { source : "draw-shader-vs", stage : gl.VERTEX_SHADER },
          { source : "draw-shader-fs", stage : gl.FRAGMENT_SHADER }
        ] );
      progDraw.inPos = gl.getAttribLocation( progDraw, "inPos" );
      if ( prog == 0 )
          return;

      var pos = [ -1, -1, 1, -1, 1, 1, -1, 1 ];
      var inx = [ 0, 1, 2, 0, 2, 3 ];
      bufObj.pos = gl.createBuffer();
      gl.bindBuffer( gl.ARRAY_BUFFER, bufObj.pos );
      gl.bufferData( gl.ARRAY_BUFFER, new Float32Array( pos ), gl.STATIC_DRAW );
      bufObj.inx = gl.createBuffer();
      bufObj.inx.len = inx.length;
      gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, bufObj.inx );
      gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, new Uint16Array( inx ), gl.STATIC_DRAW );

      setInterval(drawScene, 50);
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script id="draw-shader-vs" type="x-shader/x-vertex">
  precision mediump float;

  attribute vec2 inPos;

  varying vec2 vertPos;

  void main()
  {
      vertPos = inPos;
      gl_Position = vec4( inPos.xy, 0.0, 1.0 );
  }
  </script>

  <script id="draw-shader-fs" type="x-shader/x-fragment">
  precision mediump float;

  varying vec2 vertPos;
  uniform vec2 resolution;

    void main()
    {
      vec2 pos_ndc = 2.0 * gl_FragCoord.xy / resolution.xy - 1.0;
      float dist = length(pos_ndc);

      vec4 white = vec4(1.0, 1.0, 1.0, 1.0);
      vec4 red = vec4(1.0, 0.0, 0.0, 1.0);
      vec4 blue = vec4(0.0, 0.0, 1.0, 1.0);
      vec4 green = vec4(0.0, 1.0, 0.0, 1.0);
      float step1 = 0.0;
      float step2 = 0.33;
      float step3 = 0.66;
      float step4 = 1.0;

      vec4 color = mix(white, red, smoothstep(step1, step2, dist));
      color = mix(color, blue, smoothstep(step2, step3, dist));
      color = mix(color, green, smoothstep(step3, step4, dist));

      gl_FragColor = color;
    }
  </script>

  <body onload="sceneStart();">
      <canvas id="ogl-canvas" style="border: none;" width="256" height="256"></canvas>
  </body></code>```

Body:
I'm using some shader code to create multi-step linear gradients by mixing colors. It works great. I have a radial shader which uses distance. Works fine but I dont know to adapt it to multi-step.

How could I approach it?

Linear Gradient http://glslsandbox.com/e#39992.0

uniform float time;
uniform vec2 mouse;
uniform vec2 resolution;

void main( void ) {

    float y = gl_FragCoord.y / resolution.y;

    vec4 white = vec4(1.0, 1.0, 1.0, 1.0);
    vec4 red = vec4(1.0, 0.0, 0.0, 1.0);
    vec4 blue = vec4(0.0, 0.0, 1.0, 1.0);
    vec4 green = vec4(0.0, 1.0, 0.0, 1.0);
    float step1 = 0.0;
    float step2 = 0.33;
    float step3 = 0.66;
    float step4 = 1.0;

    vec4 color = mix(white, red, smoothstep(step1, step2, y));
    color = mix(color, blue, smoothstep(step2, step3, y));
    color = mix(color, green, smoothstep(step3, step4, y));

    gl_FragColor = color;

}

Simple radial gradient https://www.shadertoy.com/view/4tjSWh

void mainImage( out vec4 fragColor, in vec2 fragCoord )
{

    float d = distance(iResolution.xy*0.5,fragCoord.xy)*(sin(1.0)+1.5)*0.003;
    fragColor = mix(vec4(1.0, 1.0, 1.0, 1.0), vec4(0.0, 0.0, 0.0, 1.0), d);
}

Body:
You simply have to calcualte the distance from the current fragment to the center of the viewport. For this you have to calculate the fragment position in normalized device coordinates. You can use the distance to the center in the same way, as you did it with the y coordinate in the "strip" shader:

vec2 pos_ndc = 2.0 * gl_FragCoord.xy / resolution.xy - 1.0;
float dist = length(pos_ndc);

Your shader should look somehow like this:

void main()
{
    vec2 pos_ndc = 2.0 * gl_FragCoord.xy / resolution.xy - 1.0;
    float dist = length(pos_ndc);

    vec4 white = vec4(1.0, 1.0, 1.0, 1.0);
    vec4 red = vec4(1.0, 0.0, 0.0, 1.0);
    vec4 blue = vec4(0.0, 0.0, 1.0, 1.0);
    vec4 green = vec4(0.0, 1.0, 0.0, 1.0);
    float step1 = 0.0;
    float step2 = 0.33;
    float step3 = 0.66;
    float step4 = 1.0;

    vec4 color = mix(white, red, smoothstep(step1, step2, dist));
    color = mix(color, blue, smoothstep(step2, step3, dist));
    color = mix(color, green, smoothstep(step3, step4, dist));

    gl_FragColor = color;
}

Preview:

See the code snippet:

var ShaderProgram = {};
  ShaderProgram.Create = function( shaderList ) {
      var shaderObjs = [];
      for ( var i_sh = 0; i_sh < shaderList.length; ++ i_sh ) {
          var shderObj = this.CompileShader( shaderList[i_sh].source, shaderList[i_sh].stage );
          if ( shderObj == 0 )
              return 0;
          shaderObjs.push( shderObj );
      }
      var progObj = this.LinkProgram( shaderObjs )
      if ( progObj != 0 ) {
          progObj.attribIndex = {};
          var noOfAttributes = gl.getProgramParameter( progObj, gl.ACTIVE_ATTRIBUTES );
          for ( var i_n = 0; i_n < noOfAttributes; ++ i_n ) {
              var name = gl.getActiveAttrib( progObj, i_n ).name;
              progObj.attribIndex[name] = gl.getAttribLocation( progObj, name );
          }
          progObj.unifomLocation = {};
          var noOfUniforms = gl.getProgramParameter( progObj, gl.ACTIVE_UNIFORMS );
          for ( var i_n = 0; i_n < noOfUniforms; ++ i_n ) {
              var name = gl.getActiveUniform( progObj, i_n ).name;
              progObj.unifomLocation[name] = gl.getUniformLocation( progObj, name );
          }
      }
      return progObj;
  }
  ShaderProgram.AttributeIndex = function( progObj, name ) { return progObj.attribIndex[name]; }
  ShaderProgram.UniformLocation = function( progObj, name ) { return progObj.unifomLocation[name]; }
  ShaderProgram.Use = function( progObj ) { gl.useProgram( progObj ); }
  ShaderProgram.SetUniformI1  = function( progObj, name, val ) { if(progObj.unifomLocation[name]) gl.uniform1i( progObj.unifomLocation[name], val ); }
  ShaderProgram.SetUniformF1  = function( progObj, name, val ) { if(progObj.unifomLocation[name]) gl.uniform1f( progObj.unifomLocation[name], val ); }
  ShaderProgram.SetUniformF2  = function( progObj, name, arr ) { if(progObj.unifomLocation[name]) gl.uniform2fv( progObj.unifomLocation[name], arr ); }
  ShaderProgram.SetUniformF3  = function( progObj, name, arr ) { if(progObj.unifomLocation[name]) gl.uniform3fv( progObj.unifomLocation[name], arr ); }
  ShaderProgram.SetUniformF4  = function( progObj, name, arr ) { if(progObj.unifomLocation[name]) gl.uniform4fv( progObj.unifomLocation[name], arr ); }
  ShaderProgram.SetUniformM33 = function( progObj, name, mat ) { if(progObj.unifomLocation[name]) gl.uniformMatrix3fv( progObj.unifomLocation[name], false, mat ); }
  ShaderProgram.SetUniformM44 = function( progObj, name, mat ) { if(progObj.unifomLocation[name]) gl.uniformMatrix4fv( progObj.unifomLocation[name], false, mat ); }
  ShaderProgram.CompileShader = function( source, shaderStage ) {
      var shaderScript = document.getElementById(source);
      if (shaderScript) {
        source = "";
        var node = shaderScript.firstChild;
        while (node) {
          if (node.nodeType == 3) source += node.textContent;
          node = node.nextSibling;
        }
      }
      var shaderObj = gl.createShader( shaderStage );
      gl.shaderSource( shaderObj, source );
      gl.compileShader( shaderObj );
      var status = gl.getShaderParameter( shaderObj, gl.COMPILE_STATUS );
      if ( !status ) alert(gl.getShaderInfoLog(shaderObj));
      return status ? shaderObj : 0;
  }
  ShaderProgram.LinkProgram = function( shaderObjs ) {
      var prog = gl.createProgram();
      for ( var i_sh = 0; i_sh < shaderObjs.length; ++ i_sh )
          gl.attachShader( prog, shaderObjs[i_sh] );
      gl.linkProgram( prog );
      status = gl.getProgramParameter( prog, gl.LINK_STATUS );
      if ( !status ) alert("Could not initialise shaders");
      gl.useProgram( null );
      return status ? prog : 0;
  }

  function drawScene(){

      var canvas = document.getElementById( "ogl-canvas" );
      var vp = [canvas.width, canvas.height];

      gl.viewport( 0, 0, canvas.width, canvas.height );
      gl.enable( gl.DEPTH_TEST );
      gl.clearColor( 0.0, 0.0, 0.0, 1.0 );
      gl.clear( gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT );
      ShaderProgram.Use( progDraw );
      ShaderProgram.SetUniformF2( progDraw, "resolution", [256.0, 256.0] )
      gl.enableVertexAttribArray( progDraw.inPos );
      gl.bindBuffer( gl.ARRAY_BUFFER, bufObj.pos );
      gl.vertexAttribPointer( progDraw.inPos, 2, gl.FLOAT, false, 0, 0 );
      gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, bufObj.inx );
      gl.drawElements( gl.TRIANGLES, bufObj.inx.len, gl.UNSIGNED_SHORT, 0 );
      gl.disableVertexAttribArray( progDraw.pos );
  }

  var gl;
  var prog;
  var bufObj = {};
  function sceneStart() {

      var canvas = document.getElementById( "ogl-canvas");
      gl = canvas.getContext( "experimental-webgl" );
      if ( !gl )
        return;

      progDraw = ShaderProgram.Create(
        [ { source : "draw-shader-vs", stage : gl.VERTEX_SHADER },
          { source : "draw-shader-fs", stage : gl.FRAGMENT_SHADER }
        ] );
      progDraw.inPos = gl.getAttribLocation( progDraw, "inPos" );
      if ( prog == 0 )
          return;

      var pos = [ -1, -1, 1, -1, 1, 1, -1, 1 ];
      var inx = [ 0, 1, 2, 0, 2, 3 ];
      bufObj.pos = gl.createBuffer();
      gl.bindBuffer( gl.ARRAY_BUFFER, bufObj.pos );
      gl.bufferData( gl.ARRAY_BUFFER, new Float32Array( pos ), gl.STATIC_DRAW );
      bufObj.inx = gl.createBuffer();
      bufObj.inx.len = inx.length;
      gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, bufObj.inx );
      gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, new Uint16Array( inx ), gl.STATIC_DRAW );

      setInterval(drawScene, 50);
  }

<script id="draw-shader-vs" type="x-shader/x-vertex">
  precision mediump float;

  attribute vec2 inPos;

  varying vec2 vertPos;

  void main()
  {
      vertPos = inPos;
      gl_Position = vec4( inPos.xy, 0.0, 1.0 );
  }
  </script>

  <script id="draw-shader-fs" type="x-shader/x-fragment">
  precision mediump float;

  varying vec2 vertPos;
  uniform vec2 resolution;

    void main()
    {
      vec2 pos_ndc = 2.0 * gl_FragCoord.xy / resolution.xy - 1.0;
      float dist = length(pos_ndc);

      vec4 white = vec4(1.0, 1.0, 1.0, 1.0);
      vec4 red = vec4(1.0, 0.0, 0.0, 1.0);
      vec4 blue = vec4(0.0, 0.0, 1.0, 1.0);
      vec4 green = vec4(0.0, 1.0, 0.0, 1.0);
      float step1 = 0.0;
      float step2 = 0.33;
      float step3 = 0.66;
      float step4 = 1.0;

      vec4 color = mix(white, red, smoothstep(step1, step2, dist));
      color = mix(color, blue, smoothstep(step2, step3, dist));
      color = mix(color, green, smoothstep(step3, step4, dist));

      gl_FragColor = color;
    }
  </script>

  <body onload="sceneStart();">
      <canvas id="ogl-canvas" style="border: none;" width="256" height="256"></canvas>
  </body>

ContentLicense: CC BY-SA 4.0


问:
Custom control Lib with multiple controls and generic.xaml
if i define two default styles for two different controls in one custom control lib i get errors...

is it possible to have two or more controls with a default generic.xaml in one lib?

Thanks

答:
Yes, it is possible. The recommended approach is to place styles for each control in its own resource dictionary and have one Generic.xaml file that will reference others.

So, for example, if you have two controls in your library: MyControl1 and MyControl2. Then you will have the following files in the Themes folder of your project:

generic.xaml

MyControl1.generic.xaml

MyControl2.generic.xaml

And your generic.xaml will look like this:

```<code><ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="/MyControlLib;component/Themes/MyControl1.generic.xaml" />
        <ResourceDictionary Source="/MyControlLib;component/Themes/MyControl2.generic.xaml" />
    </ResourceDictionary.MergedDictionaries>

</ResourceDictionary>
</code>```

Body:
Yes, it is possible. The recommended approach is to place styles for each control in its own resource dictionary and have one Generic.xaml file that will reference others.

So, for example, if you have two controls in your library: MyControl1 and MyControl2. Then you will have the following files in the Themes folder of your project:

generic.xaml

MyControl1.generic.xaml

MyControl2.generic.xaml

And your generic.xaml will look like this:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="/MyControlLib;component/Themes/MyControl1.generic.xaml" />
        <ResourceDictionary Source="/MyControlLib;component/Themes/MyControl2.generic.xaml" />
    </ResourceDictionary.MergedDictionaries>

</ResourceDictionary>


问:
How to split a columns into 2 correctly with pandas in Python 2.7?
I have got a lot of column in a csv, and I want to split a column into 2.

My column:

I need this format :

How can I split it? It is a little bit complex for me.

EDIT: I tried this one, but it isn't working.

```<code>df = pd.read_csv('/tmp/test.csv')
df[['Animals', 'Animals2']] = df['Animals'].str.split('(^\D+)', expand=True).drop(0,1)
df['Animals'] = df['Animals'].str.strip()
</code>```

答:
Use regex and str.split with expand i.e </p>

```<code>df = pd.DataFrame({'Animal':['Cat 3:30 pm','Hamster pig 4:30 pm','Cancelled']})
df[['Animal','Time']] = df['Animal'].str.split('(^\D+)',expand=True).drop(0,1)
df['Animal'] = df['Animal'].str.strip()
</code>```

<p>Output : </p>

```
      Animal     Time
0          Cat   3:30 pm
1  Hamster pig   4:30 pm
2     Cancelled
```

Body:
I have got a lot of column in a csv, and I want to split a column into 2.

My column:

I need this format :

How can I split it? It is a little bit complex for me.

EDIT: I tried this one, but it isn't working.

df = pd.read_csv('/tmp/test.csv')
df[['Animals', 'Animals2']] = df['Animals'].str.split('(^\D+)', expand=True).drop(0,1)
df['Animals'] = df['Animals'].str.strip()

Body:
Use regex and str.split with expand i.e

df = pd.DataFrame({'Animal':['Cat 3:30 pm','Hamster pig 4:30 pm','Cancelled']})
df[['Animal','Time']] = df['Animal'].str.split('(^\D+)',expand=True).drop(0,1)
df['Animal'] = df['Animal'].str.strip()

Output :

      Animal     Time
0          Cat   3:30 pm
1  Hamster pig   4:30 pm
2     Cancelled


问:
Pre Calculate Date in Oracle SQL Statement
I have a sql query which looks like this

```<code>select
*
from TABLE@REMOTE
where 1=1
and (NODE = 3521 or node = 3787)
and TIME_START > sysdate - 1
and TIME_END < sysdate + 1;
</code>```

Works super fast.
Now I have the adjust the time_start and time_end a litte bit:

```<code>select
*
from TABLE@REMOTE
where 1=1
and (NODE = 3521 or node = 3787)
and TIME_START > CONVERTtoTimeZone(sysdate - 1, 'UTC')
and TIME_END <CONVERTtoTimeZone(sysdate + 1, 'UTC')
</code>```

Now the query is getting really slow. Is there a way to pre calculate the time_start and time_end in advance?

答:
You can try to save the value before run your query:

```<code>WITH timeTable AS (
select CONVERTtoTimeZone(sysdate - 1, 'UTC') as dayBefore, CONVERTtoTimeZone(sysdate + 1, 'UTC') as dayAfter
from dual)
select
*
from TABLE@REMOTE
where (NODE = 3521 or node = 3787)
and TIME_START > (select dayBefore from timeTable)
and TIME_END < (select dayAfter from timeTable)
</code>```

Ps. I removed 1=1 :)

Body:
I have a sql query which looks like this

select
*
from TABLE@REMOTE
where 1=1
and (NODE = 3521 or node = 3787)
and TIME_START > sysdate - 1
and TIME_END < sysdate + 1;

Works super fast.
Now I have the adjust the time_start and time_end a litte bit:

select
*
from TABLE@REMOTE
where 1=1
and (NODE = 3521 or node = 3787)
and TIME_START > CONVERTtoTimeZone(sysdate - 1, 'UTC')
and TIME_END <CONVERTtoTimeZone(sysdate + 1, 'UTC')

Now the query is getting really slow. Is there a way to pre calculate the time_start and time_end in advance?

Body:
You can try to save the value before run your query:

WITH timeTable AS (
select CONVERTtoTimeZone(sysdate - 1, 'UTC') as dayBefore, CONVERTtoTimeZone(sysdate + 1, 'UTC') as dayAfter
from dual)
select
*
from TABLE@REMOTE
where (NODE = 3521 or node = 3787)
and TIME_START > (select dayBefore from timeTable)
and TIME_END < (select dayAfter from timeTable)

Ps. I removed 1=1 :)


问:
Firebase Android Auto Login
So I setup email/password register and login.

That is working. I thought Firebase took care of this but apparently not.
I want, after the user closes the app, to be logged in already next time they open the app.

What is missing?

```<code>class LoginActivity : AppCompatActivity(){
    lateinit var auth: FirebaseAuth
    lateinit var user: FirebaseAuth

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)

        auth = FirebaseAuth.getInstance()
    }

    fun loginLoginClicked(view: View) {
        // Perform login

        val email = loginEmailTxt.text.toString()
        val password = loginPasswordTxt.text.toString()

        auth.signInWithEmailAndPassword(email, password)
                .addOnSuccessListener {
                    finish()
                }
                .addOnFailureListener { exception ->
                    Log.e("Exception", "Could not sign in user - ${exception.localizedMessage}")
                }
        val loginIntent = Intent(this, MainActivity::class.java)
        startActivity(loginIntent)
    }

    fun loginCreateClicked(view: View) {
        // segue to the create user activity

        val createIntent = Intent(this, SignUpActivity::class.java)
        startActivity(createIntent)
    }}
}
</code>```

答:
Firebase Authentication does automatically remember authentication state, so the user will still be authenticated when the app is restarted.

However, if your LoginActivity is the launcher activity, you'll still land on this activity, so you'll need to check whether the user is authenticated in onCreate(), and then redirect them to your MainActivity if they are already logged in, something like:

```<code>override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    auth = FirebaseAuth.getInstance();

    if (auth.getCurrentUser() != null) {
        // User is signed in (getCurrentUser() will be null if not signed in)
        val intent = Intent(this, MainActivity::class.java);
        startActivity(intent);
        finish();
    }
}
</code>```

This makes use of the FirebaseAuth#getCurrentUser() method that will return a FirebaseUser object if the user is logged in, or null if they are not logged in.

Alternatively, you could swap it around so that the MainActivity is the launcher activity and then only show your LoginActivity if the user is not logged in.

....

Title: Firebase Android Auto Login

Body:
So I setup email/password register and login.

That is working. I thought Firebase took care of this but apparently not.
I want, after the user closes the app, to be logged in already next time they open the app.

What is missing?

class LoginActivity : AppCompatActivity(){
    lateinit var auth: FirebaseAuth
    lateinit var user: FirebaseAuth

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)

        auth = FirebaseAuth.getInstance()
    }

    fun loginLoginClicked(view: View) {
        // Perform login

        val email = loginEmailTxt.text.toString()
        val password = loginPasswordTxt.text.toString()

        auth.signInWithEmailAndPassword(email, password)
                .addOnSuccessListener {
                    finish()
                }
                .addOnFailureListener { exception ->
                    Log.e("Exception", "Could not sign in user - ${exception.localizedMessage}")
                }
        val loginIntent = Intent(this, MainActivity::class.java)
        startActivity(loginIntent)
    }

    fun loginCreateClicked(view: View) {
        // segue to the create user activity

        val createIntent = Intent(this, SignUpActivity::class.java)
        startActivity(createIntent)
    }}
}

Body:
Firebase Authentication does automatically remember authentication state, so the user will still be authenticated when the app is restarted.

However, if your LoginActivity is the launcher activity, you'll still land on this activity, so you'll need to check whether the user is authenticated in onCreate(), and then redirect them to your MainActivity if they are already logged in, something like:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    auth = FirebaseAuth.getInstance();

    if (auth.getCurrentUser() != null) {
        // User is signed in (getCurrentUser() will be null if not signed in)
        val intent = Intent(this, MainActivity::class.java);
        startActivity(intent);
        finish();
    }
}

This makes use of the FirebaseAuth#getCurrentUser() method that will return a FirebaseUser object if the user is logged in, or null if they are not logged in.

Alternatively, you could swap it around so that the MainActivity is the launcher activity and then only show your LoginActivity if the user is not logged in.

....


问:
datatable th value should come in dropdown as per attached image
Here is my fiddle, I need my th value/text to show in my drop down just like a placeholder.

Here is the image which I want to achieve through my Jquery code.

jsfiddle.net/gkm0L680/1

答:
Because this does have a function which returns the current header, you could simple read the textContent from that node.

```<code>$('<select><option value="">' + this.header().textContent + '</option></select>')
</code>```

Demo (jsFiddle)

Body:
Because this does have a function which returns the current header, you could simple read the textContent from that node.

$('<select><option value="">' + this.header().textContent + '</option></select>')

Demo (jsFiddle)


问:
Golang: cannot install package zvelo/ttlru
I would like to use zvelo/ttlru and have successfully go get this package from github.

Problem:

The following error occurs, when I try to go run my go program, that contains the import "github.com/zvelo/ttlru":

go_server.go:8:2: code in directory
  /home/.../work_go/src/github.com/zvelo/ttlru expects import
  "zvelo.io/ttlru"

What is wrong here? I don't see any zvelo.io/ttlru imports anywhere.

答: try go getting and importing "zvelo.io/ttlru"</p>


问:
Java-Swing: A problem using layout managers!
I'm working on a JDialog (by hand, no GUI builders) and I'm having a problem doing the layout.

I have this:

My problem is that I don't know what how to tell that JList (within a JScrollPane) to have a Maximum width, I used the setSize, setMaximumSize and nothing works! I need that JList's width to be the half of the picture's size.

Explain the layouts:

The "Gene Information" is a GridLayout 2x4, it's contained by a JPanel with BoxLayout, the +/- JButtons is a BoxLayout also, all what I said before is within a BoxLayout.
Now, the "Genes" JPanel is a GridBagLayout.

What can I do?

Thanks in advance!

PD: The other borders are just for seeign the boundaries of the components.

    Source Code:

```<code>scpGenesList.setViewportView(lstGenesList);

pnlGeneInfo.setLayout(new GridLayout(4, 2, 10, 10));
pnlGeneInfo.setBorder(BorderFactory.createCompoundBorder(
        BorderFactory.createTitledBorder("Gene Information"),
        BorderFactory.createEmptyBorder(10, 10, 10, 10)));
lblGeneSymbol.setText("Symbol:");
lblGeneSymbol.setHorizontalAlignment(SwingConstants.RIGHT);
lblGeneChromosome.setText("Chromosome:");
lblGeneChromosome.setHorizontalAlignment(SwingConstants.RIGHT);
lblGeneStartPosition.setText("Start Position:");
lblGeneStartPosition.setHorizontalAlignment(SwingConstants.RIGHT);
lblGeneStopPosition.setText("Stop Position:");
lblGeneStopPosition.setHorizontalAlignment(SwingConstants.RIGHT);
pnlGeneInfo.add(lblGeneSymbol);
pnlGeneInfo.add(lblGeneSymbolValue);
pnlGeneInfo.add(lblGeneChromosome);
pnlGeneInfo.add(lblGeneChromosomeValue);
pnlGeneInfo.add(lblGeneStartPosition);
pnlGeneInfo.add(lblGeneStartPositionValue);
pnlGeneInfo.add(lblGeneStopPosition);
pnlGeneInfo.add(lblGeneStopPositionValue);

pnlGWASAddRemoveButtons.setLayout(new BoxLayout(pnlGWASAddRemoveButtons, BoxLayout.X_AXIS));
pnlGWASAddRemoveButtons.add(Box.createHorizontalGlue());
pnlGWASAddRemoveButtons.add(cmdGenesAdd);
pnlGWASAddRemoveButtons.add(Box.createHorizontalStrut(10));
pnlGWASAddRemoveButtons.add(cmdGenesRemove);
pnlGWASAddRemoveButtons.add(Box.createHorizontalGlue());

pnlGeneInfoButtons.setLayout(new BoxLayout(pnlGeneInfoButtons, BoxLayout.Y_AXIS));
pnlGeneInfoButtons.add(pnlGeneInfo);
pnlGeneInfoButtons.add(Box.createVerticalStrut(10));
pnlGeneInfoButtons.add(pnlGWASAddRemoveButtons);

pnlGenesPanel.setLayout(new GridBagLayout());
pnlGenesPanel.setBorder(BorderFactory.createCompoundBorder(
        BorderFactory.createTitledBorder("Genes"),
        BorderFactory.createEmptyBorder(10, 10, 10, 10)));

GridBagConstraints ctrGenes = new GridBagConstraints();
ctrGenes.fill = GridBagConstraints.BOTH;
ctrGenes.gridx = 0;
ctrGenes.gridy = 0;
ctrGenes.gridwidth = 1;
ctrGenes.gridheight = 1;
ctrGenes.weighty = 1.0;
ctrGenes.weightx = 1.0;
ctrGenes.insets = new Insets(0, 0, 0, 10);
pnlGenesPanel.add(scpGenesList, ctrGenes);

GridBagConstraints ctrGenesInfoButton = new GridBagConstraints();
ctrGenesInfoButton.fill = GridBagConstraints.BOTH;
ctrGenesInfoButton.gridx = 1;
ctrGenesInfoButton.gridy = 0;
ctrGenesInfoButton.gridwidth = 1;
ctrGenesInfoButton.gridheight = 1;
ctrGenesInfoButton.weighty = 1.0;
ctrGenesInfoButton.weightx = 1.0;
pnlGenesPanel.add(pnlGeneInfoButtons, ctrGenesInfoButton);

contentPane.add(pnlGenesPanel);

pack();
</code>```

答:
It doesn't answer your question - but I've found that the JGoodies FormLayout to be more intuitive than the GridBagLayout.  The library, as well as some examples, can be found here:

http://jgoodies.com/freeware/forms/index.html

Body:
I'm working on a JDialog (by hand, no GUI builders) and I'm having a problem doing the layout.

I have this:

My problem is that I don't know what how to tell that JList (within a JScrollPane) to have a Maximum width, I used the setSize, setMaximumSize and nothing works! I need that JList's width to be the half of the picture's size.

Explain the layouts:

The "Gene Information" is a GridLayout 2x4, it's contained by a JPanel with BoxLayout, the +/- JButtons is a BoxLayout also, all what I said before is within a BoxLayout.
Now, the "Genes" JPanel is a GridBagLayout.

What can I do?

Thanks in advance!

PD: The other borders are just for seeign the boundaries of the components.

    Source Code:

scpGenesList.setViewportView(lstGenesList);

pnlGeneInfo.setLayout(new GridLayout(4, 2, 10, 10));
pnlGeneInfo.setBorder(BorderFactory.createCompoundBorder(
        BorderFactory.createTitledBorder("Gene Information"),
        BorderFactory.createEmptyBorder(10, 10, 10, 10)));
lblGeneSymbol.setText("Symbol:");
lblGeneSymbol.setHorizontalAlignment(SwingConstants.RIGHT);
lblGeneChromosome.setText("Chromosome:");
lblGeneChromosome.setHorizontalAlignment(SwingConstants.RIGHT);
lblGeneStartPosition.setText("Start Position:");
lblGeneStartPosition.setHorizontalAlignment(SwingConstants.RIGHT);
lblGeneStopPosition.setText("Stop Position:");
lblGeneStopPosition.setHorizontalAlignment(SwingConstants.RIGHT);
pnlGeneInfo.add(lblGeneSymbol);
pnlGeneInfo.add(lblGeneSymbolValue);
pnlGeneInfo.add(lblGeneChromosome);
pnlGeneInfo.add(lblGeneChromosomeValue);
pnlGeneInfo.add(lblGeneStartPosition);
pnlGeneInfo.add(lblGeneStartPositionValue);
pnlGeneInfo.add(lblGeneStopPosition);
pnlGeneInfo.add(lblGeneStopPositionValue);

pnlGWASAddRemoveButtons.setLayout(new BoxLayout(pnlGWASAddRemoveButtons, BoxLayout.X_AXIS));
pnlGWASAddRemoveButtons.add(Box.createHorizontalGlue());
pnlGWASAddRemoveButtons.add(cmdGenesAdd);
pnlGWASAddRemoveButtons.add(Box.createHorizontalStrut(10));
pnlGWASAddRemoveButtons.add(cmdGenesRemove);
pnlGWASAddRemoveButtons.add(Box.createHorizontalGlue());

pnlGeneInfoButtons.setLayout(new BoxLayout(pnlGeneInfoButtons, BoxLayout.Y_AXIS));
pnlGeneInfoButtons.add(pnlGeneInfo);
pnlGeneInfoButtons.add(Box.createVerticalStrut(10));
pnlGeneInfoButtons.add(pnlGWASAddRemoveButtons);

pnlGenesPanel.setLayout(new GridBagLayout());
pnlGenesPanel.setBorder(BorderFactory.createCompoundBorder(
        BorderFactory.createTitledBorder("Genes"),
        BorderFactory.createEmptyBorder(10, 10, 10, 10)));

GridBagConstraints ctrGenes = new GridBagConstraints();
ctrGenes.fill = GridBagConstraints.BOTH;
ctrGenes.gridx = 0;
ctrGenes.gridy = 0;
ctrGenes.gridwidth = 1;
ctrGenes.gridheight = 1;
ctrGenes.weighty = 1.0;
ctrGenes.weightx = 1.0;
ctrGenes.insets = new Insets(0, 0, 0, 10);
pnlGenesPanel.add(scpGenesList, ctrGenes);

GridBagConstraints ctrGenesInfoButton = new GridBagConstraints();
ctrGenesInfoButton.fill = GridBagConstraints.BOTH;
ctrGenesInfoButton.gridx = 1;
ctrGenesInfoButton.gridy = 0;
ctrGenesInfoButton.gridwidth = 1;
ctrGenesInfoButton.gridheight = 1;
ctrGenesInfoButton.weighty = 1.0;
ctrGenesInfoButton.weightx = 1.0;
pnlGenesPanel.add(pnlGeneInfoButtons, ctrGenesInfoButton);

contentPane.add(pnlGenesPanel);

pack();


问:
Drop and create ENUM with sequelize correctly?
How to correctly drop and then recreate ENUM type with sequelize for Postgres in migrations? For example this migration doesn't drop enum_Users_status enum... so any attempts to recreate/change status values after they have been once created fail.

```<code>module.exports = {
    up: function (queryInterface, DataTypes) {
        queryInterface.createTable('Users', {
            //...
            status: {
                type: DataTypes.ENUM,
                values: [
                    'online',
                    'offline',
                ],
                defaultValue: 'online'
            }
            //...
        })
    },

    down: function (queryInterface) {
        queryInterface.dropTable('Users')
    },
}
</code>```

Eventually i did manage to delete the enum type inside down, but then up migration (which is supposed to create this status enum from scratch) fails, saying something like public.enum_Users_status enum type doesn't exist..

答:
UPDATE: I have used this in three projects up to now, so I decided to create a npm module: https://www.npmjs.com/package/sequelize-replace-enum-postgres

I made a utility to do this, hope you it this helpful.

utils/replace_enum.js:

'use strict';

/**
 * Since PostgreSQL still does not support remove values from an ENUM,
 * the workaround is to create a new ENUM with the new values and use it
 * to replace the other.
 *
 * @param {String} tableName
 * @param {String} columnName
 * @param {String} defaultValue
 * @param {Array}  newValues
 * @param {Object} queryInterface
 * @param {String} enumName - Optional.
 *
 * @return {Promise}
 */
module.exports = function replaceEnum({
  tableName,
  columnName,
  defaultValue,
  newValues,
  queryInterface,
  enumName = `enum_${tableName}_${columnName}`
}) {
  const newEnumName = `${enumName}_new`;

  return queryInterface.sequelize.transaction((t) => {
    // Create a copy of the type
    return queryInterface.sequelize.query(`
      CREATE TYPE ${newEnumName}
        AS ENUM ('${newValues.join('\', \'')}')
    `, { transaction: t })
      // Drop default value (ALTER COLUMN cannot cast default values)
      .then(() => queryInterface.sequelize.query(`
        ALTER TABLE ${tableName}
          ALTER COLUMN ${columnName}
            DROP DEFAULT
      `, { transaction: t }))
      // Change column type to the new ENUM TYPE
      .then(() => queryInterface.sequelize.query(`
        ALTER TABLE ${tableName}
          ALTER COLUMN ${columnName}
            TYPE ${newEnumName}
            USING (${columnName}::text::${newEnumName})
      `, { transaction: t }))
      // Drop old ENUM
      .then(() => queryInterface.sequelize.query(`
        DROP TYPE ${enumName}
      `, { transaction: t }))
      // Rename new ENUM name
      .then(() => queryInterface.sequelize.query(`
        ALTER TYPE ${newEnumName}
          RENAME TO ${enumName}
      `, { transaction: t }))
      .then(() => queryInterface.sequelize.query(`
        ALTER TABLE ${tableName}
          ALTER COLUMN ${columnName}
            SET DEFAULT '${defaultValue}'::${enumName}
      `, { transaction: t }));
  });
}```
</div>
</div>
</p>
<p>and this is my <em>example</em> migration:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>'use strict';

const replaceEnum = require('./utils/replace_enum');

module.exports = {
  up: (queryInterface, Sequelize) => {
    return replaceEnum({
      tableName: 'invoices',
      columnName: 'state',
      enumName: 'enum_invoices_state',
      defaultValue: 'created',
      newValues: ['archived', 'created', 'paid'],
      queryInterface
    });
  },

  down: (queryInterface, Sequelize) => {
    return replaceEnum({
      tableName: 'invoices',
      columnName: 'state',
      enumName: 'enum_invoices_state',
      defaultValue: 'draft',
      newValues: ['archived', 'draft', 'paid', 'sent'],
      queryInterface
    });
  }
};</code>```

Body:
How to correctly drop and then recreate ENUM type with sequelize for Postgres in migrations? For example this migration doesn't drop enum_Users_status enum... so any attempts to recreate/change status values after they have been once created fail.

module.exports = {
    up: function (queryInterface, DataTypes) {
        queryInterface.createTable('Users', {
            //...
            status: {
                type: DataTypes.ENUM,
                values: [
                    'online',
                    'offline',
                ],
                defaultValue: 'online'
            }
            //...
        })
    },

    down: function (queryInterface) {
        queryInterface.dropTable('Users')
    },
}

Eventually i did manage to delete the enum type inside down, but then up migration (which is supposed to create this status enum from scratch) fails, saying something like public.enum_Users_status enum type doesn't exist..

Body:
UPDATE: I have used this in three projects up to now, so I decided to create a npm module: https://www.npmjs.com/package/sequelize-replace-enum-postgres

I made a utility to do this, hope you it this helpful.

utils/replace_enum.js:

'use strict';

/**
 * Since PostgreSQL still does not support remove values from an ENUM,
 * the workaround is to create a new ENUM with the new values and use it
 * to replace the other.
 *
 * @param {String} tableName
 * @param {String} columnName
 * @param {String} defaultValue
 * @param {Array}  newValues
 * @param {Object} queryInterface
 * @param {String} enumName - Optional.
 *
 * @return {Promise}
 */
module.exports = function replaceEnum({
  tableName,
  columnName,
  defaultValue,
  newValues,
  queryInterface,
  enumName = `enum_${tableName}_${columnName}`
}) {
  const newEnumName = `${enumName}_new`;

  return queryInterface.sequelize.transaction((t) => {
    // Create a copy of the type
    return queryInterface.sequelize.query(`
      CREATE TYPE ${newEnumName}
        AS ENUM ('${newValues.join('\', \'')}')
    `, { transaction: t })
      // Drop default value (ALTER COLUMN cannot cast default values)
      .then(() => queryInterface.sequelize.query(`
        ALTER TABLE ${tableName}
          ALTER COLUMN ${columnName}
            DROP DEFAULT
      `, { transaction: t }))
      // Change column type to the new ENUM TYPE
      .then(() => queryInterface.sequelize.query(`
        ALTER TABLE ${tableName}
          ALTER COLUMN ${columnName}
            TYPE ${newEnumName}
            USING (${columnName}::text::${newEnumName})
      `, { transaction: t }))
      // Drop old ENUM
      .then(() => queryInterface.sequelize.query(`
        DROP TYPE ${enumName}
      `, { transaction: t }))
      // Rename new ENUM name
      .then(() => queryInterface.sequelize.query(`
        ALTER TYPE ${newEnumName}
          RENAME TO ${enumName}
      `, { transaction: t }))
      .then(() => queryInterface.sequelize.query(`
        ALTER TABLE ${tableName}
          ALTER COLUMN ${columnName}
            SET DEFAULT '${defaultValue}'::${enumName}
      `, { transaction: t }));
  });
}

and this is my example migration:

'use strict';

const replaceEnum = require('./utils/replace_enum');

module.exports = {
  up: (queryInterface, Sequelize) => {
    return replaceEnum({
      tableName: 'invoices',
      columnName: 'state',
      enumName: 'enum_invoices_state',
      defaultValue: 'created',
      newValues: ['archived', 'created', 'paid'],
      queryInterface
    });
  },

  down: (queryInterface, Sequelize) => {
    return replaceEnum({
      tableName: 'invoices',
      columnName: 'state',
      enumName: 'enum_invoices_state',
      defaultValue: 'draft',
      newValues: ['archived', 'draft', 'paid', 'sent'],
      queryInterface
    });
  }
};


问:
AngularJS + bootstrap carousel help to display all the images
I have an array of objects, where I have the url of the image. I need to display these images in carousel:

```<code><div class="item active">
    <div class="row cst-carouselImg">
        <div class="col-sm-3 col-xs-6" ng-repeat="image in pack.hotels.current.hotelImages | limitTo:'4'">
            <a href="#"><img
                         ng-src="<?php
                         echo 'http://photos.hotelbeds.com/giata/';
                         ?>{{image.path}}"
                         alt="Image" class="img-responsive"></a>
        </div>
    </div>
</div>
</code>```

At this point I have only the first 4 pictures from the array. Next I display the next 4 images from the array:

```<code><div class="item">
     <div class="row cst-carouselImg">
         <div class="col-sm-3 col-xs-6" ng-repeat="image in pack.hotels.current.hotelImages" ng-if="$index > 3 && $index <8">
             <a href="#"><img
                         ng-src="<?php echo
                         'http://photos.hotelbeds.com/giata/';
                         ?>{{image.path}}"
                         alt="Image" class="img-responsive"></a>
         </div>
    </div>
</div>
</code>```

How can I display all the images using ng-repeat instead of manually adding
 and setting manually $index?

答:
If I understood you correctly you are aiming at having a nested ng-repeat, one for the items and one for the images. Let me know if I misunderstood you or you need some clarifications. Please see this snippet below:

var app = angular.module("app", []);

app.controller('exampleCtrl', function($scope){
  $scope.hotels= [
    [
      {
        path: "hotel1 path1",
        otherprop: true
      },
      {
        path: "hotel1 path2",
        otherprop: false
      },
      {
        path: "hotel1 path3",
        otherprop: true
      }
    ],
    [
      {
        path: "hotel2 path1",
        otherprop: true
      },
      {
        path: "hotel2 path2",
        otherprop: true
      }
    ],
    [
      {
        path: "hotel3 path1",
        otherprop: false
      },
      {
        path: "hotel3 path2",
        otherprop: false
      },
      {
        path: "hotel3 path3",
        otherprop: false
      },
      {
        path: "hotel3 path4",
        otherprop: true
      }
    ]
  ];

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="exampleCtrl">
    <div class="item" ng-repeat="hotel in hotels">
      <p>This is Hotel #{{$index+1}}</p>
         <div class="row cst-carouselImg">
             <div class="col-sm-3 col-xs-6" ng-repeat="image in hotel">

                   <img ng-src="{{image.path}}" class="img-responsive" alt="(this is alt text)"/>
                   Image {{$index+1}}'s path: {{image.path}}

             </div>
        </div>
    </div>
  </div>
</div></code>```

Body:
I have an array of objects, where I have the url of the image. I need to display these images in carousel:

            <img
                         ng-src="<?php
                         echo 'http://photos.hotelbeds.com/giata/';
                         ?>{{image.path}}"
                         alt="Image" class="img-responsive">

At this point I have only the first 4 pictures from the array. Next I display the next 4 images from the array:

 3 && $index <8">
             <img
                         ng-src="<?php echo
                         'http://photos.hotelbeds.com/giata/';
                         ?>{{image.path}}"
                         alt="Image" class="img-responsive">

How can I display all the images using ng-repeat instead of manually adding
 and setting manually $index?

Body:
If I understood you correctly you are aiming at having a nested ng-repeat, one for the items and one for the images. Let me know if I misunderstood you or you need some clarifications. Please see this snippet below:

var app = angular.module("app", []);

app.controller('exampleCtrl', function($scope){
  $scope.hotels= [
    [
      {
        path: "hotel1 path1",
        otherprop: true
      },
      {
        path: "hotel1 path2",
        otherprop: false
      },
      {
        path: "hotel1 path3",
        otherprop: true
      }
    ],
    [
      {
        path: "hotel2 path1",
        otherprop: true
      },
      {
        path: "hotel2 path2",
        otherprop: true
      }
    ],
    [
      {
        path: "hotel3 path1",
        otherprop: false
      },
      {
        path: "hotel3 path2",
        otherprop: false
      },
      {
        path: "hotel3 path3",
        otherprop: false
      },
      {
        path: "hotel3 path4",
        otherprop: true
      }
    ]
  ];

});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="exampleCtrl">
    <div class="item" ng-repeat="hotel in hotels">
      <p>This is Hotel #{{$index+1}}</p>
         <div class="row cst-carouselImg">
             <div class="col-sm-3 col-xs-6" ng-repeat="image in hotel">
                 <a href="#">
                   <img ng-src="{{image.path}}" class="img-responsive" alt="(this is alt text)"/>
                   Image {{$index+1}}'s path: {{image.path}}
                 </a>
             </div>
        </div>
    </div>
  </div>
</div>