问:
How to get non matching records in sql server in same table?
I have a table say StudentBillDetails and in this table data is saved annually and yrid is referenced to some other table. Now I am stuck with a problem. I want to retrieve non matching records as described below.

```<code>Stid    BillNo  Yrid
1        525    3
1        525    1
1        525    4
2        443    4
2        442    1
2        443    3
</code>```

In above given table structure as you can see for three years StId 1 has same value but StId 2 has a confliction in Yrid 1. So I want to get these type of records.

答:
If you just want to flag Stid values which have conflicts then the following simple query should work:

```<code>SELECT Stid
FROM yourTable
GROUP BY Stid
HAVING COUNT(DISTINCT BillNo) > 1
</code>```

If you want the entire records you could try joining your table to the above query:

```<code>SELECT t1.*
FROM yourTable t1
INNER JOIN
( SELECT Stid FROM yourTable GROUP BY Stid HAVING COUNT(DISTINCT BillNo) > 1 ) t2
    ON t1.Stid = t2.Stid
</code>```

Body:
I have a table say StudentBillDetails and in this table data is saved annually and yrid is referenced to some other table. Now I am stuck with a problem. I want to retrieve non matching records as described below.

Stid    BillNo  Yrid
1        525    3
1        525    1
1        525    4
2        443    4
2        442    1
2        443    3

In above given table structure as you can see for three years StId 1 has same value but StId 2 has a confliction in Yrid 1. So I want to get these type of records.

Body:
If you just want to flag Stid values which have conflicts then the following simple query should work:

SELECT Stid
FROM yourTable
GROUP BY Stid
HAVING COUNT(DISTINCT BillNo) > 1

If you want the entire records you could try joining your table to the above query:

SELECT t1.*
FROM yourTable t1
INNER JOIN
( SELECT Stid FROM yourTable GROUP BY Stid HAVING COUNT(DISTINCT BillNo) > 1 ) t2
    ON t1.Stid = t2.Stid


来源: stackexchange

问:
Itext to update PDF form with multiple fields with same Field Name
I have a requirement where i have to populate values in a PDF Form using Itext.

the Form i have has multiple fields with the same field names.
The Concept is to populate same value in case the PDF form field name is common.

so if there is are 2 or more fields with the name txtSysTime, then the code should fill the system time in all the fields.

My question is basically

Is this kind of functionality supported at all by Itext?

If it is Possible then how can we do the same.

I am using the below code for attempting the same:

```<code>PdfReader pdfTemplate = new PdfReader(inputFilePath);
FileOutputStream fileOutputStream = new FileOutputStream(outputFilePath);
ByteArrayOutputStream out = new ByteArrayOutputStream();
PdfStamper stamper = new PdfStamper(pdfTemplate, fileOutputStream);
stamper.setFormFlattening(true);
stamper.getAcroFields().setField("TextBox", "value filled");
</code>```

With this code the value in the first field with the same name is populated correctly but the rest of it is left blank.

Please help

答:
itext is using widget annotation, for multiple field with same name..means for duplicate field , name will one but co ordinate will be multiple.

bellow code will help you..

```<code> InputStream pdfFileStream = new FileInputStream(file);
        PdfReader reader = new PdfReader(pdfFileStream);
        PdfStamper stamper = null;

        try {
            stamper = new PdfStamper(reader, tempOS, '\0');

        } catch (DocumentException e1) {
            e1.printStackTrace();
        }

        AcroFields form = stamper.getAcroFields();
        Object[] keys = form.getFields().keySet().toArray();

        for (Entry<String, AcroFields.Item> entry : fields.entrySet()) {

        String docFieldName = entry.getKey();
            List<FieldPosition> fieldPosition = form.getFieldPositions(docFieldName); // for multiple filed with same name  size and co ordinate  will more then 1..
            for(int i=0;i<fieldPosition.size();i++) {
            Rectangle position = fieldPosition.get(i).position;
            float left = position.getLeft();
            float top = position.getTop();
            float width = position.getWidth();
            float height = position.getHeight();
            int currentPage = fieldPosition.get(i).page;
            ........................here you can set value to list..

            }

        }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a requirement where i have to populate values in a PDF Form using Itext.

the Form i have has multiple fields with the same field names.
The Concept is to populate same value in case the PDF form field name is common.

so if there is are 2 or more fields with the name txtSysTime, then the code should fill the system time in all the fields.

My question is basically

Is this kind of functionality supported at all by Itext?

If it is Possible then how can we do the same.

I am using the below code for attempting the same:

PdfReader pdfTemplate = new PdfReader(inputFilePath);
FileOutputStream fileOutputStream = new FileOutputStream(outputFilePath);
ByteArrayOutputStream out = new ByteArrayOutputStream();
PdfStamper stamper = new PdfStamper(pdfTemplate, fileOutputStream);
stamper.setFormFlattening(true);
stamper.getAcroFields().setField("TextBox", "value filled");

With this code the value in the first field with the same name is populated correctly but the rest of it is left blank.

Please help

Body:
itext is using widget annotation, for multiple field with same name..means for duplicate field , name will one but co ordinate will be multiple.

bellow code will help you..

 InputStream pdfFileStream = new FileInputStream(file);
        PdfReader reader = new PdfReader(pdfFileStream);
        PdfStamper stamper = null;

        try {
            stamper = new PdfStamper(reader, tempOS, '\0');

        } catch (DocumentException e1) {
            e1.printStackTrace();
        }

        AcroFields form = stamper.getAcroFields();
        Object[] keys = form.getFields().keySet().toArray();

        for (Entry<String, AcroFields.Item> entry : fields.entrySet()) {

        String docFieldName = entry.getKey();
            List<FieldPosition> fieldPosition = form.getFieldPositions(docFieldName); // for multiple filed with same name  size and co ordinate  will more then 1..
            for(int i=0;i<fieldPosition.size();i++) {
            Rectangle position = fieldPosition.get(i).position;
            float left = position.getLeft();
            float top = position.getTop();
            float width = position.getWidth();
            float height = position.getHeight();
            int currentPage = fieldPosition.get(i).page;
            ........................here you can set value to list..

            }

        }


问:
Adding JPA-Connection in Eclipse
After 5 hours of trying and not finding any solution to my problem, maybe you guys can help me. I´ve been trying to add a database connection to my eclipse JPA-project, but the window in Eclipse won´t let me pass on:

I am using Eclipse Link 2.5.2 and JPA 2.1 with the newest Eclipse Neon release, my Database is an MSSQL-Server 2012. I have implemented a JDBC connection, which  works just fine (to make sure the Server-Ports are open and the connection-URL etc. is correct).

If i want to add a new connection with new->other->Connection Profiles->Connection Profile in my JPA-Project. Eclipse lets me choose the Connection Profile Type where I select SQL Server, then I define a new Driver with New Driver Definition, where I take Microsoft SQL Server 2012 JDBC Driver, add the sqljdbc4.jar (which is located in my lib folder and added to the build path). Lastly I add the connection URL and the other preferences. After I click OK, I cannot move on from there because the buttons are disabled. Did anyone experienced the same problem or knows a solution for this? Thanks in advance!

答:
Do not use "Microsoft SQL Server ..." driver (there seems to be a bug here in Eclipse, as I tested the same procedure w/ MySQL & it worked just fine), so instead use "Generic JDBC Driver"

Type in name (& optional description)

Edit driver definition (Click on triangle icon)

2.1 Jar List tab - Add in path to the driver jar file

2.2 Properties tab -

2.2.1 - Connection URL : jdbc:sqlserver://localhost:50147  (MS Sql Server does not necessarily use the default port 1443 & allocates a listening port dynamically - see How to Identify port number of SQL server (#2) for how to determine which port is being used)

2.2.2 - Database name :  "Your database name"

2.2.3 - Driver class : com.microsoft.sqlserver.jdbc.SQLServerDriver

2.2.4 - UserID  :  "myuserid"

2.2.5 - Password :

After this the "Test Connection" button is active & can be clicked & returns "Ping succeeded!".

I also had to do the below 3 things for MS Sql Server :
(My windows authentication login i.e. domain\login did not work)

In SQL Server Configuration Manager - Enable ALL TCP/IP protocols for

1.1 SQL Native Client Configuration / Client Protocols, and,

1.2 SQL Server Network Configuration / Protocols for SQLEXPRESS
(Apparently TCP/IP was disable by default for my MS Sql Server)

In MS Sqlserver Mgmt Studio, in Object Explorer

1.1 Under Security - Create a new login "myuserid" (password : ) & assign appropriate default db, etc. to it

1.2 Under "Your database name" - Create a new user "myuserid" & assign this user to the login "myuserid" above

In MS Sqlserver Mgmt Studio, in Object Explorer
Under "Your datatbase name", rt. click, "Properties" | "Permissions" | "View Server Permissions" | "Security" | "Server Authentication" - select "SQL Server and Windows Authentication Mode".  Restart the SQL Server.

Press the "Test Connection" button & it'll say "Ping Succeeded!"  This can also be done in Eclipse's Database perspective (for create a new connection) as the same setup windows are used there as well.

Title: Adding JPA-Connection in Eclipse


问:
Keyboard will appeared automatically in ios 8.3 while displaying alertview or alertcontroller
I have updated Xcode 6.3 and ios8.3 check my code. then it gives me weird result.

here is first screen of my demo app. here is one textfield. when I type somethin in textfield keyboard open.

after typing completed. I have clicked on show alert button. I have displayed alert and output will be following.

After click on cancel.
I have displayed another alert then weird result keyboard should not open but when click on cancel button. display another alert and keyboard will appear automatically.

here is next screen output

following is the code

```<code>- (IBAction)MethodShowAlert:(id)sender
 {

[tmptxtField resignFirstResponder];
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Check Alert textField" message:@"keyboard should not be open" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:nil];
[alert show];
 }

 - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  {
    [self showCustomAlertWithTitle:nil];
  }

-(void)showCustomAlertWithTitle:(NSString *)title{
      UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Now Check" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];

      [alertView show]
  }
</code>```

答:
Replace your alert method from below method.

UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:messege title message:message preferredStyle:UIAlertControllerStyleAlert];

```<code>UIAlertAction *cancelAction = [UIAlertAction
                               actionWithTitle:@"OK"
                               style:UIAlertActionStyleCancel
                               handler:^(UIAlertAction *action)
                               {

                               }];
[alertVC addAction:cancelAction];

[[[[[UIApplication sharedApplication] windows] objectAtIndex:0] rootViewController] presentViewController:alertVC animated:YES completion:^{

}];
</code>```

Body:
I have updated Xcode 6.3 and ios8.3 check my code. then it gives me weird result.

here is first screen of my demo app. here is one textfield. when I type somethin in textfield keyboard open.

after typing completed. I have clicked on show alert button. I have displayed alert and output will be following.

After click on cancel.
I have displayed another alert then weird result keyboard should not open but when click on cancel button. display another alert and keyboard will appear automatically.

here is next screen output

following is the code

- (IBAction)MethodShowAlert:(id)sender
 {

[tmptxtField resignFirstResponder];
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Check Alert textField" message:@"keyboard should not be open" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:nil];
[alert show];
 }

 - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  {
    [self showCustomAlertWithTitle:nil];
  }

-(void)showCustomAlertWithTitle:(NSString *)title{
      UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Now Check" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];

      [alertView show]
  }

Body:
Replace your alert method from below method.

UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:messege title message:message preferredStyle:UIAlertControllerStyleAlert];

UIAlertAction *cancelAction = [UIAlertAction
                               actionWithTitle:@"OK"
                               style:UIAlertActionStyleCancel
                               handler:^(UIAlertAction *action)
                               {

                               }];
[alertVC addAction:cancelAction];

[[[[[UIApplication sharedApplication] windows] objectAtIndex:0] rootViewController] presentViewController:alertVC animated:YES completion:^{

}];


问:
Computer Vision: Simple Question - what are 'side lobes'?
This is a very trivial question!!

In some computer vision literature, side-lobes are mentioned.. what are they?.... Can't seem to find anywhere that actually says what they are :S.

Thanks :).

答:
This is a term from antenna theory. Antennas broadcast radiation (radio, microwave, light, infrared) in a certain pattern. Generally, there will be a preferred direction and most of the energy will be in that 'main lobe'. However, there generally exists secondary directions ('side lobes') of energy transmission. Some times, side lobes are a not ideal and are engineered to a minimum. Other times, side lobes can be an advantage and are enhanced.

Bob

ContentLicense: CC BY-SA 2.5


问:
Do I need to free/release Observable object after I use it?
Do I need to free/release Observable object after I use it in case Observable object is not garbaged by GC? I didn't find any article to mention it. Is Observable object garbaged by GC automatically?</p>

```<code> Observable.create(new ObservableOnSubscribe<Boolean>() {
        @Override
        public void subscribe(ObservableEmitter<Boolean> e) throws Exception {
            boolean connected = true;
            //my logic code here
            e.onNext(connected);
            e.onComplete();
            e.setCancellable(null);
            //Do I need to do some extra release/free Observable object work in case Observable object is not garbaged by GC?
        }
    }).subscribeOn(Scheduler.ioThread())
            .observeOn(Scheduler.mainThread())
            .subscribe(new Consumer<Boolean>() {
                @Override
                public void accept(Boolean connected) throws Exception {
                    //my logic code here.
                    //Do I need to do some extra release/free Observable object work in case Observable object is not garbaged by GC?
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) throws Exception {
                    //my logic code here.
                    //Do I need to do some extra release/free Observable object work in case Observable object is not garbaged by GC?
                }
            });
</code>```

答: In most cases we will not need to explicitly call the unsubscribe method unless we want to cancel early or our Observable has a longer lifespan than our subscription. The default behavior of Observable operators is to dispose of the subscription as soon as .complete() or .error() messages are published. Keep in mind that RxJS was designed to be used in a "fire and forget" fashion most of the time. read</p>

Body:
Do I need to free/release Observable object after I use it in case Observable object is not garbaged by GC? I didn't find any article to mention it. Is Observable object garbaged by GC automatically?

 Observable.create(new ObservableOnSubscribe<Boolean>() {
        @Override
        public void subscribe(ObservableEmitter<Boolean> e) throws Exception {
            boolean connected = true;
            //my logic code here
            e.onNext(connected);
            e.onComplete();
            e.setCancellable(null);
            //Do I need to do some extra release/free Observable object work in case Observable object is not garbaged by GC?
        }
    }).subscribeOn(Scheduler.ioThread())
            .observeOn(Scheduler.mainThread())
            .subscribe(new Consumer<Boolean>() {
                @Override
                public void accept(Boolean connected) throws Exception {
                    //my logic code here.
                    //Do I need to do some extra release/free Observable object work in case Observable object is not garbaged by GC?
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) throws Exception {
                    //my logic code here.
                    //Do I need to do some extra release/free Observable object work in case Observable object is not garbaged by GC?
                }
            });


问:
"Build Periodically" with a Multi-branch Pipeline in Jenkins
I'm running Jenkins 2 with the Pipeline plugin. I have setup a Multi-branch Pipeline project where each branch (master, develop, etc.) has a Jenkinsfile in the root. Setting this up was simple. However, I'm at a loss for how to have each branch run periodically (not the branch indexing), even when the code does not change. What do I need to put in my Jenkinsfile to enable periodic builds?</p>

答:
If you use a declarative style Pipeline and only want to trigger the build on a specific branch you can do something like this:

```<code>String cron_string = BRANCH_NAME == "master" ? "@hourly" : ""

pipeline {
  agent none
  triggers { cron(cron_string) }
  stages {
    // do something
  }
}
</code>```

Found on Jenkins Jira

Body:
If you use a declarative style Pipeline and only want to trigger the build on a specific branch you can do something like this:

String cron_string = BRANCH_NAME == "master" ? "@hourly" : ""

pipeline {
  agent none
  triggers { cron(cron_string) }
  stages {
    // do something
  }
}

Found on Jenkins Jira


问:
Collapsing layout during scrolling in Android
I would like to have custom view collapsed with a transition during scrolling.

I have AppBarLayout with a Toolbar inside. Below that there is a custom view that I want to collapse.

Below custom view there is a NestedScrollView with LinearLayout.

Toolbar is green, custom layout is pink and scroll with linear is gray:

After scrolling down:

```<code><android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
    </android.support.design.widget.AppBarLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="170dp"
        android:layout_marginTop="?attr/actionBarSize"
        android:background="@drawable/background"
        android:gravity="center">
    </RelativeLayout>

    <ScrollView
        android:id="@+id/scroll"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="170dp"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <include
            layout="@layout/linear"
            android:layout_marginBottom="20dp"
            android:layout_marginTop="20dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </ScrollView>

</android.support.design.widget.CoordinatorLayout>
</code>```

Should I go with custom behavior and CoordinatorLayout or translation with NestedScroll with translation animation?

答:
Use Observable ScrollView library
https://github.com/ksoichiro/Android-ObservableScrollView</p>

Body:
I would like to have custom view collapsed with a transition during scrolling.

I have AppBarLayout with a Toolbar inside. Below that there is a custom view that I want to collapse.

Below custom view there is a NestedScrollView with LinearLayout.

Toolbar is green, custom layout is pink and scroll with linear is gray:

After scrolling down:

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
    </android.support.design.widget.AppBarLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="170dp"
        android:layout_marginTop="?attr/actionBarSize"
        android:background="@drawable/background"
        android:gravity="center">
    </RelativeLayout>

    <ScrollView
        android:id="@+id/scroll"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="170dp"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <include
            layout="@layout/linear"
            android:layout_marginBottom="20dp"
            android:layout_marginTop="20dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </ScrollView>

</android.support.design.widget.CoordinatorLayout>

Should I go with custom behavior and CoordinatorLayout or translation with NestedScroll with translation animation?


问:
Convert a list of minutes into lists of minutes, hours, days and months in python
I have a list of big numbers in minutes and I would like to convert or get from this four lists of minutes, hours, days and months. Lke for example:

```<code>Minutes
21601
30
0
90000
</code>```

Resulting lists:

```<code>Minutes  Hours  Days  Months
1        0      15    0
30       0      0     0
0        0      0     0
0        12     2     2
</code>```

Assumptions will be that a month has exactly 30 days. Also I know i showed them here as columns for simplicity but those will be lists.

Cheers,

答:
Ok, I found a way around, though I don't if this is the nicest way but it seems to work:

```<code># list_minutes -is a list of minutes
minutes=[x % 60 for x in list_minutes]
remeinder1=[x // 60 for x in list_minutes]
hours=[x % 24 for x in remeinder1]
remeinder2=[x // 24 for x in remeinder1]
days=[x % 30 for x in remeinder2]
month=[x % 30 for x in remeinder2]
</code>```

Cheers.

Body:
I have a list of big numbers in minutes and I would like to convert or get from this four lists of minutes, hours, days and months. Lke for example:

Minutes
21601
30
0
90000

Resulting lists:

Minutes  Hours  Days  Months
1        0      15    0
30       0      0     0
0        0      0     0
0        12     2     2

Assumptions will be that a month has exactly 30 days. Also I know i showed them here as columns for simplicity but those will be lists.

Cheers,

Body:
Ok, I found a way around, though I don't if this is the nicest way but it seems to work:

# list_minutes -is a list of minutes
minutes=[x % 60 for x in list_minutes]
remeinder1=[x // 60 for x in list_minutes]
hours=[x % 24 for x in remeinder1]
remeinder2=[x // 24 for x in remeinder1]
days=[x % 30 for x in remeinder2]
month=[x % 30 for x in remeinder2]

Cheers.


问:
How to convert vector to array
How do I convert a std::vector<double> to a double array[]?

答:
We can do this using data() method.  C++11 provides this method.

Code Snippet

```<code>#include<bits/stdc++.h>
using namespace std;

int main()
{
  ios::sync_with_stdio(false);

  vector<int>v = {7, 8, 9, 10, 11};
  int *arr = v.data();

  for(int i=0; i<v.size(); i++)
  {
    cout<<arr[i]<<" ";
  }

  return 0;
}
</code>```

Title: How to convert vector to array

Body:
We can do this using data() method.  C++11 provides this method.

Code Snippet

#include<bits/stdc++.h>
using namespace std;

int main()
{
  ios::sync_with_stdio(false);

  vector<int>v = {7, 8, 9, 10, 11};
  int *arr = v.data();

  for(int i=0; i<v.size(); i++)
  {
    cout<<arr[i]<<" ";
  }

  return 0;
}


问:
Problem with too many try catch
Is it possible to write a method like outType? TryDo(func, out exception, params) that call func(arg1,arg2,arg3,...) which params contains arg1,arg2,arg3,... and then it return func return value and if any exception occurred return null and set the exception?

Can this be done better by another function signature?

for example I have
string Foo1(int i) { return i.ToString()}

void Foo2(int[] a) {throw new Exception();}

and then call

string t = TryDo(Foo1, out ex, {i});

TryDo(Foo2, out ex, {});

-----------Edited------------------

```<code>        string t;
        SomeClass c;
        try
        {
            t = Foo1(4, 2, new OtherClass());
        }
        catch (Exception ex)
        {
            Log(ex);
            if (/*ex has some features*/)
                throw ex;
        }

        try
        {
            Foo2();
        }
        catch (Exception ex)
        {
            Log(ex);
            if (/*ex has some features*/)
                throw ex;
        }
        .
        .
        .
</code>```

I want to make it like this.

```<code>        string t = TryDo(Foo1, out ex, {4, 2, new OtherClass());
        Examine(ex);
        SomeClass c = TryDo(Foo2, out ex, {});
        Examine(ex);
</code>```

答:
if you are having too many try...catch(I can't understand why) you could go for AOP to centralize the Exception handling.

Below you can find a link that explains how to use it:

http://www.codeproject.com/KB/architecture/ExceptionHandlingWithAOP.aspx

Title: Problem with too many try catch

Body:
Is it possible to write a method like outType? TryDo(func, out exception, params) that call func(arg1,arg2,arg3,...) which params contains arg1,arg2,arg3,... and then it return func return value and if any exception occurred return null and set the exception?

Can this be done better by another function signature?

for example I have
string Foo1(int i) { return i.ToString()}

void Foo2(int[] a) {throw new Exception();}

and then call

string t = TryDo(Foo1, out ex, {i});

TryDo(Foo2, out ex, {});

-----------Edited------------------

        string t;
        SomeClass c;
        try
        {
            t = Foo1(4, 2, new OtherClass());
        }
        catch (Exception ex)
        {
            Log(ex);
            if (/*ex has some features*/)
                throw ex;
        }

        try
        {
            Foo2();
        }
        catch (Exception ex)
        {
            Log(ex);
            if (/*ex has some features*/)
                throw ex;
        }
        .
        .
        .

I want to make it like this.

        string t = TryDo(Foo1, out ex, {4, 2, new OtherClass());
        Examine(ex);
        SomeClass c = TryDo(Foo2, out ex, {});
        Examine(ex);


问:
CSS/HTML: Create a glowing border around an Input Field
I want to create some decent inputs for my form, and I would really like to know how TWITTER does their glowing border around their inputs.

Example/Picture of the Twitter border:

I also don't quite know how to create the rounded corners.

答:
$('.form-fild input,.form-fild textarea').focus(function() {
    $(this).parent().addClass('open');
});

$('.form-fild input,.form-fild textarea').blur(function() {
    $(this).parent().removeClass('open');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.open {
  color:red;
}
.form-fild {
 position: relative;
 margin: 30px 0;
}
.form-fild label {
 position: absolute;
 top: 5px;
 left: 10px;
 padding:5px;
}

.form-fild.open label {
 top: -25px;
 left: 10px;
 /*background: #ffffff;*/
}
.form-fild input[type="text"] {
 padding-left: 80px;
}
.form-fild textarea {
 padding-left: 80px;
}
.form-fild.open textarea,
.form-fild.open input[type="text"] {
 padding-left: 10px;
}
textarea,
input[type="text"] {
 padding: 10px;
 width: 100%;
}
textarea,
input,
.form-fild.open label,
.form-fild label {
 -webkit-transition: all 0.2s ease-in-out;
       -moz-transition: all 0.2s ease-in-out;
         -o-transition: all 0.2s ease-in-out;
            transition: all 0.2s ease-in-out;
}</code>```

     <form>

            Name :
            <input type="text">

            Email :
            <input type="text">

            Number :
            <input type="text">

            Message :
            <textarea cols="10" rows="5"></textarea>

    </form>

```

Body:
$('.form-fild input,.form-fild textarea').focus(function() {
    $(this).parent().addClass('open');
});

$('.form-fild input,.form-fild textarea').blur(function() {
    $(this).parent().removeClass('open');
});

.open {
  color:red;
}
.form-fild {
 position: relative;
 margin: 30px 0;
}
.form-fild label {
 position: absolute;
 top: 5px;
 left: 10px;
 padding:5px;
}

.form-fild.open label {
 top: -25px;
 left: 10px;
 /*background: #ffffff;*/
}
.form-fild input[type="text"] {
 padding-left: 80px;
}
.form-fild textarea {
 padding-left: 80px;
}
.form-fild.open textarea,
.form-fild.open input[type="text"] {
 padding-left: 10px;
}
textarea,
input[type="text"] {
 padding: 10px;
 width: 100%;
}
textarea,
input,
.form-fild.open label,
.form-fild label {
 -webkit-transition: all 0.2s ease-in-out;
       -moz-transition: all 0.2s ease-in-out;
         -o-transition: all 0.2s ease-in-out;
            transition: all 0.2s ease-in-out;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
 <div class="row">
     <form>
        <div class="form-fild">
            <label>Name :</label>
            <input type="text">
        </div>
        <div class="form-fild">
            <label>Email :</label>
            <input type="text">
        </div>
        <div class="form-fild">
            <label>Number :</label>
            <input type="text">
        </div>
        <div class="form-fild">
            <label>Message :</label>
            <textarea cols="10" rows="5"></textarea>
        </div>
    </form>
    </div>
</div>


问:
Unable to use Let's Encrypt cert in Telegram bot webhook (Self-Signed cert works fine)
I am trying to setup my Telegram bot webhook using a Let's Encrypt certificate but Telegram keeps saying verification_failed. Browsers, however, are totally fine with new Let's Encrypt certificate.

My self-signed certificate is currently working fine in webhooks on my Ubuntu 17.04 with Nginx web server.

What am i missing?

Current self-signed certificate setup (Works)

I generated my certificate using this command:

```<code>openssl req -newkey rsa:2048 -sha256 -nodes -keyout my-cert.key -x509 -days 365 -out my-cert.pem -subj "/C=CA/ST=Ontario/L=Toronto/O=My Organization/CN=example.org"
</code>```

and Nginx configuration:

```<code>server {
    server_name example.org www.example.org localhost;

    listen 443  ssl;
    listen 8080 ssl;
    listen 8443 ssl;

    ssl_certificate     /etc/nginx/certificates/my-cert.pem;
    ssl_certificate_key /etc/nginx/certificates/my-cert.key;

    ssl_protocols TLSv1.2 TLSv1.1 TLSv1;
    ssl_prefer_server_ciphers on;

    location ~* ^/bots/mybot/webhook/.+$ {
        proxy_pass          http://0.0.0.0:5000;
        proxy_http_version  1.1;
        proxy_set_header    Upgrade $http_upgrade;
        proxy_set_header    Connection keep-alive;
        proxy_set_header    Host $host;
        proxy_cache_bypass  $http_upgrade;
        proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}
</code>```

New Let's Encrypt setup (Works in browsers, Fails in webhooks)

Certificate is generated for my domain using EFF's great certbot.

When setting Telegram's webhook, I use /etc/letsencrypt/live/example.org/cert1.pem file.

This is Nginx configuration I tried:

```<code>server {
    server_name example.org www.example.org localhost;

    listen  80;
    listen  [::]:80;

    root /var/www/html;
    index index.html index.htm index.nginx-debian.html;

    if ($scheme != "https") {
        return 301 https://$host$request_uri;
    }
}

server {
    server_name example.org www.example.org localhost;

    listen 443  ssl;
    listen 8080 ssl;
    listen 8443 ssl;

    ssl_certificate /etc/letsencrypt/live/example.org/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.org/privkey.pem; # managed by Certbot

    ssl_protocols TLSv1.2 TLSv1.1 TLSv1;
    ssl_prefer_server_ciphers on;

    location ~* ^/bots/mybot/webhook/.+$ {
        proxy_pass          http://0.0.0.0:5000;
        proxy_http_version  1.1;
        proxy_set_header    Upgrade $http_upgrade;
        proxy_set_header    Connection keep-alive;
        proxy_set_header    Host $host;
        proxy_cache_bypass  $http_upgrade;
        proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}
</code>```

答:
I tried this a while ago myself with an Apache webserver but on Ubuntu 17.04 too with letsencrypt and it works fine.

You mentioned that you used the setwebhook?url= method with an additional argument (passing the certificate...). Somehow this isn´t needed. You can just enter the url starting with https:// and you are fine.

Body:
I am trying to setup my Telegram bot webhook using a Let's Encrypt certificate but Telegram keeps saying verification_failed. Browsers, however, are totally fine with new Let's Encrypt certificate.

My self-signed certificate is currently working fine in webhooks on my Ubuntu 17.04 with Nginx web server.

What am i missing?

Current self-signed certificate setup (Works)

I generated my certificate using this command:

openssl req -newkey rsa:2048 -sha256 -nodes -keyout my-cert.key -x509 -days 365 -out my-cert.pem -subj "/C=CA/ST=Ontario/L=Toronto/O=My Organization/CN=example.org"

and Nginx configuration:

server {
    server_name example.org www.example.org localhost;

    listen 443  ssl;
    listen 8080 ssl;
    listen 8443 ssl;

    ssl_certificate     /etc/nginx/certificates/my-cert.pem;
    ssl_certificate_key /etc/nginx/certificates/my-cert.key;

    ssl_protocols TLSv1.2 TLSv1.1 TLSv1;
    ssl_prefer_server_ciphers on;

    location ~* ^/bots/mybot/webhook/.+$ {
        proxy_pass          http://0.0.0.0:5000;
        proxy_http_version  1.1;
        proxy_set_header    Upgrade $http_upgrade;
        proxy_set_header    Connection keep-alive;
        proxy_set_header    Host $host;
        proxy_cache_bypass  $http_upgrade;
        proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

New Let's Encrypt setup (Works in browsers, Fails in webhooks)

Certificate is generated for my domain using EFF's great certbot.

When setting Telegram's webhook, I use /etc/letsencrypt/live/example.org/cert1.pem file.

This is Nginx configuration I tried:

server {
    server_name example.org www.example.org localhost;

    listen  80;
    listen  [::]:80;

    root /var/www/html;
    index index.html index.htm index.nginx-debian.html;

    if ($scheme != "https") {
        return 301 https://$host$request_uri;
    }
}

server {
    server_name example.org www.example.org localhost;

    listen 443  ssl;
    listen 8080 ssl;
    listen 8443 ssl;

    ssl_certificate /etc/letsencrypt/live/example.org/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.org/privkey.pem; # managed by Certbot

    ssl_protocols TLSv1.2 TLSv1.1 TLSv1;
    ssl_prefer_server_ciphers on;

    location ~* ^/bots/mybot/webhook/.+$ {
        proxy_pass          http://0.0.0.0:5000;
        proxy_http_version  1.1;
        proxy_set_header    Upgrade $http_upgrade;
        proxy_set_header    Connection keep-alive;
        proxy_set_header    Host $host;
        proxy_cache_bypass  $http_upgrade;
        proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}


问:
disable the list item for empty parent
I have 5 list item which has a tag with class Articles, Blogs, Brochures, Webinars, Whitepapers and have their child content in 'view-content' div.on load it shows blogs and hide the other child.when I chick 'whitepapers' child whitepaper shows and other child will hide(working fine).

I want to add the class 'disable' to the list item as

 for the list which doesn't has the child.In my example 'Brochures' and 'Webinars' have no child so need to add the class 'disable' for the respective list.

(function($) {
  function perspective_type() {
    $(".perspective-list a").click(function(e) {
      e.preventDefault();
      $(".perspective-list a").parent().removeClass('active');
      $('.wrapper .page-perspective').show();
      var href = $(this).attr('href');
      $('.wrapper > :not(.' + href + ')').hide();
      $('.wrapper > .' + href + '').show();
      $(this).parent().addClass('active');
    });
    $(".perspective-list a").mouseover(
      function() {
        $(".perspective-list a").removeClass('hover');
        $(this).parent().addClass('hover');
      });
    $(".perspective-list a").mouseout(
      function() {
        $(".perspective-list a").each(function() {
          $(this).parent().removeClass('hover');
        });
      });
    $('#perspectives .perspectiveReadurl', '#page_perspectives .perspectiveReadurl').find('a').attr('target', '_blank');
  }
  jQuery(document).ready(function($) {
    var href = 'Blogs';
    jQuery('.perspective-list a.' + href + '').parent().addClass('active');
    jQuery('.wrapper > :not(.' + href + ')').hide();
    perspective_type();
  });

})(jQuery)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="perspective-list">
  <ul class="nav nav-justified">
    <li class="">Articles</li>
    <li class="">Blogs</li>
    <li class="">Brochures</li>
    <li class="">Webinars</li>
    <li class="active">Whitepapers</li>
  </ul>
</div>
<div class="view-content">
  <div class="wrapper">
    <div class=" Articles">
      article
    </div>
  </div>
  <div class="wrapper">
    <div class="Blogs">
      Blogs
    </div>
  </div>
  <div class="wrapper">
    <div class="Whitepapers">
      Whitepapers
    </div>
  </div>
</div></code>```

答:
You can .each through the list items, check if more than one elements share the same class. If there isn't any other elements then add a class of disabled.

(function($) {
  function perspective_type() {
    $(".perspective-list a").click(function(e) {
      e.preventDefault();
      $(".perspective-list a").parent().removeClass('active');
      $('.wrapper .page-perspective').show();
      var href = $(this).attr('href');
      $('.wrapper > :not(.' + href + ')').hide();
      $('.wrapper > .' + href + '').show();
      $(this).parent().addClass('active');
    });
    $(".perspective-list a").mouseover(
      function() {
        $(".perspective-list a").removeClass('hover');
        $(this).parent().addClass('hover');
      });
    $(".perspective-list a").mouseout(
      function() {
        $(".perspective-list a").each(function() {
          $(this).parent().removeClass('hover');
        });
      });
    $('#perspectives .perspectiveReadurl', '#page_perspectives .perspectiveReadurl').find('a').attr('target', '_blank');
  }
  var href = 'Blogs';
  jQuery('.perspective-list a.' + href + '').parent().addClass('active');
  jQuery('.wrapper > :not(.' + href + ')').hide();
  perspective_type();

  jQuery(".nav-justified a").each(function() {
    var className = jQuery(this).attr("class");
    var elemCount = jQuery("." + className).length;
    if(elemCount == 1) {
     jQuery(this).parent().addClass("disable");
    }
  });

})(jQuery)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.disable {
 display:none;
}</code>```

Articles

Blogs

Brochures

Webinars

Whitepapers

      article

      Blogs

      Whitepapers

```

Title: disable the list item for empty parent

Body:
I have 5 list item which has a tag with class Articles, Blogs, Brochures, Webinars, Whitepapers and have their child content in 'view-content' div.on load it shows blogs and hide the other child.when I chick 'whitepapers' child whitepaper shows and other child will hide(working fine).

I want to add the class 'disable' to the list item as

 for the list which doesn't has the child.In my example 'Brochures' and 'Webinars' have no child so need to add the class 'disable' for the respective list.

(function($) {
  function perspective_type() {
    $(".perspective-list a").click(function(e) {
      e.preventDefault();
      $(".perspective-list a").parent().removeClass('active');
      $('.wrapper .page-perspective').show();
      var href = $(this).attr('href');
      $('.wrapper > :not(.' + href + ')').hide();
      $('.wrapper > .' + href + '').show();
      $(this).parent().addClass('active');
    });
    $(".perspective-list a").mouseover(
      function() {
        $(".perspective-list a").removeClass('hover');
        $(this).parent().addClass('hover');
      });
    $(".perspective-list a").mouseout(
      function() {
        $(".perspective-list a").each(function() {
          $(this).parent().removeClass('hover');
        });
      });
    $('#perspectives .perspectiveReadurl', '#page_perspectives .perspectiveReadurl').find('a').attr('target', '_blank');
  }
  jQuery(document).ready(function($) {
    var href = 'Blogs';
    jQuery('.perspective-list a.' + href + '').parent().addClass('active');
    jQuery('.wrapper > :not(.' + href + ')').hide();
    perspective_type();
  });

})(jQuery)

Articles

Blogs

Brochures

Webinars

Whitepapers

      article

      Blogs

      Whitepapers

Body:
You can .each through the list items, check if more than one elements share the same class. If there isn't any other elements then add a class of disabled.

(function($) {
  function perspective_type() {
    $(".perspective-list a").click(function(e) {
      e.preventDefault();
      $(".perspective-list a").parent().removeClass('active');
      $('.wrapper .page-perspective').show();
      var href = $(this).attr('href');
      $('.wrapper > :not(.' + href + ')').hide();
      $('.wrapper > .' + href + '').show();
      $(this).parent().addClass('active');
    });
    $(".perspective-list a").mouseover(
      function() {
        $(".perspective-list a").removeClass('hover');
        $(this).parent().addClass('hover');
      });
    $(".perspective-list a").mouseout(
      function() {
        $(".perspective-list a").each(function() {
          $(this).parent().removeClass('hover');
        });
      });
    $('#perspectives .perspectiveReadurl', '#page_perspectives .perspectiveReadurl').find('a').attr('target', '_blank');
  }
  var href = 'Blogs';
  jQuery('.perspective-list a.' + href + '').parent().addClass('active');
  jQuery('.wrapper > :not(.' + href + ')').hide();
  perspective_type();

  jQuery(".nav-justified a").each(function() {
    var className = jQuery(this).attr("class");
    var elemCount = jQuery("." + className).length;
    if(elemCount == 1) {
     jQuery(this).parent().addClass("disable");
    }
  });

})(jQuery)

.disable {
 display:none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="perspective-list">
  <ul class="nav nav-justified">
    <li class=""><a href="Articles" class="Articles">Articles</a></li>
    <li class=""><a href="Blogs" class="Blogs">Blogs</a></li>
    <li class=""><a href="Brochures" class="Brochures">Brochures</a></li>
    <li class=""><a href="Webinars" class="Webinars">Webinars</a></li>
    <li class="active"><a href="Whitepapers" class="Whitepapers">Whitepapers</a></li>
  </ul>
</div>
<div class="view-content">
  <div class="wrapper">
    <div class=" Articles">
      article
    </div>
  </div>
  <div class="wrapper">
    <div class="Blogs">
      Blogs
    </div>
  </div>
  <div class="wrapper">
    <div class="Whitepapers">
      Whitepapers
    </div>
  </div>
</div>


问:
Why does IntelliJ show error for my JavaScript scratch file?
I use scratch files extensively but suddenly today I'm seeing an error. This is making formatting/linting not work or be effective, but the code executes just fine if I run the scratch file.

It does not matter which JavaScript language version I select when creating the file.

Version: IntelliJ Ultimate 2017.1.4

答:
Known issue, please follow WEB-24263 for updates.
For now, I'd suggest choosing 'ECMAScript 6' language when creating new scratch file


问:
Python Memory Error - Numpy Matrix (1568x1568)
I have two very similar programs whose functions differ only slightly. Within both programs, a 1568 x 1568 numpy matrix is produced. In one of my programs, this matrix creation works perfectly, however, in the other, I receive a MemoryError. Error message below:

```<code>    a = empty(shape, dtype, order)
MemoryError
</code>```

Also, when I copy the section of code that creates the matrix, from the program that does work, into its own python file, this too produces the MemoryError.

The code below reproduces the error:

```<code>import matplotlib.pyplot as plt
import numpy as np

Z = np.zeros((1568, 1568))
fig = plt.figure(figsize=(6,6))
X = np.arange(0, 1568, 0.1)
Y = np.arange(0, 1568, 0.1)
X, Y = np.meshgrid(X, Y)

plt.contourf(X, Y, Z)
plt.show()
</code>```

I don't think this is caused by the fact that I'm using 32 bit python rather than 64 bit (as is the case with others who have posted questions with similar problems), purely because of the fact that this does work in my other program and the matrix should only be using 9.83 MB of RAM anyway.

Any help would be greatly appreciated.

答: Thanks to the help in the comments, I realised that the code in the program that I said was working, wasn't actually exactly the same as the other program and had a matrix of size 156.8 x 156.8 rather than 1568 x 1568. In the full code, I have variables rather than numbers in the matrix set up, so this wasn't immediately obvious. I changed the program giving the error to match this and the problem was solved.</p>

Body:
I have two very similar programs whose functions differ only slightly. Within both programs, a 1568 x 1568 numpy matrix is produced. In one of my programs, this matrix creation works perfectly, however, in the other, I receive a MemoryError. Error message below:

    a = empty(shape, dtype, order)
MemoryError

Also, when I copy the section of code that creates the matrix, from the program that does work, into its own python file, this too produces the MemoryError.

The code below reproduces the error:

import matplotlib.pyplot as plt
import numpy as np

Z = np.zeros((1568, 1568))
fig = plt.figure(figsize=(6,6))
X = np.arange(0, 1568, 0.1)
Y = np.arange(0, 1568, 0.1)
X, Y = np.meshgrid(X, Y)

plt.contourf(X, Y, Z)
plt.show()

I don't think this is caused by the fact that I'm using 32 bit python rather than 64 bit (as is the case with others who have posted questions with similar problems), purely because of the fact that this does work in my other program and the matrix should only be using 9.83 MB of RAM anyway.

Any help would be greatly appreciated.


问:
Adding Methods to Constructors
Refactor the carlike function in a way that allows us to use the method calling syntax with "dot access".

var carlike = function(obj, loc) {
  obj.loc = loc;
  return obj;
};

var move = function(car) {
  car.loc++;
};

var amy = carlike({}, 1);
var ben = carlike({}, 9);

/*
Here we want to call move with "dot access"

amy.move();
ben.move();
*/```
</div>
</div>
</p>

<p><strong>THIS IS WHAT I'VE DONE...</strong></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>var carlike = function(obj, loc) {
  obj.loc = loc;
  obj.move = move;//CHANGE#1
  return obj;
};

var move = function(car) {
  car.loc++;
};

var amy = carlike({}, 1);
var ben = carlike({}, 9);
amy.move();//CHANGE#2
ben.move();//CHANGE#3</code>```

BUT IT WON'T WORK IT'S HAVING ERROR REGARDING LOCATION VARIABLE WHICH WAS WORKING GOOD UNTIL!

Thank You in Advance ☺

答:
If you want to refer to the current created object, you have to define the method inside the function which is constructing the object. like following code:

var carlike = function(obj, loc) {
  obj.loc = loc;
  obj.move = function() {
     obj.loc++;
     console.log( obj.loc );
  }
  return obj;
};

var amy = carlike({}, 1);
var ben = carlike({}, 9);
amy.move();//CHANGE#2
ben.move();//CHANGE#3```
</div>
</div>

as obj is created at runtime. if you refer the method externally like previous code snippets, the javascript interpreter does not know which object you are referring. yes there is an exception to that, like you can call the method as follows:</p>

```amy.move(amy);
ben.move(ben);
```

but writing that kind of code doesn't make any sense.

Title: Adding Methods to Constructors

Body:
Refactor the carlike function in a way that allows us to use the method calling syntax with "dot access".

var carlike = function(obj, loc) {
  obj.loc = loc;
  return obj;
};

var move = function(car) {
  car.loc++;
};

var amy = carlike({}, 1);
var ben = carlike({}, 9);

/*
Here we want to call move with "dot access"

amy.move();
ben.move();
*/

THIS IS WHAT I'VE DONE...

var carlike = function(obj, loc) {
  obj.loc = loc;
  obj.move = move;//CHANGE#1
  return obj;
};

var move = function(car) {
  car.loc++;
};

var amy = carlike({}, 1);
var ben = carlike({}, 9);
amy.move();//CHANGE#2
ben.move();//CHANGE#3

BUT IT WON'T WORK IT'S HAVING ERROR REGARDING LOCATION VARIABLE WHICH WAS WORKING GOOD UNTIL!

Thank You in Advance ☺

Body:
If you want to refer to the current created object, you have to define the method inside the function which is constructing the object. like following code:

var carlike = function(obj, loc) {
  obj.loc = loc;
  obj.move = function() {
     obj.loc++;
     console.log( obj.loc );
  }
  return obj;
};

var amy = carlike({}, 1);
var ben = carlike({}, 9);
amy.move();//CHANGE#2
ben.move();//CHANGE#3

as obj is created at runtime. if you refer the method externally like previous code snippets, the javascript interpreter does not know which object you are referring. yes there is an exception to that, like you can call the method as follows:

amy.move(amy);
ben.move(ben);

but writing that kind of code doesn't make any sense.


问:
how to create two rounded bordered uiimage in swift
Could anyone suggest me how could I create two rounded border uiimage like shown in this picture.

Is there any available library that I could use?

答:
```<code>import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var secondView: UIView!
    @IBOutlet weak var imgView: UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()
        imgView.layer.cornerRadius = imgView.frame.size.height/2
         secondView.layer.cornerRadius = secondView.frame.size.height/2
        imgView.layer.borderWidth = 5.0
        imgView.layer.borderColor = UIColor.red.cgColor
        imgView.clipsToBounds = true
         secondView.clipsToBounds = true
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
</code>```


问:
deploy rails app on heroku
Hey
I'm afraid I should ask a rookie question :

After push my app to heroku. I got error of no database

This is the command I use

heroku rake db:migrate

My app can run locally with no problem, but I notice the database file only in development.
and my test evironment only use rails server and localhost:3000

anyone tell me how to make the database in production mode in heroku.

Thanks

here's the heroku log file:

here's the logs

Started GET "/drummers/1" for
  221.9.247.14 at Sat Dec 18 06:17:40 -0800 2010  Processing by DrummersController#show as HTML
  Parameters: {"id"=>"1"}  Completed in
  167ms

ActiveRecord::RecordNotFound (Couldn't
  find Drummer with ID=1):
  app/controllers/drummers_controller.rb:11:in
  `show'

I think it may due to the datebase,config file, become I use sqlite3 in local test, and all the migration file is development prefix,

答:
Heroku creates a database for each application deployed to it (no need to run heroku rake db:create. Here are the commands you should be using to deploy a Rails application to Heroku:

```<code>git init
git add .
git commit -m "initial import"
heroku create
git push heroku master
heroku rake db:migrate
heroku open
</code>```

Title: deploy rails app on heroku

Body:
Heroku creates a database for each application deployed to it (no need to run heroku rake db:create. Here are the commands you should be using to deploy a Rails application to Heroku:

git init
git add .
git commit -m "initial import"
heroku create
git push heroku master
heroku rake db:migrate
heroku open


问:
Using env variable in Spring Boot's application.properties
We are working on a Spring Boot web application, and the database we are using is MySQL;

the setup we have is we first test it locally (means we need to install MySQL on our PC);

then we push to Bitbucket;

Jenkins automatically detects the new push to Bitbucket and does a build on it (for Jenkins mvn build to pass we also need to install MySQL on the virtual machines that is running Jenkins).

if Jenkins build passes  we push the code to our application on OpenShift (using the Openshift deployment plugin on Jenkins).

The problem we have, as you may have already figured it out, is that:

in application.properties we can not hard code the MySQL info. Since our project will be running in 3 different places (local, Jenkins, and OpenShift), we need to make the datasource field dynamic in application.properties (we know there are different ways of doing it but we are working on this solution for now).

```<code>  spring.datasource.url =
  spring.datasource.username =
  spring.datasource.password =
</code>```

The solution we came up with is we create system environment variables locally and in the Jenkins VM (naming them the same way OpenShift names them), and assigning them the right values respectively:

```<code>export OPENSHIFT_MYSQL_DB_HOST="jdbc:mysql://localhost"
export OPENSHIFT_MYSQL_DB_PORT="3306"
export OPENSHIFT_MYSQL_DB_USERNAME="root"
export OPENSHIFT_MYSQL_DB_PASSWORD="123asd"
</code>```

We have done this and it works. We have also checked with Map<String, String> env = System.getenv(); that the environment variables can be made into java variables as such:

```<code>String password = env.get("OPENSHIFT_MYSQL_DB_PASSWORD");
String userName = env.get("OPENSHIFT_MYSQL_DB_USERNAME");
String sqlURL = env.get("OPENSHIFT_MYSQL_DB_HOST");
String sqlPort = env.get("OPENSHIFT_MYSQL_DB_PORT");
</code>```

Now the only thing left is we need to use these java variables in our application.properties, and that is what we are having trouble with.

In which folder, and how, do we need to assign the password, userName, sqlURL, and sqlPort variables for application.properties to be able to see them and how do we include them in application.properties?

We have tried many things one of them being:

```<code>spring.datasource.url = ${sqlURL}:${sqlPort}/"nameofDB"
spring.datasource.username = ${userName}
spring.datasource.password = ${password}
</code>```

No luck so far.  We are probably not putting these environment variables in the right class/folder or are using them incorrectly in application.properties.

答:
Maybe I write this too late, but I have gotten the similar problem when I have tried to override methods for reading properties.

My problem have been:
1) Read property from env if this property has been set in env
2) Read property from system property if this property have been setted in system property
3) And last, read from application properties.

So, for resolving this problem I go to my bean configuration class

```<code>@Validated
@Configuration
@ConfigurationProperties(prefix = ApplicationConfiguration.PREFIX)
@PropertySource(value = "${application.properties.path}", factory = PropertySourceFactoryCustom.class)
@Data // lombok
public class ApplicationConfiguration {

    static final String PREFIX = "application";

    @NotBlank
    private String keysPath;

    @NotBlank
    private String publicKeyName;

    @NotNull
    private Long tokenTimeout;

    private Boolean devMode;

    public void setKeysPath(String keysPath) {
        this.keysPath = StringUtils.cleanPath(keysPath);
    }
}
</code>```

And overwrite factory in @PropertySource. And then I have created my own implementation for reading properties.

```<code>    public class PropertySourceFactoryCustom implements PropertySourceFactory {

        @Override
        public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
            return name != null ? new PropertySourceCustom(name, resource) : new PropertySourceCustom(resource);
        }

    }
</code>```

And created PropertySourceCustom

```<code>public class PropertySourceCustom extends ResourcePropertySource {

    public LifeSourcePropertySource(String name, EncodedResource resource) throws IOException {
        super(name, resource);
    }

    public LifeSourcePropertySource(EncodedResource resource) throws IOException {
        super(resource);
    }

    public LifeSourcePropertySource(String name, Resource resource) throws IOException {
        super(name, resource);
    }

    public LifeSourcePropertySource(Resource resource) throws IOException {
        super(resource);
    }

    public LifeSourcePropertySource(String name, String location, ClassLoader classLoader) throws IOException {
        super(name, location, classLoader);
    }

    public LifeSourcePropertySource(String location, ClassLoader classLoader) throws IOException {
        super(location, classLoader);
    }

    public LifeSourcePropertySource(String name, String location) throws IOException {
        super(name, location);
    }

    public LifeSourcePropertySource(String location) throws IOException {
        super(location);
    }

    @Override
    public Object getProperty(String name) {

        if (StringUtils.isNotBlank(System.getenv(name)))
            return System.getenv(name);

        if (StringUtils.isNotBlank(System.getProperty(name)))
            return System.getProperty(name);

        return super.getProperty(name);
    }
}
</code>```

So, this has helped me.

ContentLicense: CC BY-SA 4.0

Body:
We are working on a Spring Boot web application, and the database we are using is MySQL;

the setup we have is we first test it locally (means we need to install MySQL on our PC);

then we push to Bitbucket;

Jenkins automatically detects the new push to Bitbucket and does a build on it (for Jenkins mvn build to pass we also need to install MySQL on the virtual machines that is running Jenkins).

if Jenkins build passes  we push the code to our application on OpenShift (using the Openshift deployment plugin on Jenkins).

The problem we have, as you may have already figured it out, is that:

in application.properties we can not hard code the MySQL info. Since our project will be running in 3 different places (local, Jenkins, and OpenShift), we need to make the datasource field dynamic in application.properties (we know there are different ways of doing it but we are working on this solution for now).

  spring.datasource.url =
  spring.datasource.username =
  spring.datasource.password =

The solution we came up with is we create system environment variables locally and in the Jenkins VM (naming them the same way OpenShift names them), and assigning them the right values respectively:

export OPENSHIFT_MYSQL_DB_HOST="jdbc:mysql://localhost"
export OPENSHIFT_MYSQL_DB_PORT="3306"
export OPENSHIFT_MYSQL_DB_USERNAME="root"
export OPENSHIFT_MYSQL_DB_PASSWORD="123asd"

We have done this and it works. We have also checked with Map<String, String> env = System.getenv(); that the environment variables can be made into java variables as such:

String password = env.get("OPENSHIFT_MYSQL_DB_PASSWORD");
String userName = env.get("OPENSHIFT_MYSQL_DB_USERNAME");
String sqlURL = env.get("OPENSHIFT_MYSQL_DB_HOST");
String sqlPort = env.get("OPENSHIFT_MYSQL_DB_PORT");

Now the only thing left is we need to use these java variables in our application.properties, and that is what we are having trouble with.

In which folder, and how, do we need to assign the password, userName, sqlURL, and sqlPort variables for application.properties to be able to see them and how do we include them in application.properties?

We have tried many things one of them being:

spring.datasource.url = ${sqlURL}:${sqlPort}/"nameofDB"
spring.datasource.username = ${userName}
spring.datasource.password = ${password}

No luck so far.  We are probably not putting these environment variables in the right class/folder or are using them incorrectly in application.properties.

Body:
Maybe I write this too late, but I have gotten the similar problem when I have tried to override methods for reading properties.

My problem have been:
1) Read property from env if this property has been set in env
2) Read property from system property if this property have been setted in system property
3) And last, read from application properties.

So, for resolving this problem I go to my bean configuration class

@Validated
@Configuration
@ConfigurationProperties(prefix = ApplicationConfiguration.PREFIX)
@PropertySource(value = "${application.properties.path}", factory = PropertySourceFactoryCustom.class)
@Data // lombok
public class ApplicationConfiguration {

    static final String PREFIX = "application";

    @NotBlank
    private String keysPath;

    @NotBlank
    private String publicKeyName;

    @NotNull
    private Long tokenTimeout;

    private Boolean devMode;

    public void setKeysPath(String keysPath) {
        this.keysPath = StringUtils.cleanPath(keysPath);
    }
}

And overwrite factory in @PropertySource. And then I have created my own implementation for reading properties.

    public class PropertySourceFactoryCustom implements PropertySourceFactory {

        @Override
        public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
            return name != null ? new PropertySourceCustom(name, resource) : new PropertySourceCustom(resource);
        }

    }

And created PropertySourceCustom

public class PropertySourceCustom extends ResourcePropertySource {

    public LifeSourcePropertySource(String name, EncodedResource resource) throws IOException {
        super(name, resource);
    }

    public LifeSourcePropertySource(EncodedResource resource) throws IOException {
        super(resource);
    }

    public LifeSourcePropertySource(String name, Resource resource) throws IOException {
        super(name, resource);
    }

    public LifeSourcePropertySource(Resource resource) throws IOException {
        super(resource);
    }

    public LifeSourcePropertySource(String name, String location, ClassLoader classLoader) throws IOException {
        super(name, location, classLoader);
    }

    public LifeSourcePropertySource(String location, ClassLoader classLoader) throws IOException {
        super(location, classLoader);
    }

    public LifeSourcePropertySource(String name, String location) throws IOException {
        super(name, location);
    }

    public LifeSourcePropertySource(String location) throws IOException {
        super(location);
    }

    @Override
    public Object getProperty(String name) {

        if (StringUtils.isNotBlank(System.getenv(name)))
            return System.getenv(name);

        if (StringUtils.isNotBlank(System.getProperty(name)))
            return System.getProperty(name);

        return super.getProperty(name);
    }
}

So, this has helped me.


问:
How to organize my Buttons in Row layout and full width
I would like to have my two divs(Up and down buttons) organized in a layout row side by side and taking the full widh of the page.
right now, they are organized like this :

My HTML is this :

```<code> <div layout="row">
    <div class="btn btn-info btn-lg" width="50%;">
        <span class="glyphicon glyphicon-menu-up"></span> Up
    </div>
    <div class="btn btn-info btn-lg" width="50%;">
        <span class="glyphicon glyphicon-menu-down"></span> Down
    </div>
</div>
</code>```

答:
If you are using boostrap you can do it in following way:

```<code><div class="row">
    <div class="col-md-6">

        <div class="btn btn-info btn-lg btn-full-width">
            <span class="glyphicon glyphicon-menu-up"></span> Up
        </div>

    </div>

        <div class="col-md-6">

            <div class="btn btn-info btn-lg btn-full-width">
                <span class="glyphicon glyphicon-menu-down"></span> Down
            </div>

    </div>

</div>
</code>```

CSS:

```<code>.btn-full-width { width: 100%; }
</code>```

Edit: added CSS class for buttons.

Body:
I would like to have my two divs(Up and down buttons) organized in a layout row side by side and taking the full widh of the page.
right now, they are organized like this :

My HTML is this :

         Up

         Down

Body:
If you are using boostrap you can do it in following way:

<div class="row">
    <div class="col-md-6">

        <div class="btn btn-info btn-lg btn-full-width">
            <span class="glyphicon glyphicon-menu-up"></span> Up
        </div>

    </div>

        <div class="col-md-6">

            <div class="btn btn-info btn-lg btn-full-width">
                <span class="glyphicon glyphicon-menu-down"></span> Down
            </div>

    </div>

</div>

CSS:

.btn-full-width { width: 100%; }

Edit: added CSS class for buttons.


问:
Gett image alt from cmb2 file custom field in loop (CMB2!)
I use wordpress CMS and CMB2 plugin to create cmb fields.It is perfect combination but I can't get alt text from my images added using "file" field type. As usual I register repeatable fields and bringing them to frontend by this :

```<code><?php $successful_students_items = get_post_meta( get_the_id(), 'successful_students_block_box', true );
                                  if( !empty( $successful_students_items ) ) {
                                    foreach( $successful_students_items as $successful_students_item ) { ?>
                                <div class="ipd-je-8 ipd-rz-8 ipd-pv-12 ipd-ke-24">
                                    <div class="rjeudirnskxzi nnu">
                                                        <div class="h1ge6swchqzj6de">
                                                            <div class="h1ge6swchqzj6de_cvz">
                                                          <figure class="o309iruhgtybgyu5">
                                          <blockquote><?php echo $successful_students_item['successful_students_block_testimonial']; ?>
                                            <div class="ingi3h38d8jj4"></div>
                                          </blockquote>
                                          <img alt="" src="<?php echo $successful_students_item['successful_students_block_image']; ?>"/>
                                          <div class="ewr4i9548jfdeuthie">
                                            <h5><?php echo $successful_students_item['successful_students_block_name_lastname']; ?>
                                              <span>
                                                <br>
                                                <?php echo $successful_students_item['successful_students_block_position']; ?>
                                              </span>
                                            </h5>
                                          </div>
                                        </figure>
                                                          </div>
                                                        </div>
                                                      </div>
                                                  </div>
                                    <?php }
                                  } ?>
</code>```

but I can't get image alt text , tried to google but nothing of what I've found work.. Maybe anyone can help? Thanks!!

答:
You can achieve Your requirement by bit of alternative way, means by using the file_list type of CMB2 you will get the array of images. So use the array_key to get the individual image id e.g

foreach( array_keys($successful_students_items) as $successful_students_item_id )
{

/** Now by using this id you can get the individual data of an attachment**/

$successful_students_block_image_alt = get_post_meta( $successful_students_item_id, '_wp_attachment_image_alt', true );
                            $successful_students_block_image_url_details = wp_get_attachment_image_src( $successful_students_item_id, 'full');

/** this will return an array **/
                            $successful_students_block_image_url = $successful_students_block_image_url_details[0];

}
/** Now you can use this individual data in img tag.**/

Body:
I use wordpress CMS and CMB2 plugin to create cmb fields.It is perfect combination but I can't get alt text from my images added using "file" field type. As usual I register repeatable fields and bringing them to frontend by this :

<?php $successful_students_items = get_post_meta( get_the_id(), 'successful_students_block_box', true );
                                  if( !empty( $successful_students_items ) ) {
                                    foreach( $successful_students_items as $successful_students_item ) { ?>

<?php echo $successful_students_item['successful_students_block_testimonial']; ?>

                                          <img alt="" src="<?php echo $successful_students_item['successful_students_block_image']; ?>"/>

<?php echo $successful_students_item['successful_students_block_name_lastname']; ?>

                                                <?php echo $successful_students_item['successful_students_block_position']; ?>

                                    <?php }
                                  } ?>

but I can't get image alt text , tried to google but nothing of what I've found work.. Maybe anyone can help? Thanks!!


问:
Smart way to remove PDO statement rows integer keys and relative values
I have a PHP page showing user a query content.

If a csv parameter is passed, I let the user download the results in csv like this:

```<code>$stmt = $pdo->prepare($query_select);
$stmt->execute($params);
if ($format == 'csv'){
  $fobj = fopen('php://output', 'w');
  header('Content-Type: text/csv');
  header('Content-Disposition: attachment; filename="' . $search_text . '.csv"');
  $i = 0;
  foreach ($stmt as $row) {
    if (!$i++) {
      fputcsv($fobj, array_keys($row));
    }
    fputcsv($fobj, array_values($row));
  }
  fclose($fobj);
  exit();
}
</code>```

Problem is $row contains data as this:

```<code>Array
(
    [name] => apple
    [0] => apple
    [colour] => red
    [1] => red
)
</code>```

so my csv file ends up with duplicate data:

```<code>name,0,colour,1
apple,apple,red,red
</code>```

Which could be a smart way to get instead what user expects?

```<code>name,colour
apple,red
</code>```

答:
if you don't want to use the PDO:FETCH_ASSOC for some reason you can use this for your array:

```<code>array_filter( $array, 'is_string', ARRAY_FILTER_USE_KEY );
</code>```

this will return an array with the keys that are strings only

Body:
I have a PHP page showing user a query content.

If a csv parameter is passed, I let the user download the results in csv like this:

$stmt = $pdo->prepare($query_select);
$stmt->execute($params);
if ($format == 'csv'){
  $fobj = fopen('php://output', 'w');
  header('Content-Type: text/csv');
  header('Content-Disposition: attachment; filename="' . $search_text . '.csv"');
  $i = 0;
  foreach ($stmt as $row) {
    if (!$i++) {
      fputcsv($fobj, array_keys($row));
    }
    fputcsv($fobj, array_values($row));
  }
  fclose($fobj);
  exit();
}

Problem is $row contains data as this:

Array
(
    [name] => apple
    [0] => apple
    [colour] => red
    [1] => red
)

so my csv file ends up with duplicate data:

name,0,colour,1
apple,apple,red,red

Which could be a smart way to get instead what user expects?

name,colour
apple,red

Body:
if you don't want to use the PDO:FETCH_ASSOC for some reason you can use this for your array:

array_filter( $array, 'is_string', ARRAY_FILTER_USE_KEY );

this will return an array with the keys that are strings only


问:
Angular2 RC6: '<component> is not a known element'
I am getting the following error in the browser console when trying to run my Angular 2 RC6 app:

```<code>> Error: Template parse errors: 'header-area' is not a known element:
> 1. If 'header-area' is an Angular component, then verify that it is part of this module.
> 2. If 'header-area' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schema' of this component
> to suppress this message.("

    <div class="page-container">
        [ERROR->]<header-area></header-area>
        <div class="container-fluid">

> "): PlannerComponent@1:2
</code>```

I don't get why the component isn't found. My PlannerModule looks like this:

```<code>@NgModule({
  declarations: [
    PlannerComponent,
    HeaderAreaComponent,
    NavbarAreaComponent,
    EreignisbarAreaComponent,
    GraphAreaComponent,
    nvD3
    ],
  imports: [
    RouterModule,
    CommonModule,
    ModalModule
    ],
  bootstrap: [PlannerComponent],
})
export class PlannerModule {}
</code>```

and as far as I understood the concept of Modules in ng2, the parts of the modules are declared in 'declarations'. For completeness, here is the PlannerComponent:

```<code>@Component({
  selector: 'planner',
  providers: [CalculationService],
  templateUrl: './planner.component.html',
  styleUrls: ['./planner.component.styl']
})
export default class PlannerComponent {
}
</code>```

and the HeaderAreaComponent:

```<code>@Component({
  selector: 'header-area',
  templateUrl: './header-area.component.html',
  styleUrls: ['./header-area.component.styl']
})
export default class HeaderAreaComponent {
}
</code>```

The -Tag is located in planner.component.html:

```<code><div class="page-container">
  <header-area></header-area>
  <div class="container-fluid">

    <div class="row">...
</code>```

Did I get something wrong?

Update: Complete code

planner.module.ts:

```<code>import HeaderAreaComponent from '../header-area/header-area.component';
import NavbarAreaComponent from '../navbar-area/navbar-area.component';
import GraphAreaComponent from '../graph-area/graph-area.component';
import EreignisbarAreaComponent from '../ereignisbar-area/ereignisbar-area.component';
import PlannerComponent from './planner.component';
import {NgModule} from '@angular/core';
import {nvD3} from 'ng2-nvd3';
import {RouterModule} from '@angular/router';
import {CommonModule} from '@angular/common';
import {ModalModule} from 'ng2-bootstrap/ng2-bootstrap';

@NgModule({
  declarations: [
    PlannerComponent,
    HeaderAreaComponent,
    NavbarAreaComponent,
    EreignisbarAreaComponent,
    GraphAreaComponent,
    nvD3
  ],
  imports: [
    RouterModule,
    CommonModule,
    ModalModule
  ],
  bootstrap: [PlannerComponent],
})
export class PlannerModule {
  // TODO: get rid of the "unused class" warning
}
</code>```

planner.component.ts

```<code>import {Component} from '@angular/core';
import CalculationService from '../_shared/services/calculation.service/calculation.service';
import HeaderAreaComponent from '../header-area/header-area.component';

@Component({
  selector: 'planner',
  providers: [CalculationService],
  templateUrl: './planner.component.html',
  styleUrls: ['./planner.component.styl']
})
export default class PlannerComponent {
}
</code>```

planner.component.html

```<code><div class="page-container">
  <header-area></header-area>
  <div class="container-fluid">

    <div class="row">
      <div class="col-xs-2 col-sm-1 sidebar">
        <navbar-area></navbar-area>
      </div>
      <div class="col-xs-10 col-sm-11">
        <graph-area></graph-area>
      </div>
    </div><!--/.row-->

    <div class="row">
      <div class="col-xs-10 col-sm-11 offset-sm-1">
        <ereignisbar-area></ereignisbar-area>
      </div>
    </div><!--/.row-->

  </div><!--/.container-->
</div><!--/.page-container-->
</code>```

答:
If you have used the Webclipse automatically generated component definition you may find that the selector name has 'app-' prepended to it.  Apparently this is a new convention when declaring sub-components of a main app component. Check how your selector has been defined in your component if you have used 'new' - 'component' to create it in Angular IDE.  So instead of putting

```<code><header-area></header-area>
</code>```

you may need

```<code><app-header-area></app-header-area>
</code>```

Body:
I am getting the following error in the browser console when trying to run my Angular 2 RC6 app:

> Error: Template parse errors: 'header-area' is not a known element:
> 1. If 'header-area' is an Angular component, then verify that it is part of this module.
> 2. If 'header-area' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schema' of this component
> to suppress this message.("

        [ERROR->]

> "): PlannerComponent@1:2

I don't get why the component isn't found. My PlannerModule looks like this:

@NgModule({
  declarations: [
    PlannerComponent,
    HeaderAreaComponent,
    NavbarAreaComponent,
    EreignisbarAreaComponent,
    GraphAreaComponent,
    nvD3
    ],
  imports: [
    RouterModule,
    CommonModule,
    ModalModule
    ],
  bootstrap: [PlannerComponent],
})
export class PlannerModule {}

and as far as I understood the concept of Modules in ng2, the parts of the modules are declared in 'declarations'. For completeness, here is the PlannerComponent:

@Component({
  selector: 'planner',
  providers: [CalculationService],
  templateUrl: './planner.component.html',
  styleUrls: ['./planner.component.styl']
})
export default class PlannerComponent {
}

and the HeaderAreaComponent:

@Component({
  selector: 'header-area',
  templateUrl: './header-area.component.html',
  styleUrls: ['./header-area.component.styl']
})
export default class HeaderAreaComponent {
}

The -Tag is located in planner.component.html:

...

Did I get something wrong?

Update: Complete code

planner.module.ts:

import HeaderAreaComponent from '../header-area/header-area.component';
import NavbarAreaComponent from '../navbar-area/navbar-area.component';
import GraphAreaComponent from '../graph-area/graph-area.component';
import EreignisbarAreaComponent from '../ereignisbar-area/ereignisbar-area.component';
import PlannerComponent from './planner.component';
import {NgModule} from '@angular/core';
import {nvD3} from 'ng2-nvd3';
import {RouterModule} from '@angular/router';
import {CommonModule} from '@angular/common';
import {ModalModule} from 'ng2-bootstrap/ng2-bootstrap';

@NgModule({
  declarations: [
    PlannerComponent,
    HeaderAreaComponent,
    NavbarAreaComponent,
    EreignisbarAreaComponent,
    GraphAreaComponent,
    nvD3
  ],
  imports: [
    RouterModule,
    CommonModule,
    ModalModule
  ],
  bootstrap: [PlannerComponent],
})
export class PlannerModule {
  // TODO: get rid of the "unused class" warning
}

planner.component.ts

import {Component} from '@angular/core';
import CalculationService from '../_shared/services/calculation.service/calculation.service';
import HeaderAreaComponent from '../header-area/header-area.component';

@Component({
  selector: 'planner',
  providers: [CalculationService],
  templateUrl: './planner.component.html',
  styleUrls: ['./planner.component.styl']
})
export default class PlannerComponent {
}

planner.component.html

        <navbar-area></navbar-area>

        <graph-area></graph-area>

        <ereignisbar-area></ereignisbar-area>

Body:
If you have used the Webclipse automatically generated component definition you may find that the selector name has 'app-' prepended to it.  Apparently this is a new convention when declaring sub-components of a main app component. Check how your selector has been defined in your component if you have used 'new' - 'component' to create it in Angular IDE.  So instead of putting

<header-area></header-area>

you may need

<app-header-area></app-header-area>


问:
ERROR_INVALID_PRINTER_NAME returned by OpenPrinter() in Windows 8 when executed under "SYSTEM" account
My application deletes virtual printer when user uninstalls the application.
Application's installation and Uninstallation can be done using user interaction(wizard) or by setting group policy in Windows server 2003(domain admin sets the policy in server and the domain user in client PC need to update the group policy and restart the Client PC for installation or uninstallation of the application).
The follwing code in the application deletes printer and printer driver when uninstalling the application.

```<code>void CPrinterDriver::DeletePrinterIfExists()
{
// Delete old printer driver if existing
ControlSpoolService(TRUE);

HANDLE hPrinter = NULL;
PRINTER_DEFAULTS    pDefaults = { NULL, NULL, PRINTER_ALL_ACCESS };
// Ignore error codes
OpenPrinter(m_driverInfo.pName, &hPrinter, &pDefaults);
if (hPrinter)
{
// deleting jobs
SetPrinter(hPrinter, 0, NULL, PRINTER_CONTROL_PURGE);
// Delete printer
DeletePrinter(hPrinter);
// Get printer driver name and delete it
DWORD   dwNeeded = 0;
GetPrinter(hPrinter, 2, NULL, 0, &dwNeeded);
if (dwNeeded)
{
PRINTER_INFO_2  *pi2 = (PRINTER_INFO_2 *)GlobalAlloc(GPTR, sizeof(PRINTER_INFO_2)*dwNeeded);
if (pi2)
{
   GetPrinter(hPrinter, 2, (LPBYTE)pi2, dwNeeded, &dwNeeded);
   DeletePrinterDriver(NULL, NULL, pi2->pDriverName);
   GlobalFree(pi2);
}
}
ClosePrinter(hPrinter);
}
}
</code>```

The above code works well in Windows 7 in both cases(user interactive installation and using group policy) of uninstallation. In Windows 8, it works well using user interactive installation and uninstallation.
But in Windows 8 the above OpenPrinter() is returing ERROR_INVALID_PRINTER_NAME.

We found that the OpenPrinter() is called using the "SYSTEM" account.
Kindly help.

答:
If you suffer from the issue where:

the registry key for the shared (network) printer is missing and

the API gives you the invalid printer name error

Then you can try opening the printer by its full UNC path.

So when opening MYPRINTER does not work, then open it as \\MYSERVER\MYPRINTER .

Of course this still assumes that you can already print to this printer normally from other applications!

Body:
My application deletes virtual printer when user uninstalls the application.
Application's installation and Uninstallation can be done using user interaction(wizard) or by setting group policy in Windows server 2003(domain admin sets the policy in server and the domain user in client PC need to update the group policy and restart the Client PC for installation or uninstallation of the application).
The follwing code in the application deletes printer and printer driver when uninstalling the application.

void CPrinterDriver::DeletePrinterIfExists()
{
// Delete old printer driver if existing
ControlSpoolService(TRUE);

HANDLE hPrinter = NULL;
PRINTER_DEFAULTS    pDefaults = { NULL, NULL, PRINTER_ALL_ACCESS };
// Ignore error codes
OpenPrinter(m_driverInfo.pName, &hPrinter, &pDefaults);
if (hPrinter)
{
// deleting jobs
SetPrinter(hPrinter, 0, NULL, PRINTER_CONTROL_PURGE);
// Delete printer
DeletePrinter(hPrinter);
// Get printer driver name and delete it
DWORD   dwNeeded = 0;
GetPrinter(hPrinter, 2, NULL, 0, &dwNeeded);
if (dwNeeded)
{
PRINTER_INFO_2  *pi2 = (PRINTER_INFO_2 *)GlobalAlloc(GPTR, sizeof(PRINTER_INFO_2)*dwNeeded);
if (pi2)
{
   GetPrinter(hPrinter, 2, (LPBYTE)pi2, dwNeeded, &dwNeeded);
   DeletePrinterDriver(NULL, NULL, pi2->pDriverName);
   GlobalFree(pi2);
}
}
ClosePrinter(hPrinter);
}
}

The above code works well in Windows 7 in both cases(user interactive installation and using group policy) of uninstallation. In Windows 8, it works well using user interactive installation and uninstallation.
But in Windows 8 the above OpenPrinter() is returing ERROR_INVALID_PRINTER_NAME.

We found that the OpenPrinter() is called using the "SYSTEM" account.
Kindly help.


问:
What's the magic of arrays in C#
```<code>int[] a = new int[5];
string[] b = new string[1];
</code>```

The types of both a and b inherit from the abstract System.Array, but there is no real classes in the built-in library(it seems that there are some runtime types, you can't find the type defination class of an int[]). Can you tell me what happens while compiling? And why did they(the c# team) make this design(I mean why it's not something like Array<T>,instead they are using an abstract class with compiler magics)?

答:
Trying to reason this out within the .NET type system doesn't get you very far.  There is core support built into the JIT compiler and the CLR to deal with creating arrays.  A statement like this:

```<code>        var arr = new int[5];
</code>```

Generates this IL:

```<code>  IL_0001:  ldc.i4.5
  IL_0002:  newarr     [mscorlib]System.Int32
</code>```

Which the JIT compiler then translate into this machine code:

```<code>00000035  mov         edx,5                 ; arg2 = array size
0000003a  mov         ecx,6F535F06h         ; arg1 = typeof(int)
0000003f  call        FFD52128              ; call JIT_NewArr1(type, size)
</code>```

Core ingredients here are the dedicated IL opcode, newarr, instead of the usual newobj opcode that creates an instance of a class.  And the simple translation to a CLR helper function that actually gets the object created.  You can have a look-see at this helper function with the SSCLI20 source code, clr\src\vm\jithelpers.cpp.  Too large to post here, but it is heavily optimized to make this kind of code run as fast possible, having direct access to the type internals available to CLR code.

There are two of these helpers available, JIT_NewArr1() creates one-dimensional (vector) arrays and JIT_NewMDArr() creates multi-dimensional arrays.  Compare to the two overloads available for Type.MakeArrayType().

Title: What's the magic of arrays in C#

Body:
int[] a = new int[5];
string[] b = new string[1];

The types of both a and b inherit from the abstract System.Array, but there is no real classes in the built-in library(it seems that there are some runtime types, you can't find the type defination class of an int[]). Can you tell me what happens while compiling? And why did they(the c# team) make this design(I mean why it's not something like Array<T>,instead they are using an abstract class with compiler magics)?

Body:
Trying to reason this out within the .NET type system doesn't get you very far.  There is core support built into the JIT compiler and the CLR to deal with creating arrays.  A statement like this:

        var arr = new int[5];

Generates this IL:

  IL_0001:  ldc.i4.5
  IL_0002:  newarr     [mscorlib]System.Int32

Which the JIT compiler then translate into this machine code:

00000035  mov         edx,5                 ; arg2 = array size
0000003a  mov         ecx,6F535F06h         ; arg1 = typeof(int)
0000003f  call        FFD52128              ; call JIT_NewArr1(type, size)

Core ingredients here are the dedicated IL opcode, newarr, instead of the usual newobj opcode that creates an instance of a class.  And the simple translation to a CLR helper function that actually gets the object created.  You can have a look-see at this helper function with the SSCLI20 source code, clr\src\vm\jithelpers.cpp.  Too large to post here, but it is heavily optimized to make this kind of code run as fast possible, having direct access to the type internals available to CLR code.

There are two of these helpers available, JIT_NewArr1() creates one-dimensional (vector) arrays and JIT_NewMDArr() creates multi-dimensional arrays.  Compare to the two overloads available for Type.MakeArrayType().


问:
grep invert match on two files
I have two text files containing one column each, for example -

File_A       File_B

1              1

2              2

3              8

If I do grep -f File_A File_B > File_C, I get File_C containing 1 and 2. I want to know how to use grep -v on two files so that I can get the non-matching values, 3 and 8 in the above example.

Thanks.

答:
You can also use comm if it allows empty output delimiter

```<code>$ # -3 means suppress lines common to both input files
$ # by default, tab character appears before lines from second file
$ comm -3 f1 f2
3
    8
$ # change it to empty string
$ comm -3 --output-delimiter='' f1 f2
3
8
</code>```

Note: comm requires sorted input, so use comm -3 --output-delimiter='' <(sort f1) <(sort f2) if they are not already sorted

You can also pass common lines got from grep as input to grep -v. Tested with GNU grep, some version might not support all these options

```<code>$ grep -Fxf f1 f2 | grep -hxvFf- f1 f2
3
8
</code>```

-F option to match strings literally, not as regex

-x option to match whole lines only

-h to suppress file name prefix

f- to accept stdin instead of file input

Title: grep invert match on two files

Body:
You can also use comm if it allows empty output delimiter

$ # -3 means suppress lines common to both input files
$ # by default, tab character appears before lines from second file
$ comm -3 f1 f2
3
    8
$ # change it to empty string
$ comm -3 --output-delimiter='' f1 f2
3
8

Note: comm requires sorted input, so use comm -3 --output-delimiter='' <(sort f1) <(sort f2) if they are not already sorted

You can also pass common lines got from grep as input to grep -v. Tested with GNU grep, some version might not support all these options

$ grep -Fxf f1 f2 | grep -hxvFf- f1 f2
3
8

-F option to match strings literally, not as regex

-x option to match whole lines only

-h to suppress file name prefix

f- to accept stdin instead of file input


问: How to add a

答:
I found this function in the JQuery source, which seems to do what you want and feels a bit cleaner than the other approaches to me. But then again I am a JS beginner and probably don't see the details. Anyways, somebody might take something useful away from this.</p>

```<code>function DOMEval( code, doc ) {
    doc = doc || document;

    var script = doc.createElement( "script" );

    script.text = code;
    doc.head.appendChild( script ).parentNode.removeChild( script );
}
</code>```

Title: How to add a <script> element to the DOM and execute its code?

Body:
I want to add a  element into the existing DOM to have the javascript code run.

I did this with YUI:

var scriptNode = Y.Node.create('

Body:
I found this function in the JQuery source, which seems to do what you want and feels a bit cleaner than the other approaches to me. But then again I am a JS beginner and probably don't see the details. Anyways, somebody might take something useful away from this.

function DOMEval( code, doc ) {
    doc = doc || document;

    var script = doc.createElement( "script" );

    script.text = code;
    doc.head.appendChild( script ).parentNode.removeChild( script );
}


问:
Python/Django - No module named
I try to work with a class from Django views.

sync.py

```<code>import requests

class Sync:

    def do():
        r = requests.post('http://192.168.1.7/api/report_x')
        print(r.response)
</code>```

views.py

```<code>import sync

def index(request):
    s = Sync()
    s.do()
    return HttpResponse("Hello, this is index")
</code>```

When I access index from the browser I get:

global name 'Sync' is not defined

What am I doing wrong?

答:
Assuming that your file directory is proper and not the reason for the error, change your code to the following:</p>

```<code>from sync import Sync    # simply import sync just calls the synv.py file, not the Sync class

def index(request):
    s = Sync()
    s.do()
    return HttpResponse("Hello, this is index")
</code>```

Title: Python/Django - No module named

Body:
I try to work with a class from Django views.

sync.py

import requests

class Sync:

    def do():
        r = requests.post('http://192.168.1.7/api/report_x')
        print(r.response)

views.py

import sync

def index(request):
    s = Sync()
    s.do()
    return HttpResponse("Hello, this is index")

When I access index from the browser I get:

global name 'Sync' is not defined

What am I doing wrong?

Body:
Assuming that your file directory is proper and not the reason for the error, change your code to the following:

from sync import Sync    # simply import sync just calls the synv.py file, not the Sync class

def index(request):
    s = Sync()
    s.do()
    return HttpResponse("Hello, this is index")


问:
Is it possible to combine rst-class and ifconfig?
I am writing on a software documentation. I am using the .. rst-cass:: directive to add specific css classes to different sections which control different styles and features, which works really well. Now I tried to create different versions of the document and therefore tried to combine .. rst-cass::  with .. ifconfig::. My .rst files looked like this:

```<code>.. ifconfig::  var==True

   .. rst-class:: html-toggle

.. ifconfig::  var==False

   .. rst-class:: grey

Sectiontitle
============
</code>```

When I tried to build this into HTML files, the build process didn´t finish and showed me:

'Losing "%s" attribute: %s' % (att, self[att])

AssertionError: Losing "classes" attribute: ['html-toggle']

Is there any way this can work, or any other way, where to assign CSS classes to sections depending on variables in the conf.py.

答:
Use custom CSS, instead of adding classes to the HTML, and selecting which style sheet to use in your conf.py with a Python expression.

ifconfig is intended to "include content of the directive only if the Python expression given as an argument is True", not customizing styles.

Body:
I am writing on a software documentation. I am using the .. rst-cass:: directive to add specific css classes to different sections which control different styles and features, which works really well. Now I tried to create different versions of the document and therefore tried to combine .. rst-cass::  with .. ifconfig::. My .rst files looked like this:

.. ifconfig::  var==True

   .. rst-class:: html-toggle

.. ifconfig::  var==False

   .. rst-class:: grey

Sectiontitle
============

When I tried to build this into HTML files, the build process didn´t finish and showed me:

'Losing "%s" attribute: %s' % (att, self[att])

AssertionError: Losing "classes" attribute: ['html-toggle']

Is there any way this can work, or any other way, where to assign CSS classes to sections depending on variables in the conf.py.