问:
How do I calculate the sum of the values in a count column in mysql?
I have a pretty complex database and I am trying to execute a query that returns the sum of all the values of the resulting count column. I can successfully determine the count values but how do I determine the sum?

My code is:

```<code>SELECT COUNT(cause) as num_of_deaths
FROM deaths
WHERE rlist IN ('09A', '09B', '09N', '09C')
AND ryear IN (SELECT DISTINCT ryear FROM deaths)
AND cause IN (SELECT cause FROM icd9 WHERE description LIKE '%MN OF%')
GROUP BY cause;
</code>```

Every time I try to wrap my count within SUM I get an error saying 'Invalid use of group function'. How do I go around about this?

My resulting set looks like this: resultant set

答:
Have you tried:</p>

```<code>SELECT SUM(num_of_deaths) FROM (
SELECT COUNT(cause) as num_of_deaths
FROM deaths
WHERE rlist IN ('09A', '09B', '09N', '09C')
AND ryear IN (SELECT DISTINCT ryear FROM deaths)
AND cause IN (SELECT cause FROM icd9 WHERE description LIKE '%MN OF%')
GROUP BY cause) as nums_of_deaths;
</code>```

Body:
I have a pretty complex database and I am trying to execute a query that returns the sum of all the values of the resulting count column. I can successfully determine the count values but how do I determine the sum?

My code is:

SELECT COUNT(cause) as num_of_deaths
FROM deaths
WHERE rlist IN ('09A', '09B', '09N', '09C')
AND ryear IN (SELECT DISTINCT ryear FROM deaths)
AND cause IN (SELECT cause FROM icd9 WHERE description LIKE '%MN OF%')
GROUP BY cause;

Every time I try to wrap my count within SUM I get an error saying 'Invalid use of group function'. How do I go around about this?

My resulting set looks like this: resultant set

Body:
Have you tried:

SELECT SUM(num_of_deaths) FROM (
SELECT COUNT(cause) as num_of_deaths
FROM deaths
WHERE rlist IN ('09A', '09B', '09N', '09C')
AND ryear IN (SELECT DISTINCT ryear FROM deaths)
AND cause IN (SELECT cause FROM icd9 WHERE description LIKE '%MN OF%')
GROUP BY cause) as nums_of_deaths;


来源: stackexchange

问:
CMake External Project Symlinks
I am building an external project that generates shared objects with symlinks:

i.e.

```<code>libxml.so -> libxml.so.0.0.0
libxml.so.0 -> libxml.so.0.0.0
libxml.so.0.0.0
</code>```

I want to copy these 3 files to my library output path. However, if I do:

```<code>ExternalProject_Add_Step(
    xml copy2lib
    COMMAND ${CMAKE_COMMAND} -E copy_directory ${EXTERNAL_INSTALL_PATH}/xml/lib/ ${LIBRARY_OUTPUT_PATH}
    DEPENDEES install
)
</code>```

All of the symlinks are destroyed and there are essentially 3 copies of the library. I am aware of the following solution, i.e.:

```<code>COMMAND ${CMAKE_COMMAND} -E create_symlink ./libxml.so.0.0.0 ./libxml.so
WORKING_DIRECTORY ${LIBRARY_OUTPUT_PATH}
</code>```

However, in my case, the external project is generating dozens of libraries that follow this convention. Please tell me I don't have to manually repair every symlink?

答:
CMake has a poor support for file links (symlinks, hardlinks, etc.). Partially, this is because there is no cross-platform view of such thing: Windows and Linux have different interpretation of these terms.

So, when you want to operate with Linux symlinks in a specific way, use Linux-specific commands. Instead of cross-platform cmake -E copy_directory use Linux-specific cp:

```<code>COMMAND cp -Pr ${EXTERNAL_INSTALL_PATH}/xml/lib/ ${LIBRARY_OUTPUT_PATH}
</code>```

Note, that copiing symlink has a sence only for relative symlinks. If symlink contains absolute path, after copy it will refer to original library location, not to the copied one.

ContentLicense: CC BY-SA 3.0

Title: CMake External Project Symlinks

Body:
I am building an external project that generates shared objects with symlinks:

i.e.

libxml.so -> libxml.so.0.0.0
libxml.so.0 -> libxml.so.0.0.0
libxml.so.0.0.0

I want to copy these 3 files to my library output path. However, if I do:

ExternalProject_Add_Step(
    xml copy2lib
    COMMAND ${CMAKE_COMMAND} -E copy_directory ${EXTERNAL_INSTALL_PATH}/xml/lib/ ${LIBRARY_OUTPUT_PATH}
    DEPENDEES install
)

All of the symlinks are destroyed and there are essentially 3 copies of the library. I am aware of the following solution, i.e.:

COMMAND ${CMAKE_COMMAND} -E create_symlink ./libxml.so.0.0.0 ./libxml.so
WORKING_DIRECTORY ${LIBRARY_OUTPUT_PATH}

However, in my case, the external project is generating dozens of libraries that follow this convention. Please tell me I don't have to manually repair every symlink?

Body:
CMake has a poor support for file links (symlinks, hardlinks, etc.). Partially, this is because there is no cross-platform view of such thing: Windows and Linux have different interpretation of these terms.

So, when you want to operate with Linux symlinks in a specific way, use Linux-specific commands. Instead of cross-platform cmake -E copy_directory use Linux-specific cp:

COMMAND cp -Pr ${EXTERNAL_INSTALL_PATH}/xml/lib/ ${LIBRARY_OUTPUT_PATH}

Note, that copiing symlink has a sence only for relative symlinks. If symlink contains absolute path, after copy it will refer to original library location, not to the copied one.


问:
SwiftMailer ReflectionException: Class Egulias\EmailValidator\EmailValidator does not exist
SwiftMailer: Reflection exception

I've been trying to figure out this error for a half a day and feel like I've tried everything. I literally copied the code from SwiftMailer's Website for the section I was having trouble with, but it is still getting the ReflectionException.

Some Background Details:

Php Version: 7

Swiftmailer Version: 6.0.0

PHP Code Using SwiftMailer

```<code>require_once 'swiftmailer-master/lib/swift_required.php';

$transport = (new Swift_SmtpTransport('smtp.gmail.com', 465, "ssl"))
  ->setUsername('my_gmail_username')
  ->setPassword('my_gmail_password');

$mailer = new Swift_Mailer($transport);

$message = (new Swift_Message())
  ->setSubject('Your subject')
  ->setFrom(['john@doe.com' => 'John Doe'])
  ->setTo(['receiver@domain.org', 'other@domain.org' => 'A name'])
  ->setBody('Here is the message itself')
</code>```

The Error I'm getting

```<code>[07-Jun-2017 17:31:28 America/New_York] PHP Fatal error:  Uncaught
ReflectionException: Class Egulias\EmailValidator\EmailValidator does not
exist in /home/johnjpra/public_html/php/swiftmailer-
master/lib/classes/Swift/DependencyContainer.php:309
Stack trace:
#0 /home/johnjpra/public_html/php/swiftmailer-
master/lib/classes/Swift/DependencyContainer.php(309): ReflectionClass-
>__construct('Egulias\\EmailVa...')
#1 /home/johnjpra/public_html/php/swiftmailer-
master/lib/classes/Swift/DependencyContainer.php(323):
Swift_DependencyContainer->createNewInstance('email.validator')
#2 /home/johnjpra/public_html/php/swiftmailer-
master/lib/classes/Swift/DependencyContainer.php(114):
Swift_DependencyContainer->createSharedInstance('email.validator')
#3 /home/johnjpra/public_html/php/swiftmailer-
master/lib/classes/Swift/DependencyContainer.php(371):
Swift_DependencyContainer->lookup('email.validator')
#4 /home/johnjpra/public_html/php/swiftmailer-
master/lib/classes/Swift/DependencyContainer.php(348):
Swift_DependencyContainer->lookupRecursive('email.validator')
#5 /home/johnjpra/pu in /home/johnjpra/public_html/php/swiftmailer-
master/lib/classes/Swift/DependencyContainer.php on line 309
</code>```

I'm itching to figure this out. Thanks in advance to anyone who comments or answers this

答:
You're missing egulias/email-validator package.

In composer.json of SwiftMailer you can see that it has this dependency.

```<code>"require": {
    "php": ">=7.0.0",
    "egulias/email-validator": "~2.0"
},
</code>```

Body:
SwiftMailer: Reflection exception

I've been trying to figure out this error for a half a day and feel like I've tried everything. I literally copied the code from SwiftMailer's Website for the section I was having trouble with, but it is still getting the ReflectionException.

Some Background Details:

Php Version: 7

Swiftmailer Version: 6.0.0

PHP Code Using SwiftMailer

require_once 'swiftmailer-master/lib/swift_required.php';

$transport = (new Swift_SmtpTransport('smtp.gmail.com', 465, "ssl"))
  ->setUsername('my_gmail_username')
  ->setPassword('my_gmail_password');

$mailer = new Swift_Mailer($transport);

$message = (new Swift_Message())
  ->setSubject('Your subject')
  ->setFrom(['john@doe.com' => 'John Doe'])
  ->setTo(['receiver@domain.org', 'other@domain.org' => 'A name'])
  ->setBody('Here is the message itself')

The Error I'm getting

[07-Jun-2017 17:31:28 America/New_York] PHP Fatal error:  Uncaught
ReflectionException: Class Egulias\EmailValidator\EmailValidator does not
exist in /home/johnjpra/public_html/php/swiftmailer-
master/lib/classes/Swift/DependencyContainer.php:309
Stack trace:
#0 /home/johnjpra/public_html/php/swiftmailer-
master/lib/classes/Swift/DependencyContainer.php(309): ReflectionClass-
>__construct('Egulias\\EmailVa...')
#1 /home/johnjpra/public_html/php/swiftmailer-
master/lib/classes/Swift/DependencyContainer.php(323):
Swift_DependencyContainer->createNewInstance('email.validator')
#2 /home/johnjpra/public_html/php/swiftmailer-
master/lib/classes/Swift/DependencyContainer.php(114):
Swift_DependencyContainer->createSharedInstance('email.validator')
#3 /home/johnjpra/public_html/php/swiftmailer-
master/lib/classes/Swift/DependencyContainer.php(371):
Swift_DependencyContainer->lookup('email.validator')
#4 /home/johnjpra/public_html/php/swiftmailer-
master/lib/classes/Swift/DependencyContainer.php(348):
Swift_DependencyContainer->lookupRecursive('email.validator')
#5 /home/johnjpra/pu in /home/johnjpra/public_html/php/swiftmailer-
master/lib/classes/Swift/DependencyContainer.php on line 309

I'm itching to figure this out. Thanks in advance to anyone who comments or answers this

Body:
You're missing egulias/email-validator package.

In composer.json of SwiftMailer you can see that it has this dependency.

"require": {
    "php": ">=7.0.0",
    "egulias/email-validator": "~2.0"
},


问:
.panel-default border color
I have a bootstrap default panel:

```<code><div class="panel panel-default">
    <div class="panel-heading">Login</div>
    <div class="panel-body">
    ...
</code>```

I want remove the border, but don't want to use additional class or id, etc..

Inspecting elements in chrome I see:

```<code>.panel-default {
    border-color: #ddd;
}
</code>```

That's how it got this value assigned.
As I know I can overwrite css values by applying (at least) new values by same css selectors. My css file is imported after bootstrap file.

I tried:

```<code>.panel-default {
    border-color: none;
}
</code>```

Does not work, but if I use:

```<code>.panel-default {
    border: none;
}
</code>```

this works.

So none is not an acceptable value for border-color? or what a hack it might be? because if I assign none from inspect element feature of chrome it works.

答:
Yes none is not a valid value of border-color, so you have to use border: none to remove it or border-color: transparent if you want to keep the border, but make it invisible.

The reason it works for chrome devtools is, that chrome is not applying invalid styles such as border-color: none and if you're changing the original style of your element, the style gets removed.

Title: .panel-default border color

Body:
I have a bootstrap default panel:

Login

    ...

I want remove the border, but don't want to use additional class or id, etc..

Inspecting elements in chrome I see:

.panel-default {
    border-color: #ddd;
}

That's how it got this value assigned.
As I know I can overwrite css values by applying (at least) new values by same css selectors. My css file is imported after bootstrap file.

I tried:

.panel-default {
    border-color: none;
}

Does not work, but if I use:

.panel-default {
    border: none;
}

this works.

So none is not an acceptable value for border-color? or what a hack it might be? because if I assign none from inspect element feature of chrome it works.


问:
Android Persistence room: "Cannot figure out how to read this field from a cursor"
I'm trying to create a relation between two database tables using the new Android Persistence Room Library. I looked at the documentation and tried to implement the example found at https://developer.android.com/reference/android/arch/persistence/room/Relation.html:

```<code> @Entity
 public class User {
 @PrimaryKey
     int id;
 }

 @Entity
 public class Pet {
     @PrimaryKey
     int id;
     int userId;
     String name;

 }

 @Dao
 public interface UserDao {
     @Query("SELECT * from User")
     public List<User> loadUser();
 }

 @Dao
 public interface PetDao {
     @Query("SELECT * from Pet")
     public List<Pet> loadUserAndPets();
 }

 public class UserAllPets {
     @Embedded
     public User user;
     @Relation(parentColumn = "user.id", entityColumn = "userId", entity = Pet.class)
     public List pets;
 }

 @Dao
 public interface UserPetDao {
     @Query("SELECT * from User")
     public List<UserAllPets> loadUserAndPets();
 }
</code>```

I get the following error

```<code>    ...error: Cannot figure out how to read this field from a cursor.
</code>```

in relation to:

```<code> private java.util.List<?> pets;
</code>```

I would like to point out that I found some things in their docs really confusing. For example the lack of @PrimaryKey and also the fact that the User class is missing the @Entity annotation, although it's supposed to be an entity (as fas as I see it). Did anybody run into the same problem? Thanks a lot in advance

答:
Document is really confusing. Try with just below classes:

1) User Entity:

```<code>@Entity
public class User {
    @PrimaryKey
    public int id; // User id
}
</code>```

2) Pet Entity:

```<code>@Entity
public class Pet {
    @PrimaryKey
    public int id;     // Pet id
    public int userId; // User id
    public String name;
}
</code>```

3) UserWithPets POJO:

```<code>// Note: No annotation required at this class definition.
public class UserWithPets {
   @Embedded
   public User user;

   @Relation(parentColumn = "id", entityColumn = "userId", entity = Pet.class)
   public List<Pet> pets; // or use simply 'List pets;'

   /* Alternatively you can use projection to fetch a specific column (i.e. only name of the pets) from related Pet table. You can uncomment and try below;

   @Relation(parentColumn = "id", entityColumn = "userId", entity = Pet.class, projection = "name")
   public List<String> pets;
   */
}
</code>```

parentColumn refers to Embedded User table's id column,

entityColumn refers to Pet table's userId (User - Pet relation) column,

entity refers to table(Pet) which has relation with User table.

4) UserDao Dao:

```<code>@Dao
public interface UserDao {
    @Query("SELECT * FROM User")
    public List<UserWithPets> loadUsersWithPets();
}
</code>```

Now try loadUsersWithPets(), which returns the users with their list of pets.

Edit: See my other answer for many ot many relation.

Body:
I'm trying to create a relation between two database tables using the new Android Persistence Room Library. I looked at the documentation and tried to implement the example found at https://developer.android.com/reference/android/arch/persistence/room/Relation.html:

 @Entity
 public class User {
 @PrimaryKey
     int id;
 }

 @Entity
 public class Pet {
     @PrimaryKey
     int id;
     int userId;
     String name;

 }

 @Dao
 public interface UserDao {
     @Query("SELECT * from User")
     public List<User> loadUser();
 }

 @Dao
 public interface PetDao {
     @Query("SELECT * from Pet")
     public List<Pet> loadUserAndPets();
 }

 public class UserAllPets {
     @Embedded
     public User user;
     @Relation(parentColumn = "user.id", entityColumn = "userId", entity = Pet.class)
     public List pets;
 }

 @Dao
 public interface UserPetDao {
     @Query("SELECT * from User")
     public List<UserAllPets> loadUserAndPets();
 }

I get the following error

    ...error: Cannot figure out how to read this field from a cursor.

in relation to:

 private java.util.List<?> pets;

I would like to point out that I found some things in their docs really confusing. For example the lack of @PrimaryKey and also the fact that the User class is missing the @Entity annotation, although it's supposed to be an entity (as fas as I see it). Did anybody run into the same problem? Thanks a lot in advance

Body:
Document is really confusing. Try with just below classes:

1) User Entity:

@Entity
public class User {
    @PrimaryKey
    public int id; // User id
}

2) Pet Entity:

@Entity
public class Pet {
    @PrimaryKey
    public int id;     // Pet id
    public int userId; // User id
    public String name;
}

3) UserWithPets POJO:

// Note: No annotation required at this class definition.
public class UserWithPets {
   @Embedded
   public User user;

   @Relation(parentColumn = "id", entityColumn = "userId", entity = Pet.class)
   public List<Pet> pets; // or use simply 'List pets;'

   /* Alternatively you can use projection to fetch a specific column (i.e. only name of the pets) from related Pet table. You can uncomment and try below;

   @Relation(parentColumn = "id", entityColumn = "userId", entity = Pet.class, projection = "name")
   public List<String> pets;
   */
}

parentColumn refers to Embedded User table's id column,

entityColumn refers to Pet table's userId (User - Pet relation) column,

entity refers to table(Pet) which has relation with User table.

4) UserDao Dao:

@Dao
public interface UserDao {
    @Query("SELECT * FROM User")
    public List<UserWithPets> loadUsersWithPets();
}

Now try loadUsersWithPets(), which returns the users with their list of pets.

Edit: See my other answer for many ot many relation.


问:
How to store multilayer objects in react redux?
I am trying to add multiple objects into desire's object and store all of the desires that are collected inside this object. I am trying to set the key to the the date that it was set on, thus having an individual key for each record.

However all that is happening I end up with having an desire object in the state, which gets overwritten each time of writing and also sex and masturbation are removed with each update.

I know I should be able to get this, but its late and I'm stuck :D

Reducer

```<code>import Moment from 'moment';
import {
  SET_DESIRE_DATA,
  SET_MASTURBATION_DATA,
  SET_SEX_DATA
} from '../actions/dataAction';

const initialState = {
  'desire': {},
    'masturbation': {},
    'sex': {}
};

function desire (state = initialState, action) {
    //var action
    //{
    //    desire: 3,
    //    date: Wed Jun 07 2017 23:45:41 GMT+0100 (BST)
    //}
    switch (action.type) {
        case SET_DESIRE_DATA:
            //Date returned 07_06_2017
            //Moment(action.data.date).format('D-MM-YYYY')
            return {
                ...state.desire,
                desire: action.data
            }
        case SET_MASTURBATION_DATA:
            return {
                ...state,
                masturbation: action.data
            }
        case SET_SEX_DATA:
            return {
                ...state,
                sex: action.data
            }
    }
    return state
}

export default desire;
</code>```

Updated Store.desire

答:
Try this: </p>

```<code>function desire (state = initialState, action) {
    //var action
    //{
    //    desire: 3,
    //    date: Wed Jun 07 2017 23:45:41 GMT+0100 (BST)
    //}
    switch (action.type) {
        case SET_DESIRE_DATA:
            //Date returned 07_06_2017
            const key = Moment(action.data.date).format('D-MM-YYYY')
            const desire = Object.assign({}, state.desire);
            desire[key] = action.data
            return {
                ...state.desire,
                desire,
            }
        case SET_MASTURBATION_DATA:
          //similar code here
    }
    return state
}

export default desire;
</code>```

Body:
I am trying to add multiple objects into desire's object and store all of the desires that are collected inside this object. I am trying to set the key to the the date that it was set on, thus having an individual key for each record.

However all that is happening I end up with having an desire object in the state, which gets overwritten each time of writing and also sex and masturbation are removed with each update.

I know I should be able to get this, but its late and I'm stuck :D

Reducer

import Moment from 'moment';
import {
  SET_DESIRE_DATA,
  SET_MASTURBATION_DATA,
  SET_SEX_DATA
} from '../actions/dataAction';

const initialState = {
  'desire': {},
    'masturbation': {},
    'sex': {}
};

function desire (state = initialState, action) {
    //var action
    //{
    //    desire: 3,
    //    date: Wed Jun 07 2017 23:45:41 GMT+0100 (BST)
    //}
    switch (action.type) {
        case SET_DESIRE_DATA:
            //Date returned 07_06_2017
            //Moment(action.data.date).format('D-MM-YYYY')
            return {
                ...state.desire,
                desire: action.data
            }
        case SET_MASTURBATION_DATA:
            return {
                ...state,
                masturbation: action.data
            }
        case SET_SEX_DATA:
            return {
                ...state,
                sex: action.data
            }
    }
    return state
}

export default desire;

Updated Store.desire

Body:
Try this:

function desire (state = initialState, action) {
    //var action
    //{
    //    desire: 3,
    //    date: Wed Jun 07 2017 23:45:41 GMT+0100 (BST)
    //}
    switch (action.type) {
        case SET_DESIRE_DATA:
            //Date returned 07_06_2017
            const key = Moment(action.data.date).format('D-MM-YYYY')
            const desire = Object.assign({}, state.desire);
            desire[key] = action.data
            return {
                ...state.desire,
                desire,
            }
        case SET_MASTURBATION_DATA:
          //similar code here
    }
    return state
}

export default desire;


问:
WPF/C# Application Command Line Parms
I have an application that takes various command line parameters. This works fine but I need to make a change and I was wanting some input as to the best way to handle this change.

Currently:

The application two gets called from application one. I do not have control over application one to pass it through as a reference to application two.

I pass the command line parameters needed from application one to application two as such:

applicationtwo.exe /AA username filename.txt

Change:

The initial load of the program is slow due to the connection to SQL Server. It's not horribly slow, we just have people on the phone with customers that do not want to wait 3-4 each time it opens.

I was thinking I could keep it running in the task bar and bringing it to the front once it's a called again, only allowing one instance of the program to open. I wasn't sure how to get the parameters back to it like I do the command line way though.

Anyone have a good suggestion on how to handle this?

Thanks as usual!

答:
Are these command line parameters constantly changing based on the other application? If not why not make use of Application/User Settings to store them? This way the application will always have a reference to the settings since you are going to allow it to remain running via the task bar. If you do not want to use the Application/User Settings then simply storing a reference to the passed in arguments in a Singleton somewhere in your app should suffice.

If the values are indeed dynamic and changing then knowing how the parameters come down via application 1 would be needed. If they are fed to a file on the disk then your application 2 could simply read in that file periodically or initiated by the user on demand.

ContentLicense: CC BY-SA 2.5

Title: WPF/C# Application Command Line Parms


问:
Unable to parse required data from nested arrays in json using python
When I tried with my script, I do get response but can't parse the Name and Email from this response as I never worked with json arrays. Hope there is somebody to give me an idea. I tried with:

```<code>import requests
from urllib.parse import urlencode
url = 'https://oresapp.asicanada.net/ores.imis.services/api/member/?'
address = '&callback=angular.callbacks._0&city=&companyName=&personName='
xhr = url + urlencode({'address':address})
j = requests.get(xhr).json()
print(j)
</code>```

And the partial response is like:

```<code>[{'EmailAddress': '', 'Zip': '', 'Members': [{'Fax': '', 'FirstLastName': 'Ryley Reat', 'Id': 46648, 'FirstName': 'Ryley', 'FullName': 'Ryley Reat', 'Email': 'zolo@zolo.ca', 'LastName': 'Reat', 'LocationId': 46647, 'Phone': '', 'WebSite': ''}], 'ProvinceCode': '', 'CityRanking': 1.0, 'WorkPhone': '', 'Website': '', 'GeoCodeAddress': 'CANADA', 'GeoCode': {'latitude': 56.130366, 'longitude': -106.346771}, 'City': '', 'FullAddress': 'CANADA', 'Id': 46647, 'Fax': '', 'CompanyNameRanking': 1.0, 'Company': 'Zolo Realty Inc.', 'Country': 'Canada', 'BrokerName': ' '}, {'EmailAddress': '', 'Zip': 'T3H 4W2', 'Members': [{'Fax': '', 'FirstLastName': 'David SandBrand', 'Id': 46646, 'FirstName': 'David', 'FullName': 'David SandBrand', 'Email': 'david@sandbrand.com', 'LastName': 'SandBrand', 'LocationId': 46645, 'Phone': '', 'WebSite': ''}], 'ProvinceCode': 'AB', 'CityRanking': 1.0, 'WorkPhone': '', 'Website': '', 'GeoCodeAddress': '146 West Springs Pl SW Calgary, AB  T3H 4W2 CANADA', 'GeoCode': {'latitude': 51.0626195, 'longitude': -114.1907432}, 'City': 'Calgary', 'FullAddress': '146 West Springs Pl SW Calgary, AB  T3H 4W2 CANADA', 'Id': 46645, 'Fax': '', 'CompanyNameRanking': 1.0, 'Company': 'Damecca Holdings Ltd', 'Country': 'Canada', 'BrokerName': ' '}, {'EmailAddress': 'c.reception@century21.ca', 'Zip': 'S9V 0N7', 'Members': [{'Fax': '', 'FirstLastName': 'Alex Palmer', 'Id': 45347, 'FirstName': 'Alex', 'FullName': 'Alex Palmer', 'Email': 'alex.palmer@century21.ca', 'LastName': 'Palmer', 'LocationId': 37526, 'Phone': '(306) 821-0138', 'WebSite': ''}, {'Fax': '', 'FirstLastName': 'Becky Hofer', 'Id': 45379, 'FirstName': 'Becky', 'FullName': 'Becky Hofer', 'Email': 'becky.hofer@century21.ca', 'LastName': 'Hofer', 'LocationId': 37526, 'Phone': '(306) 830-9740', 'WebSite': ''}, {'Fax': '', 'FirstLastName': 'Cheryl Fairweather', 'Id': 45346, 'FirstName': 'Cheryl', 'FullName': 'Cheryl Fairweather', 'Email': 'cheryl.fariweather@century21.ca', 'LastName': 'Fairweather', 'LocationId': 37526, 'Phone': '(780) 808-9406', 'WebSite': ''}, {'Fax': '', 'FirstLastName': 'Chris Hassall', 'Id': 45334, 'FirstName': 'Chris', 'FullName': 'Chris Hassall', 'Email': 'chris.hassall@century21.ca', 'LastName': 'Hassall', 'LocationId': 37526, 'Phone': '(780) 871-3838', 'WebSite': ''}
</code>```

答:
Finally found the solution:</p>

```<code>import requests
from urllib.parse import urlencode
url = 'https://oresapp.asicanada.net/ores.imis.services/api/member/?'
address = '&callback=angular.callbacks._0&city=&companyName=&personName='
xhr = url + urlencode({'address':address})
j = requests.get(xhr).json()
for item in j:
    print(item['Members'][0]['FirstLastName'],item['Members'][0]['Email'], item['Members'][0]['Phone'])
</code>```

Body:
When I tried with my script, I do get response but can't parse the Name and Email from this response as I never worked with json arrays. Hope there is somebody to give me an idea. I tried with:

import requests
from urllib.parse import urlencode
url = 'https://oresapp.asicanada.net/ores.imis.services/api/member/?'
address = '&callback=angular.callbacks._0&city=&companyName=&personName='
xhr = url + urlencode({'address':address})
j = requests.get(xhr).json()
print(j)

And the partial response is like:

[{'EmailAddress': '', 'Zip': '', 'Members': [{'Fax': '', 'FirstLastName': 'Ryley Reat', 'Id': 46648, 'FirstName': 'Ryley', 'FullName': 'Ryley Reat', 'Email': 'zolo@zolo.ca', 'LastName': 'Reat', 'LocationId': 46647, 'Phone': '', 'WebSite': ''}], 'ProvinceCode': '', 'CityRanking': 1.0, 'WorkPhone': '', 'Website': '', 'GeoCodeAddress': 'CANADA', 'GeoCode': {'latitude': 56.130366, 'longitude': -106.346771}, 'City': '', 'FullAddress': 'CANADA', 'Id': 46647, 'Fax': '', 'CompanyNameRanking': 1.0, 'Company': 'Zolo Realty Inc.', 'Country': 'Canada', 'BrokerName': ' '}, {'EmailAddress': '', 'Zip': 'T3H 4W2', 'Members': [{'Fax': '', 'FirstLastName': 'David SandBrand', 'Id': 46646, 'FirstName': 'David', 'FullName': 'David SandBrand', 'Email': 'david@sandbrand.com', 'LastName': 'SandBrand', 'LocationId': 46645, 'Phone': '', 'WebSite': ''}], 'ProvinceCode': 'AB', 'CityRanking': 1.0, 'WorkPhone': '', 'Website': '', 'GeoCodeAddress': '146 West Springs Pl SW Calgary, AB  T3H 4W2 CANADA', 'GeoCode': {'latitude': 51.0626195, 'longitude': -114.1907432}, 'City': 'Calgary', 'FullAddress': '146 West Springs Pl SW Calgary, AB  T3H 4W2 CANADA', 'Id': 46645, 'Fax': '', 'CompanyNameRanking': 1.0, 'Company': 'Damecca Holdings Ltd', 'Country': 'Canada', 'BrokerName': ' '}, {'EmailAddress': 'c.reception@century21.ca', 'Zip': 'S9V 0N7', 'Members': [{'Fax': '', 'FirstLastName': 'Alex Palmer', 'Id': 45347, 'FirstName': 'Alex', 'FullName': 'Alex Palmer', 'Email': 'alex.palmer@century21.ca', 'LastName': 'Palmer', 'LocationId': 37526, 'Phone': '(306) 821-0138', 'WebSite': ''}, {'Fax': '', 'FirstLastName': 'Becky Hofer', 'Id': 45379, 'FirstName': 'Becky', 'FullName': 'Becky Hofer', 'Email': 'becky.hofer@century21.ca', 'LastName': 'Hofer', 'LocationId': 37526, 'Phone': '(306) 830-9740', 'WebSite': ''}, {'Fax': '', 'FirstLastName': 'Cheryl Fairweather', 'Id': 45346, 'FirstName': 'Cheryl', 'FullName': 'Cheryl Fairweather', 'Email': 'cheryl.fariweather@century21.ca', 'LastName': 'Fairweather', 'LocationId': 37526, 'Phone': '(780) 808-9406', 'WebSite': ''}, {'Fax': '', 'FirstLastName': 'Chris Hassall', 'Id': 45334, 'FirstName': 'Chris', 'FullName': 'Chris Hassall', 'Email': 'chris.hassall@century21.ca', 'LastName': 'Hassall', 'LocationId': 37526, 'Phone': '(780) 871-3838', 'WebSite': ''}

Body:
Finally found the solution:

import requests
from urllib.parse import urlencode
url = 'https://oresapp.asicanada.net/ores.imis.services/api/member/?'
address = '&callback=angular.callbacks._0&city=&companyName=&personName='
xhr = url + urlencode({'address':address})
j = requests.get(xhr).json()
for item in j:
    print(item['Members'][0]['FirstLastName'],item['Members'][0]['Email'], item['Members'][0]['Phone'])


问:
How to connect to an RDS database from Yii2?
I have deployed a Yii2 based app onto AWS Elastic Beanstalk, also I have created the RDS instance with a database (it already has tables) on Elastic Beanstalk. However I received this error: "SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known"

All the files are uploaded correctly to the AWS instance.

The file /common/config/main-local.php has:

```<code>'components' => [
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=',
            'dsn' => 'mysql:host=RDS_HOSTNAME:RDS_PORT;dbname=RDS_DB_NAME',
            'username' => 'RDS_USERNAME',
            'password' => 'RDS_PASSWORD',
            'charset' => 'utf8',
        ],
</code>```

What could be wrong? Thanks.

答:
You have 2 times your 'dsn' line and maybe the first one survives, so changing your config to this should work:

```<code>'components' => [
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=RDS_HOSTNAME:RDS_PORT;dbname=RDS_DB_NAME',
            'username' => 'RDS_USERNAME',
            'password' => 'RDS_PASSWORD',
            'charset' => 'utf8',
        ],
</code>```

(In addition I hope you are aware that you have to change RDS_* parameters :D)

Body:
I have deployed a Yii2 based app onto AWS Elastic Beanstalk, also I have created the RDS instance with a database (it already has tables) on Elastic Beanstalk. However I received this error: "SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known"

All the files are uploaded correctly to the AWS instance.

The file /common/config/main-local.php has:

'components' => [
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=',
            'dsn' => 'mysql:host=RDS_HOSTNAME:RDS_PORT;dbname=RDS_DB_NAME',
            'username' => 'RDS_USERNAME',
            'password' => 'RDS_PASSWORD',
            'charset' => 'utf8',
        ],

What could be wrong? Thanks.

Body:
You have 2 times your 'dsn' line and maybe the first one survives, so changing your config to this should work:

'components' => [
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=RDS_HOSTNAME:RDS_PORT;dbname=RDS_DB_NAME',
            'username' => 'RDS_USERNAME',
            'password' => 'RDS_PASSWORD',
            'charset' => 'utf8',
        ],

(In addition I hope you are aware that you have to change RDS_* parameters :D)


问:
JDBC Template in Spring giving exception
So I have tried many changes and what not, but I am not sure what the heck is going wrong with my code. This is my first project in Spring. I am being given a null pointer exception with my sql methods.

My JdbcDAO.java

```<code>import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.jdbc.datasource.*;
import org.springframework.stereotype.Repository;

/**
 * Created by Albedo on 6/6/2017.
 */

@Repository("reviewDAO")
public class JdbcReviewDAO {
    private DataSource dataSource;
    private JdbcTemplate jdbcTemplate;

    @Autowired
    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    @Bean
    public JdbcTemplate getTemplate(){
        return jdbcTemplate;
    }

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate){
        this.jdbcTemplate = jdbcTemplate;
    }

    // sql methods go here
}
</code>```

My spring-Datasource.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <bean id="dataSource"
          class="org.springframework.jdbc.datasource.DriverManagerDataSource">

        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/" />
        <property name="username" value="root" />
        <property name="password" value="admin" />
                </bean>
 <bean id="reviewDAO" class="com.JdbcReviewDAO">
    <property name="dataSource" ref="dataSource" />
</bean>
</beans>
</code>```

My application.java:

```<code>import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        //ApplicationContext context =
        //      new ClassPathXmlApplicationContext("Spring-Review.xml");
        JdbcReviewDAO reviewDAO = new JdbcReviewDAO();
        reviewDAO.grabFirstPost(1);
        SpringApplication.run(Application.class, args);
    }
}
</code>```

(I have removed package names - rest assured they are properly defined in the project. As well with SQL methods to remove redundancy. Let me know if I should include them if you suspect they are the problem.) I think this is more an 'infrastructure' issue(forgive my ignorance, still a noobie) rather than code. Anyone have an idea?

Error log: \

```<code>Exception in thread "main" java.lang.NullPointerException
    at JdbcDAO.grabFirstPost(JdbcDAO.java:63)
    at Application.main(Application.java:15)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

Process finished with exit code 1
</code>```

Method* that gives the error:

```<code>public String grabFirstPost(int id) {
    String sql = "SELECT * FROM post WHERE postid ='" + id + "'";

    String postContent = (String)jdbcTemplate.queryForObject(sql, new Object[] {id}, String.class);
    return postContent;
}
</code>```

答: Looks like the variable jdbcTemplate contains null. The most likely cause is that Spring does not inject it, because the setter is not annotated with @Autowired.

Body:
So I have tried many changes and what not, but I am not sure what the heck is going wrong with my code. This is my first project in Spring. I am being given a null pointer exception with my sql methods.

My JdbcDAO.java

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.jdbc.datasource.*;
import org.springframework.stereotype.Repository;

/**
 * Created by Albedo on 6/6/2017.
 */

@Repository("reviewDAO")
public class JdbcReviewDAO {
    private DataSource dataSource;
    private JdbcTemplate jdbcTemplate;

    @Autowired
    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    @Bean
    public JdbcTemplate getTemplate(){
        return jdbcTemplate;
    }

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate){
        this.jdbcTemplate = jdbcTemplate;
    }

    // sql methods go here
}

My spring-Datasource.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <bean id="dataSource"
          class="org.springframework.jdbc.datasource.DriverManagerDataSource">

        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/" />
        <property name="username" value="root" />
        <property name="password" value="admin" />
                </bean>
 <bean id="reviewDAO" class="com.JdbcReviewDAO">
    <property name="dataSource" ref="dataSource" />
</bean>
</beans>

My application.java:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        //ApplicationContext context =
        //      new ClassPathXmlApplicationContext("Spring-Review.xml");
        JdbcReviewDAO reviewDAO = new JdbcReviewDAO();
        reviewDAO.grabFirstPost(1);
        SpringApplication.run(Application.class, args);
    }
}

(I have removed package names - rest assured they are properly defined in the project. As well with SQL methods to remove redundancy. Let me know if I should include them if you suspect they are the problem.) I think this is more an 'infrastructure' issue(forgive my ignorance, still a noobie) rather than code. Anyone have an idea?

Error log: \

Exception in thread "main" java.lang.NullPointerException
    at JdbcDAO.grabFirstPost(JdbcDAO.java:63)
    at Application.main(Application.java:15)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

Process finished with exit code 1

Method* that gives the error:

public String grabFirstPost(int id) {
    String sql = "SELECT * FROM post WHERE postid ='" + id + "'";

    String postContent = (String)jdbcTemplate.queryForObject(sql, new Object[] {id}, String.class);
    return postContent;
}


问:
Chose next proxy from listbox with timer vb.net
Hi start a new application to generate traffic and i have 3 list boxs one for the referral links , one for the proxys , and one for the users agents.
My question is i have add tree timers to my form and i need to change the referral link on the textbox each 10 secs for example
How can i archive this?
This is my code</p>

```<code>Imports System.Runtime.InteropServices
Imports System.Net
Imports System
Public Class Form3
Dim FILE_NAME As String = "C:\proxy.txt"
Dim x As Integer
Dim rfe As Integer
Dim prx As Integer
Dim users As Integer
Dim label As String
Public proxy(2000) As String
Public index As Integer = 0
Public max_proxys As Integer = 0
Dim a As String
Dim start_check As Integer = 0
<Runtime.InteropServices.DllImport("wininet.dll", SetLastError:=True)> _
Private Shared Function InternetSetOption(ByVal hInternet As IntPtr, ByVal dwOption As Integer, ByVal lpBuffer As IntPtr, ByVal lpdwBufferLength As Integer) As Boolean
End Function
Public Structure Struct_INTERNET_PROXY_INFO
    Public dwAccessType As Integer
    Public proxy As IntPtr
    Public proxyBypass As IntPtr
End Structure
Private Sub UseProxy(ByVal strProxy As String)
    Const INTERNET_OPTION_PROXY As Integer = 38
    Const INTERNET_OPEN_TYPE_PROXY As Integer = 3

    Dim struct_IPI As Struct_INTERNET_PROXY_INFO

    struct_IPI.dwAccessType = INTERNET_OPEN_TYPE_PROXY
    struct_IPI.proxy = Marshal.StringToHGlobalAnsi(strProxy)
    struct_IPI.proxyBypass = Marshal.StringToHGlobalAnsi("local")

    Dim intptrStruct As IntPtr = Marshal.AllocCoTaskMem(Marshal.SizeOf(struct_IPI))

    Marshal.StructureToPtr(struct_IPI, intptrStruct, True)

    Dim iReturn As Boolean = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_PROXY, intptrStruct, System.Runtime.InteropServices.Marshal.SizeOf(struct_IPI))
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Timer1.Enabled = True

End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Timerreferrals.Enabled = True
    UseProxy(Label8.Text)
    Dim wr As HttpWebRequest = HttpWebRequest.Create(TextBox1.Text)
    wr.Referer = TextBox5.Text
    wr.UserAgent = "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36"
    Dim resp As HttpWebResponse = wr.GetResponse
    WebBrowser1.Navigate(TextBox1.Text)
    Button1.Enabled = False
    Button2.Enabled = True
    Button3.Enabled = True
End Sub

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    Timer1.Enabled = False
    Button1.Enabled = True
    Button2.Enabled = False
    Button3.Enabled = False
End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick

    x = x + 1
    If x = TextBox2.Text Then
        WebBrowser1.Refresh()
        x = 0
        Label4.Text = Val(Label4.Text) + 1

    End If
End Sub

Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    TextBox2.Text = 10
End Sub

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
    Label8.Text = (TextBox3.Text & ":" & TextBox4.Text)
End Sub

Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
    If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then

        Dim path As String = OpenFileDialog1.FileName

        ListBox1.Items.AddRange(System.IO.File.ReadAllLines(path))

    End If

End Sub

Private Sub Label13_Click(sender As Object, e As EventArgs) Handles Label13.Click
    ListBox1.Items.Clear()

End Sub

Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
    If OpenFileDialog2.ShowDialog = Windows.Forms.DialogResult.OK Then

        Dim path As String = OpenFileDialog2.FileName

        ListBox2.Items.AddRange(System.IO.File.ReadAllLines(path))

    End If
End Sub

Private Sub Label14_Click(sender As Object, e As EventArgs) Handles Label14.Click
    ListBox2.Items.Clear()

End Sub

Private Sub Label15_Click(sender As Object, e As EventArgs) Handles Label15.Click
    ListBox4.Items.Clear()

End Sub

Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
    If OpenFileDialog3.ShowDialog = Windows.Forms.DialogResult.OK Then

        Dim path As String = OpenFileDialog3.FileName

        ListBox4.Items.AddRange(System.IO.File.ReadAllLines(path))

    End If
End Sub

Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timerreferrals.Tick
    rfe = rfe + 1
    Dim counthit = 0
    TextBox5.Text = ListBox1.Text
    Label17.Text = rfe
    Timerreferrals.Interval = 1000
    Dim sb As New System.Text.StringBuilder()
    If rfe = TextBox6.Text Then
        For Each o As Object In ListBox1.Items
            'sb.AppendLine(o)
            'TextBox5.Text = sb.ToString
            ' rfe = 0
            counthit = counthit + 1

        Next
        ListBox1.SelectedIndex = Me.ListBox1.SelectedIndex + 1

        TextBox5.Text = ListBox1.Text
        rfe = 0
    End If

    If TextBox6.Text = "" Then
        Return

    End If

End Sub
End Class
</code>```

答:
My question is i have manage to get each time the timer its finish to
  change the current item from a listbox but the wen its come the final
  item its make a error out of range ... how can i detect wen there is
  no more items there and go the first again

Gotcha...so change:

```<code>ListBox1.SelectedIndex = Me.ListBox1.SelectedIndex + 1
</code>```

To something like:

```<code>If Me.ListBox1.SelectedIndex < Me.ListBox1.Items.Count - 1 Then
    Me.ListBox1.SelectedIndex = Me.ListBox1.SelectedIndex + 1
Else
    Me.ListBox1.SelectedIndex = 0
End If
</code>```

Body:
Hi start a new application to generate traffic and i have 3 list boxs one for the referral links , one for the proxys , and one for the users agents.
My question is i have add tree timers to my form and i need to change the referral link on the textbox each 10 secs for example
How can i archive this?
This is my code

Imports System.Runtime.InteropServices
Imports System.Net
Imports System
Public Class Form3
Dim FILE_NAME As String = "C:\proxy.txt"
Dim x As Integer
Dim rfe As Integer
Dim prx As Integer
Dim users As Integer
Dim label As String
Public proxy(2000) As String
Public index As Integer = 0
Public max_proxys As Integer = 0
Dim a As String
Dim start_check As Integer = 0
<Runtime.InteropServices.DllImport("wininet.dll", SetLastError:=True)> _
Private Shared Function InternetSetOption(ByVal hInternet As IntPtr, ByVal dwOption As Integer, ByVal lpBuffer As IntPtr, ByVal lpdwBufferLength As Integer) As Boolean
End Function
Public Structure Struct_INTERNET_PROXY_INFO
    Public dwAccessType As Integer
    Public proxy As IntPtr
    Public proxyBypass As IntPtr
End Structure
Private Sub UseProxy(ByVal strProxy As String)
    Const INTERNET_OPTION_PROXY As Integer = 38
    Const INTERNET_OPEN_TYPE_PROXY As Integer = 3

    Dim struct_IPI As Struct_INTERNET_PROXY_INFO

    struct_IPI.dwAccessType = INTERNET_OPEN_TYPE_PROXY
    struct_IPI.proxy = Marshal.StringToHGlobalAnsi(strProxy)
    struct_IPI.proxyBypass = Marshal.StringToHGlobalAnsi("local")

    Dim intptrStruct As IntPtr = Marshal.AllocCoTaskMem(Marshal.SizeOf(struct_IPI))

    Marshal.StructureToPtr(struct_IPI, intptrStruct, True)

    Dim iReturn As Boolean = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_PROXY, intptrStruct, System.Runtime.InteropServices.Marshal.SizeOf(struct_IPI))
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Timer1.Enabled = True

End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Timerreferrals.Enabled = True
    UseProxy(Label8.Text)
    Dim wr As HttpWebRequest = HttpWebRequest.Create(TextBox1.Text)
    wr.Referer = TextBox5.Text
    wr.UserAgent = "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36"
    Dim resp As HttpWebResponse = wr.GetResponse
    WebBrowser1.Navigate(TextBox1.Text)
    Button1.Enabled = False
    Button2.Enabled = True
    Button3.Enabled = True
End Sub

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    Timer1.Enabled = False
    Button1.Enabled = True
    Button2.Enabled = False
    Button3.Enabled = False
End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick

    x = x + 1
    If x = TextBox2.Text Then
        WebBrowser1.Refresh()
        x = 0
        Label4.Text = Val(Label4.Text) + 1

    End If
End Sub

Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    TextBox2.Text = 10
End Sub

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
    Label8.Text = (TextBox3.Text & ":" & TextBox4.Text)
End Sub

Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
    If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then

        Dim path As String = OpenFileDialog1.FileName

        ListBox1.Items.AddRange(System.IO.File.ReadAllLines(path))

    End If

End Sub

Private Sub Label13_Click(sender As Object, e As EventArgs) Handles Label13.Click
    ListBox1.Items.Clear()

End Sub

Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
    If OpenFileDialog2.ShowDialog = Windows.Forms.DialogResult.OK Then

        Dim path As String = OpenFileDialog2.FileName

        ListBox2.Items.AddRange(System.IO.File.ReadAllLines(path))

    End If
End Sub

Private Sub Label14_Click(sender As Object, e As EventArgs) Handles Label14.Click
    ListBox2.Items.Clear()

End Sub

Private Sub Label15_Click(sender As Object, e As EventArgs) Handles Label15.Click
    ListBox4.Items.Clear()

End Sub

Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
    If OpenFileDialog3.ShowDialog = Windows.Forms.DialogResult.OK Then

        Dim path As String = OpenFileDialog3.FileName

        ListBox4.Items.AddRange(System.IO.File.ReadAllLines(path))

    End If
End Sub

Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timerreferrals.Tick
    rfe = rfe + 1
    Dim counthit = 0
    TextBox5.Text = ListBox1.Text
    Label17.Text = rfe
    Timerreferrals.Interval = 1000
    Dim sb As New System.Text.StringBuilder()
    If rfe = TextBox6.Text Then
        For Each o As Object In ListBox1.Items
            'sb.AppendLine(o)
            'TextBox5.Text = sb.ToString
            ' rfe = 0
            counthit = counthit + 1

        Next
        ListBox1.SelectedIndex = Me.ListBox1.SelectedIndex + 1

        TextBox5.Text = ListBox1.Text
        rfe = 0
    End If

    If TextBox6.Text = "" Then
        Return

    End If

End Sub
End Class

Body:
My question is i have manage to get each time the timer its finish to
  change the current item from a listbox but the wen its come the final
  item its make a error out of range ... how can i detect wen there is
  no more items there and go the first again

Gotcha...so change:

ListBox1.SelectedIndex = Me.ListBox1.SelectedIndex + 1

To something like:

If Me.ListBox1.SelectedIndex < Me.ListBox1.Items.Count - 1 Then
    Me.ListBox1.SelectedIndex = Me.ListBox1.SelectedIndex + 1
Else
    Me.ListBox1.SelectedIndex = 0
End If


问:
Python Stale Element Reference: Element not attached to page document
having trouble getting around Stale Element reference. I think the innerArticles array is at fault, as it is controlling the whole for loop. After I refresh explicitly i get stale element exception.

Esentially I want the page to keep refreshing until the 'Text' in SubItems xpath has appeared on the page. As I do not know when this will occur I need to start and keep reloading.

Any help is appreciated.

Code:

```<code>innerArticles = driver.find_elements_by_xpath("//div[@class='inner-article']")

for links in innerArticles:
    print('inFor')

    SubItems = links.find_elements_by_xpath("//a[text()='Text']")

    iterator = 0
    if len(SubItems) < 1:
        print('Sub < 1')
        while iterator < 5:
            print('While', iterator)

            time.sleep(1)  # sleep 1 seconds to refresh again
            iterator = iterator + 1  # iterate
            driver.refresh()  # refresh
            SubItems = links.find_elements_by_xpath("//a[text()='Text']")
            break
            if len(SubItems) > 0:
                print('break')
                break

    if len(SubItems) > 0:
        print('SecondIf')
        if links.text.startswith('SText') and links.text.endswith('SText'):
            links.click()
</code>```

答:
When you are doing the explicit refresh, the links object will not longer be valid and will throw the StaleElementReferenceException. You should get that element again after the refresh. You can try something like below:

```<code>innerArticles = driver.find_elements_by_xpath("//div[@class='inner-article']")

for i in range(len(innerArticles)):
    print('inFor')

    SubItems = driver.find_elements_by_xpath("//div[@class='inner-article']")[i].find_elements_by_xpath("//a[text()='Text']")

    iterator = 0
    if len(SubItems) < 1:
        print('Sub < 1')
        while iterator < 5:
            print('While', iterator)

            time.sleep(1)  # sleep 1 seconds to refresh again
            iterator = iterator + 1  # iterate
            driver.refresh()  # refresh
            SubItems = driver.find_elements_by_xpath("//div[@class='inner-article']")[i].find_elements_by_xpath("//a[text()='Text']")
            break
            if len(SubItems) > 0:
                print('break')
                break

    if len(SubItems) > 0:
        print('SecondIf')
        links = driver.find_elements_by_xpath("//div[@class='inner-article']")[i]
        if links.text.startswith('SText') and links.text.endswith('SText'):
            links.click()
</code>```

Body:
having trouble getting around Stale Element reference. I think the innerArticles array is at fault, as it is controlling the whole for loop. After I refresh explicitly i get stale element exception.

Esentially I want the page to keep refreshing until the 'Text' in SubItems xpath has appeared on the page. As I do not know when this will occur I need to start and keep reloading.

Any help is appreciated.

Code:

innerArticles = driver.find_elements_by_xpath("//div[@class='inner-article']")

for links in innerArticles:
    print('inFor')

    SubItems = links.find_elements_by_xpath("//a[text()='Text']")

    iterator = 0
    if len(SubItems) < 1:
        print('Sub < 1')
        while iterator < 5:
            print('While', iterator)

            time.sleep(1)  # sleep 1 seconds to refresh again
            iterator = iterator + 1  # iterate
            driver.refresh()  # refresh
            SubItems = links.find_elements_by_xpath("//a[text()='Text']")
            break
            if len(SubItems) > 0:
                print('break')
                break

    if len(SubItems) > 0:
        print('SecondIf')
        if links.text.startswith('SText') and links.text.endswith('SText'):
            links.click()

Body:
When you are doing the explicit refresh, the links object will not longer be valid and will throw the StaleElementReferenceException. You should get that element again after the refresh. You can try something like below:

innerArticles = driver.find_elements_by_xpath("//div[@class='inner-article']")

for i in range(len(innerArticles)):
    print('inFor')

    SubItems = driver.find_elements_by_xpath("//div[@class='inner-article']")[i].find_elements_by_xpath("//a[text()='Text']")

    iterator = 0
    if len(SubItems) < 1:
        print('Sub < 1')
        while iterator < 5:
            print('While', iterator)

            time.sleep(1)  # sleep 1 seconds to refresh again
            iterator = iterator + 1  # iterate
            driver.refresh()  # refresh
            SubItems = driver.find_elements_by_xpath("//div[@class='inner-article']")[i].find_elements_by_xpath("//a[text()='Text']")
            break
            if len(SubItems) > 0:
                print('break')
                break

    if len(SubItems) > 0:
        print('SecondIf')
        links = driver.find_elements_by_xpath("//div[@class='inner-article']")[i]
        if links.text.startswith('SText') and links.text.endswith('SText'):
            links.click()


问:
SAP - Code Coverage Analyzer Results
I'm trying to extract the results from my Code Coverage analysis from my own abap program from the database in SAP.

At the following website Coverage Analyzer: Technology I find this information:
Initially, RSCVR_COLLECT transfers data to the 'staging area' of table COVRES0. Finally, the new data is aggregated with the statistics in tables COVRES and COVREF, among others.

In the table COVRES i can see one row where my program is listed but there are no further information about statistics like branch coverage, etc.

Can anybody give me a hint, where I can find the results of the Code Coverage Analyzer, so I am able to extract them for further processing?

Best regards
Bernhard

答:
Copied from the comments above:

Instead of using the code for Code Coverage Analyzer (scov), use the Coverage API.

Interfaces IF_SCV* in SE24

Title: SAP - Code Coverage Analyzer Results


问:
Best way to download and install Eclipse if you want to do C++ and Java and GUI design
I'm interested in using Eclipse. The Eclipse Downloads page has versions for Java Developers for Java EE Developers for C/C++ developers, and so on. I want to use Eclipse for Java, C/C++, GUI design, and more. There doesn't seem to be a single download that has it all. Am I missing something? Or is there an easy way to download and install all of the components.

And then it's a big pain every time they upgrade, as I have to do it all over again, and it seems that I have to do it again for every machine. Can I simply move the Eclipse folder form one machine to another?

答:
In addition, if you want to browse Eclipse plugins by category, resolve plugin dependencies, and download the complete plugin-included Eclipse package as a single .zip, you can use Yoxos.

http://eclipsesource.com/en/yoxos/


问:
Eval list within quotes
I am writing a program in Python that takes in user input (not using Python's built-in input) that is a string that contains a list of strings, ie. '["hello", "world"]'. However, some inputs will have multiple quotes inside, ie. '["Hello", "wor"ld"]'. I need the string to always eval() to a list. Any advice on cleansing the input string to ensure that it will always eval? Already tried .replace('"', '\"').

答:
I almost hate myself for doing this, but it may actually work. First, select a symbol that is not going to be entered by the user, ever (e.g., 字 or ~). Then, remove the valid quotation marks at the beginning at the end and replace all valid quotation marks between items by that symbol:

```<code>s = '["Hello", "wor",ld"  , " ]'
s1 = re.sub(r"(\[\s*\")|(\"\s*,?\s*\])", "", s)
# 'Hello", "wor",ld"  , '
s1 = re.sub(r"\"\s*,\s*\"", "字", s1)
# 'Hello字wor",ld"  , '
</code>```

Finally, escape all remaining double quotes, replace the funny symbols with the item separators, and add the brackets:

```<code>result = '["' + s1.replace('"', r'\"').replace("字",'","') + '"]'
#'["Hello","wor\\",ld\\"  , "]'
ast.literal_eval(result)
#['Hello', 'wor",ld"  , ']
</code>```

Title: Eval list within quotes

Body:
I almost hate myself for doing this, but it may actually work. First, select a symbol that is not going to be entered by the user, ever (e.g., 字 or ~). Then, remove the valid quotation marks at the beginning at the end and replace all valid quotation marks between items by that symbol:

s = '["Hello", "wor",ld"  , " ]'
s1 = re.sub(r"(\[\s*\")|(\"\s*,?\s*\])", "", s)
# 'Hello", "wor",ld"  , '
s1 = re.sub(r"\"\s*,\s*\"", "字", s1)
# 'Hello字wor",ld"  , '

Finally, escape all remaining double quotes, replace the funny symbols with the item separators, and add the brackets:

result = '["' + s1.replace('"', r'\"').replace("字",'","') + '"]'
#'["Hello","wor\\",ld\\"  , "]'
ast.literal_eval(result)
#['Hello', 'wor",ld"  , ']


问:
How to scrape non-standard HTML with Nokogiri
How can I unpack a non-standard HTML:

```<code><body>
    <div class="open">
        <div style='style'>Raw name 1</div>
        <p>Text_1</p>
        <p>Text_2</p>
        <p>Text_3</p>
        <p>Text_4</p>
        <p>Text_5</p>
        <div style='style'>Raw name 5</div>
        <p>Text_1</p>
        <p>Text_2</p>
        <p>Text_3</p>
        <p>Text_4</p>
        <p>Text_5</p>
    </div>
</body>
</code>```

I want to get a result similar to:

```<code>['Raw name 1', Text_1, Text_2, Text_3, Text_4, Text_5]
...
['Raw name 5', Text_1, Text_2, Text_3, Text_4, Text_5]
</code>```

I tried to do something on this example How to parse a HTML table with Nokogiri?, but nothing happened.

Is it possible to obtain information that I want from such HTML?

答:
I'd do something like:

```<code>require 'nokogiri'

doc = Nokogiri::HTML(<<EOT)
<body>
    <div class="open">
        <div style='style'>Raw name 1</div>
        <p>Text_1</p>
        <p>Text_2</p>
        <div style='style'>Raw name 5</div>
        <p>Text_1</p>
        <p>Text_2</p>
    </div>
</body>
EOT

doc.at('.open').elements.slice_before { |e| e.name == 'div' }.map { |ary|
  ary.map(&:text)
}
# => [["Raw name 1", "Text_1", "Text_2"], ["Raw name 5", "Text_1", "Text_2"]]
</code>```

Breaking it down a bit:

```<code>doc.at('.open').elements.map(&:name) # => ["div", "p", "p", "div", "p", "p"]
doc.at('.open').elements.slice_before { |e| e.name == 'div' }.map { |a| a.map(&:name) } # => [["div", "p", "p"], ["div", "p", "p"]]
</code>```

elements and slice_before are the magic here.

Body:
How can I unpack a non-standard HTML:

Raw name 1

Text_1

Text_2

Text_3

Text_4

Text_5

Raw name 5

Text_1

Text_2

Text_3

Text_4

Text_5

I want to get a result similar to:

['Raw name 1', Text_1, Text_2, Text_3, Text_4, Text_5]
...
['Raw name 5', Text_1, Text_2, Text_3, Text_4, Text_5]

I tried to do something on this example How to parse a HTML table with Nokogiri?, but nothing happened.

Is it possible to obtain information that I want from such HTML?

Body:
I'd do something like:

require 'nokogiri'

doc = Nokogiri::HTML(<<EOT)
<body>
    <div class="open">
        <div style='style'>Raw name 1</div>
        <p>Text_1</p>
        <p>Text_2</p>
        <div style='style'>Raw name 5</div>
        <p>Text_1</p>
        <p>Text_2</p>
    </div>
</body>
EOT

doc.at('.open').elements.slice_before { |e| e.name == 'div' }.map { |ary|
  ary.map(&:text)
}
# => [["Raw name 1", "Text_1", "Text_2"], ["Raw name 5", "Text_1", "Text_2"]]

Breaking it down a bit:

doc.at('.open').elements.map(&:name) # => ["div", "p", "p", "div", "p", "p"]
doc.at('.open').elements.slice_before { |e| e.name == 'div' }.map { |a| a.map(&:name) } # => [["div", "p", "p"], ["div", "p", "p"]]

elements and slice_before are the magic here.


问:
Selecting different columns with VBA
I have a worksheet with 22 columns of data and I need to copy and paste the first column and individual columns starting at column 3 to new worksheets in the same workbook.  For example, I would select column A and column C and copy those two columns to a new worksheet.  Then, I would go back to the initial worksheet and select column A and column D and copy just those two columns to a new worksheet, etc.

The code below iterates over all of the columns but it always selects a continuous range instead of just column A and the next column in the series.  My initial code is below:

```<code>Sub CashFlowColumnTabSplit()

ActiveSheet.Name = "Main"

For i = 3 To 22
    Range(Columns(1), Columns(i)).Select
    Selection.Copy
    Sheets.Add After:=ActiveSheet
    Range("A1").Select
    ActiveSheet.Paste
    Sheets("Main").Select
Next i

End Sub
</code>```

答:
The code below did the trick:</p>

```<code>Sub CashFlowColumnTabSplit2()

ActiveSheet.Name = "Main"

For i = 3 To 22
    Application.Union(Columns(1), Columns(i)).Copy
    Sheets.Add After:=ActiveSheet
    Range("A1").Select
    ActiveSheet.Paste
    Sheets("Main").Select
Next i

End Sub
</code>```

Title: Selecting different columns with VBA

Body:
I have a worksheet with 22 columns of data and I need to copy and paste the first column and individual columns starting at column 3 to new worksheets in the same workbook.  For example, I would select column A and column C and copy those two columns to a new worksheet.  Then, I would go back to the initial worksheet and select column A and column D and copy just those two columns to a new worksheet, etc.

The code below iterates over all of the columns but it always selects a continuous range instead of just column A and the next column in the series.  My initial code is below:

Sub CashFlowColumnTabSplit()

ActiveSheet.Name = "Main"

For i = 3 To 22
    Range(Columns(1), Columns(i)).Select
    Selection.Copy
    Sheets.Add After:=ActiveSheet
    Range("A1").Select
    ActiveSheet.Paste
    Sheets("Main").Select
Next i

End Sub

Body:
The code below did the trick:

Sub CashFlowColumnTabSplit2()

ActiveSheet.Name = "Main"

For i = 3 To 22
    Application.Union(Columns(1), Columns(i)).Copy
    Sheets.Add After:=ActiveSheet
    Range("A1").Select
    ActiveSheet.Paste
    Sheets("Main").Select
Next i

End Sub


答:
Your main method is wrong. You are not loading application context but directly creating your DAO. Maybe you need to change to this:</p>

```<code>ApplicationContext context =
      new ClassPathXmlApplicationContext("Spring-Review.xml");
JdbcReviewDAO reviewDAO = context.getBean("reviewDAO");
</code>```

Title: JDBC Template in Spring giving exception

Body:
Your main method is wrong. You are not loading application context but directly creating your DAO. Maybe you need to change to this:

ApplicationContext context =
      new ClassPathXmlApplicationContext("Spring-Review.xml");
JdbcReviewDAO reviewDAO = context.getBean("reviewDAO");


问:
Using purrr::map and forcats::fct_reorder to reorder factor levels by each subgroup
I'm trying to reorder the factor levels of a variable within each subgroup of that variable based on a third variable but I'm getting an error.

I recognize this is a little difficult to understand without context, so I'm using the gapminder dataset to illustrate. Here, I want to re-order the factor levels of the country variable within each category of the continent variable based on the size of the pop variable:

```<code>library(gapminder)
library(tidyverse)
library(forcats)

gapminder %>%
    filter(year == 2007) %>%
    group_by(continent) %>%
    nest() %>%
    mutate(newdata = map(data, fct_reorder, country, pop)) %>%
    unnest(newdata)
</code>```

```<code>Error in mutate_impl(.data, dots) :
`f` must be a factor (or character vector).
</code>```

What am I doing wrong?

Body:
I'm trying to reorder the factor levels of a variable within each subgroup of that variable based on a third variable but I'm getting an error.

I recognize this is a little difficult to understand without context, so I'm using the gapminder dataset to illustrate. Here, I want to re-order the factor levels of the country variable within each category of the continent variable based on the size of the pop variable:

library(gapminder)
library(tidyverse)
library(forcats)

gapminder %>%
    filter(year == 2007) %>%
    group_by(continent) %>%
    nest() %>%
    mutate(newdata = map(data, fct_reorder, country, pop)) %>%
    unnest(newdata)

Error in mutate_impl(.data, dots) :
`f` must be a factor (or character vector).

What am I doing wrong?

Body:
I don't really now forcats and its fct_* functions, I poked around and didn't find a way to accomplish what you want. However we can obtain it with:

library(gapminder)
library(tidyverse)

gapminder %>%
  filter(year == 2007) %>%
  group_by(continent) %>%
  nest() %>%
  mutate(newdata = map(data, ~{
    .x$country <- reorder(.x$country, order(.x$pop, decreasing = TRUE))
    .x
    })
  ) -> res
res
#> # A tibble: 5 × 3
#>   continent              data           newdata
#>      <fctr>            <list>            <list>
#> 1      Asia <tibble [33 × 5]> <tibble [33 × 5]>
#> 2    Europe <tibble [30 × 5]> <tibble [30 × 5]>
#> 3    Africa <tibble [52 × 5]> <tibble [52 × 5]>
#> 4  Americas <tibble [25 × 5]> <tibble [25 × 5]>
#> 5   Oceania  <tibble [2 × 5]>  <tibble [2 × 5]>

We can verify that the factor levels really changed:

lapply(res$newdata, function(x) as.numeric(x$country))
#> [[1]]
#>  [1]  5  7  8 23  3 12 24 31  9 30 15 20  1 21 25 10 18 14 29 33 27 28  4
#> [24]  6 11 13 26 32 17 22 19 16  2
#>
#> [[2]]
#>  [1] 11 29 10 30 16 26 20 22 18 12 21  3  7 23 13 27  2 28  5  8 24  9 19
#> [24]  4  6 15  1 25 17 14
#>
#> [[3]]
#>  [1] 37 15 18 11 44 45 47 24 33  1 50 21 34 28 13  7  5 29 36  2 52 41 30
#> [24] 51 49  9 22 43 39  6  3 42 27 48 17  8 12 31 26 35 25 20  4 23 19 32
#> [47] 46 38 10 16 14 40
#>
#> [[4]]
#>  [1] 23  3 16  6  1  4 20 25  5 10 12  8  9  2 13 14 11 19 17  7 21 24 18
#> [24] 15 22
#>
#> [[5]]
#> [1] 1 2

After this you can't really unnest it, as the country factor 'list' for each continent would conflict with the others:

res %>%
  select(-data) %>%
  unnest() -> res2
sapply(res2$country, as.numeric)
#>   [1]   5   7   8  23   3  12  24  31   9  30  15  20   1  21  25  10  18
#>  [18]  14  29  33  27  28   4   6  11  13  26  32  17  22  19  16   2  34
#>  [35]  39  40  43  46  60  62  63  72  73  76  78  84  85  86  87  99 103
#>  [52] 108 112 113 116 120 122 123 126 129 130 135 137  35  36  41  44  47
#>  [69]  48  49  51  52  55  56  57  59  64  67  69  70  71  74  75  77  80
#>  [86]  81  89  90  91  92  93  94  95  96  97 100 101 102 106 107 115 117
#> [103] 118 119 121 124 125 127 128 131 132 134 136 141 142  37  42  45  50
#> [120]  53  54  58  61  65  66  68  79  82  83  88  98 105 109 110 111 114
#> [137] 133 138 139 140  38 104

I think they are reordered again sequentially.


问:
Changing Android Project SDK level
I started writing my first Android app, and chose SDK 2.0.1, before I had an android phone.
I wantto test the app on a phone that is Android 1.6. The app itself uses pretty simple stuff, so I'm sure its 1.6 compatible, but I want to change the SDK level from Eclipse.

The "default.properties" file in my project tree and naively tried to change from Android 6, but it isn't changeable, but if I try to change it it tells me to change the build.properties of the project. I don't know what that means. I'm not used to eclipse and am still fumbling around it.

I went to the project properties and clicked on "Java Build Path", but from there I don't know how to add,remove or edit the libraries.

Basically, I'm asking how to downgrade my project from inside eclipse, so I can export it to a compatible phone.

答:
You can change your the Build Target for your project at any time: Right-click the project in the Package Explorer, select Properties, select Android and then check the desired Project Target.

PS : I'm on Eclipse Helios

http://developer.android.com/guide/developing/eclipse-adt.html

Title: Changing Android Project SDK level


问:
Multi line regex expression
I have the following file, and I'm trying to use /\|\".*\"\|/gm match multi line..end here, but the regex finds nothing using sed -e ':a;N;$!ba;s/\|\".*\"\|/abcxyz/gm' t >  t.2, I can't find out what's wrong with it.

```<code>    |2012-10-12 13:41:08.067|2012-10-12 13:45:03.282|f||"multi line star t herer erj
jdkajdkfj
   end here"|2017
</code>```

答:
sed is for simple subsitutions on individual lines, that is all. If you are using sed constructs other than s, g, and p (with -n) then you are using functionality that became obsolete in the mid-1970s when awk was invented.

With GNU awk for multi-char RS:

```<code>$ awk -v RS='multi line.*end here' 'RT{print RT}' file
multi line star t herer erj
jdkajdkfj
end here
</code>```

If that's not what you're looking for then edit your question to clarify the expected output and your requirements for matching it (string vs regexp, case sensitive vs insensitive, partial vs full, etc.)

Title: Multi line regex expression

Body:
I have the following file, and I'm trying to use /\|\".*\"\|/gm match multi line..end here, but the regex finds nothing using sed -e ':a;N;$!ba;s/\|\".*\"\|/abcxyz/gm' t >  t.2, I can't find out what's wrong with it.

    |2012-10-12 13:41:08.067|2012-10-12 13:45:03.282|f||"multi line star t herer erj
jdkajdkfj
   end here"|2017

Body:
sed is for simple subsitutions on individual lines, that is all. If you are using sed constructs other than s, g, and p (with -n) then you are using functionality that became obsolete in the mid-1970s when awk was invented.

With GNU awk for multi-char RS:

$ awk -v RS='multi line.*end here' 'RT{print RT}' file
multi line star t herer erj
jdkajdkfj
end here

If that's not what you're looking for then edit your question to clarify the expected output and your requirements for matching it (string vs regexp, case sensitive vs insensitive, partial vs full, etc.)


问:
How to change default JSDoc Text Color?
I am using JSDoc to generate Documentation for my JS library. The default HTML content generated from JSDoc has gray color text and very hard to read. Now, I would like to change text color to black/blue. is there any way to change text color or background color?

答:
Yes, there is a way to change the default template/styles of JSDoc, and you can achieve that as described here:

Overriding the default template's layout file

The default template uses a file named layout.tmpl to specify the
  header and footer for each page in the generated documentation. In
  particular, this file defines which CSS and JavaScript files are
  loaded for each page. In JSDoc 3.3.0 and later, you can specify your
  own layout.tmpl file to use, which allows you to load your own custom
  CSS and JavaScript files in addition to, or instead of, the standard
  files.

To use this feature, set the option templates.default.layoutFile to
  the path to your customized layout file. Relative paths are resolved
  against the path to the config.json file; the current working
  directory; and the JSDoc directory, in that order.

Title: How to change default JSDoc Text Color?


问:
mysql count the number of matches based on a column
This is my example dataset I have groups with students assigned to them as shown below

```
uid | groupid         | studentid
49  | PZV7cUZCnLwNkSS | wTsBSkkg4Weo8R3
50  | PZV7cUZCnLwNkSS | aIuDhxfChg3enCf
97  | CwvkffFcBCRbzdw | hEwLxJmnJmZFAic
99  | CwvkffFcBCRbzdw | OKFfl58XVQMrAyC
126 | CwvkffFcBCRbzdw | dlH8udyTjNV3nXM
142 | 2vu1eqTCWVjgE58 | Q01Iz3lC2uUMBSB
143 | 2vu1eqTCWVjgE58 | vB5s8hfTaVtx3wO
144 | 2vu1eqTCWVjgE58 | 5O9HA5Z7wVhgi6l
145 | 2vu1eqTCWVjgE58 | OiEUOXNjK2D2s8F```

I am trying to output with the following information.
The problem I am having is the Group Size column getting it to output a count.

```
Studentid       | Groupid         | Group Size
wTsBSkkg4Weo8R3 | PZV7cUZCnLwNkSS | 2
aIuDhxfChg3enCf | PZV7cUZCnLwNkSS | 2
hEwLxJmnJmZFAic | CwvkffFcBCRbzdw | 3
OKFfl58XVQMrAyC | CwvkffFcBCRbzdw | 3
dlH8udyTjNV3nXM | CwvkffFcBCRbzdw | 3```

I have researched if I can you can use a where clause in the count, and does not seem like it will let me do that.  I thought about doing a sum but couldn't make that happen either.  I feel like I am missing something simple.

答:
An easy way to solve this, is using a JOIN statement:

```<code>SELECT a.studentid AS Studentid, a.groupid AS Groupid, <b>COUNT(*)</b>
FROM table AS a
     <b>JOIN table AS b ON a.groupid = b.groupid
GROUP BY a.studentid, a.groupid</b></code>```

So here we join the table with itself and use a GROUP BY to group on the studentid and groupid and then use COUNT(*) to count the number of rows in b that have the same groupid.

Body:
This is my example dataset I have groups with students assigned to them as shown below

uid | groupid         | studentid
49  | PZV7cUZCnLwNkSS | wTsBSkkg4Weo8R3
50  | PZV7cUZCnLwNkSS | aIuDhxfChg3enCf
97  | CwvkffFcBCRbzdw | hEwLxJmnJmZFAic
99  | CwvkffFcBCRbzdw | OKFfl58XVQMrAyC
126 | CwvkffFcBCRbzdw | dlH8udyTjNV3nXM
142 | 2vu1eqTCWVjgE58 | Q01Iz3lC2uUMBSB
143 | 2vu1eqTCWVjgE58 | vB5s8hfTaVtx3wO
144 | 2vu1eqTCWVjgE58 | 5O9HA5Z7wVhgi6l
145 | 2vu1eqTCWVjgE58 | OiEUOXNjK2D2s8F

I am trying to output with the following information.
The problem I am having is the Group Size column getting it to output a count.

Studentid       | Groupid         | Group Size
wTsBSkkg4Weo8R3 | PZV7cUZCnLwNkSS | 2
aIuDhxfChg3enCf | PZV7cUZCnLwNkSS | 2
hEwLxJmnJmZFAic | CwvkffFcBCRbzdw | 3
OKFfl58XVQMrAyC | CwvkffFcBCRbzdw | 3
dlH8udyTjNV3nXM | CwvkffFcBCRbzdw | 3

I have researched if I can you can use a where clause in the count, and does not seem like it will let me do that.  I thought about doing a sum but couldn't make that happen either.  I feel like I am missing something simple.

Body:
An easy way to solve this, is using a JOIN statement:

SELECT a.studentid AS Studentid, a.groupid AS Groupid, COUNT(*)
FROM table AS a
     JOIN table AS b ON a.groupid = b.groupid
GROUP BY a.studentid, a.groupid

So here we join the table with itself and use a GROUP BY to group on the studentid and groupid and then use COUNT(*) to count the number of rows in b that have the same groupid.


答:
You should try:

SELECT COUNT(Groupid) AS Groupsize FROM table;

It seems that what you're trying to do is simple. If I understand correctly, a simple SELECT COUNT statement. To exclude multiple returns of the same value, use SELECT DISTINCT COUNT()

Title: mysql count the number of matches based on a column


问:
Weblogic wlserver memory setting?
When we start up Weblogic (8.1) from the command line, we’re passing it memory usage arguments of the form “-Xms256m -Xmx1024m” which gives it a GB to play with.

When we’re starting it up from ANT, we’re using a “wlserver” task instead which, I’m guessing, does a live launch of it. What memory parameters is it using then? How I would I tell it to use the 1GB option instead?

Thanks.

答: Class weblogic.ant.taskdefs.management.WLServer extends org.apache.tools.ant.taskdefs.Java so it should be possible to give it the same parameters as to java ant task (see http://ant.apache.org/manual/Tasks/java.html).

OwnerDisplayName: Marcus Leon

Title: Weblogic wlserver memory setting?

LastEditorDisplayName: Marcus Leon

OwnerDisplayName: martsraits


问:
Jolt - change format of elasticsearch response
This should be a no brainer as Jolt was built mainly to transform ES ,mongodb responses.But I am unable to figure it out

I want to parse ES response and print only selected fields. For instance I want to transform the response to

```<code>{
"time" : 63,
"totalhits":100,
"0";{ response1.field1,response1.field2},
"1";{ response2.field1,response2.field2},
"2";{ response3.field1,response3.field2},
}

  {
  "took" : 63,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "failed" : 0
  },
  "hits" : {
    "total" : 1000,
    "max_score" : null,
    "hits" : [ {
      "_index" : "bank",
      "_type" : "account",
      "_id" : "0",
      "sort": [0],
      "_score" : null,
      "_source" : {"account_number":0,"balance":16623,"firstname":"Bradshaw","lastname":"Mckenzie","age":29,"gender":"F","address":"244 Columbus Place","employer":"Euron","email":"bradshawmckenzie@euron.com","city":"Hobucken","state":"CO"}
    }, {
      "_index" : "bank",
      "_type" : "account",
      "_id" : "1",
      "sort": [1],
      "_score" : null,
      "_source" : {"account_number":1,"balance":39225,"firstname":"Amber","lastname":"Duke","age":32,"gender":"M","address":"880 Holmes Lane","employer":"Pyrami","email":"amberduke@pyrami.com","city":"Brogan","state":"IL"}
    }, ...
    ]
  }
    }
</code>```

The spec file I got so far is

```<code>[
  {
    "operation": "shift",
    "spec": {
      "hits": {
        "*": {
          "*": "&"
        }
      }
    }
}
]
</code>```

答:
figured it out.</p>

```<code>[
  {
    "operation": "shift",
    "spec": {
      "took": "took",
      "hits": {
        "total": "total_hits",
        "hits": {
          "*": {
            "_source": {
              "country": "Response[&2].country",
              "city": "Response[&2].city",
              "year": "Response[&2].year"
            }
          }
        }
      }
    }
  }
]
</code>```

Body:
This should be a no brainer as Jolt was built mainly to transform ES ,mongodb responses.But I am unable to figure it out

I want to parse ES response and print only selected fields. For instance I want to transform the response to

{
"time" : 63,
"totalhits":100,
"0";{ response1.field1,response1.field2},
"1";{ response2.field1,response2.field2},
"2";{ response3.field1,response3.field2},
}

  {
  "took" : 63,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "failed" : 0
  },
  "hits" : {
    "total" : 1000,
    "max_score" : null,
    "hits" : [ {
      "_index" : "bank",
      "_type" : "account",
      "_id" : "0",
      "sort": [0],
      "_score" : null,
      "_source" : {"account_number":0,"balance":16623,"firstname":"Bradshaw","lastname":"Mckenzie","age":29,"gender":"F","address":"244 Columbus Place","employer":"Euron","email":"bradshawmckenzie@euron.com","city":"Hobucken","state":"CO"}
    }, {
      "_index" : "bank",
      "_type" : "account",
      "_id" : "1",
      "sort": [1],
      "_score" : null,
      "_source" : {"account_number":1,"balance":39225,"firstname":"Amber","lastname":"Duke","age":32,"gender":"M","address":"880 Holmes Lane","employer":"Pyrami","email":"amberduke@pyrami.com","city":"Brogan","state":"IL"}
    }, ...
    ]
  }
    }

The spec file I got so far is

[
  {
    "operation": "shift",
    "spec": {
      "hits": {
        "*": {
          "*": "&"
        }
      }
    }
}
]

Body:
figured it out.

[
  {
    "operation": "shift",
    "spec": {
      "took": "took",
      "hits": {
        "total": "total_hits",
        "hits": {
          "*": {
            "_source": {
              "country": "Response[&2].country",
              "city": "Response[&2].city",
              "year": "Response[&2].year"
            }
          }
        }
      }
    }
  }
]


问:
Display image from json data in html?
I'm trying to display an image from my JSON data in HTML, but I'm not having any success.

I have a marker which displays some content  when an onclick event occurs.

For this purpose, I am using the following JSON code:

```<code>var json = {
"Hatch": [
    {
        "image": "img/myimage.jpg",
        "description": "test goes here"
    }
]
}

 $(document).ready(function(){
for( index in json.Hatch )

$('.marker.one').on('click', function(){
$('#show').html(   'Image : ' +json.Hatch[index].image + '| Description : ' + json.Hatch[index].description  );

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

My trigger on click from my html is the following:

```<code><section class="info">

    <div class="container-fluid">
      <div class="row">

      <div class="marker one">

         <img  class="trigger" src="img/marker.png">

      </div>

      <div class="marker two">
         <img  class="trigger" src="img/tooltip.png">

      </div>

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

which display here:

```<code><div id="show"></div>
</code>```

Any help you may offer would be awesome! I'm starting to use JSON only.

Thanks for your time!

答:
for..in loop is not necessary.  If you are expecting an  element to be rendered, include  with src set to json.Hatch[0].image within string passed to .html()

```<code>$(".marker.one").on("click", function() {
  if (!$("#show img").is("*"))
    $("#show").html(
      "Image : <img src=" + json.Hatch[0].image + ">"
    + "| Description : " + json.Hatch[0].description
    );
});
</code>```

Title: Display image from json data in html?

Body:
I'm trying to display an image from my JSON data in HTML, but I'm not having any success.

I have a marker which displays some content  when an onclick event occurs.

For this purpose, I am using the following JSON code:

var json = {
"Hatch": [
    {
        "image": "img/myimage.jpg",
        "description": "test goes here"
    }
]
}

 $(document).ready(function(){
for( index in json.Hatch )

$('.marker.one').on('click', function(){
$('#show').html(   'Image : ' +json.Hatch[index].image + '| Description : ' + json.Hatch[index].description  );

});
});

My trigger on click from my html is the following:

which display here:

Any help you may offer would be awesome! I'm starting to use JSON only.

Thanks for your time!

Body:
for..in loop is not necessary.  If you are expecting an <img> element to be rendered, include <img> with src set to json.Hatch[0].image within string passed to .html()

$(".marker.one").on("click", function() {
  if (!$("#show img").is("*"))
    $("#show").html(
      "Image : <img src=" + json.Hatch[0].image + ">"
    + "| Description : " + json.Hatch[0].description
    );
});


问:
SimpleXML changing file encoding
I am trying to write a function which could read an existing XML file and create a new one with all the data from the first one, but in a different encoding. As far I understand it, SimpleXML saves the file in UTF-8 encoding. My original XML file is Windows-1257.

Code:

```<code>public static function toUTF8()
{
    $remote_file = "data/test/import/test.xml";
    $xml = simplexml_load_file($remote_file);
    $xml->asXml('data/test/import/utf8/test.xml');

    echo var_dump('done');
    exit;
}
</code>```

This way the encoding of file is still not good. I wanted to try this:

```<code>$newXML = new SimpleXMLElement($xml);
</code>```

But this takes only plain XML code as a parameter. How could I get the whole XML code from the object? Or how else could I create a new UTF-8 XML object and insert all the data from the old file?

答:
I tried this out and saw problems importing the XML directly with SimpleXML. Despite the correct encoding declaration in the XML, it would output the wrong characters. So the alternative is to use a function like iconv which can do the conversion for you.

If you don't need to parse the XML, you can just do this directly:

```<code><?php
$remote_file = "data/test/import/test.xml";
$new_file    = "data/test/import/utf8/test.xml";

$baltic_xml  = file_get_contents($remote_file);
$unicode_xml = iconv("CP1257", "UTF-8", $baltic_xml);

file_put_contents($new_file, $unicode_xml);
</code>```

If you need to do stuff with the XML, it gets a little more complicated because you have to update the character set in the XML declaration.

```<code><?php
$remote_file = "data/test/import/test.xml";
$new_file    = "data/test/import/utf8/test.xml";

$baltic_xml  = file_get_contents($remote_file);
$unicode_xml = iconv("CP1257", "UTF-8", $baltic_xml);
$unicode_xml = str_replace('encoding="CP1257"', 'encoding="UTF-8"', $unicode_xml);

$xml         = new SimpleXMLElement($unicode_xml);
// do stuff with $xml
$xml->asXml($new_file);
</code>```

I tested this out with the following file (saved as CP1257) and it worked fine:

```<code><?xml version="1.0" encoding="CP1257"?>
<Root-Element>
    <Test>ŁųßŻĒČ</Test>
</Root-Element>
</code>```

Title: SimpleXML changing file encoding

Body:
I am trying to write a function which could read an existing XML file and create a new one with all the data from the first one, but in a different encoding. As far I understand it, SimpleXML saves the file in UTF-8 encoding. My original XML file is Windows-1257.

Code:

public static function toUTF8()
{
    $remote_file = "data/test/import/test.xml";
    $xml = simplexml_load_file($remote_file);
    $xml->asXml('data/test/import/utf8/test.xml');

    echo var_dump('done');
    exit;
}

This way the encoding of file is still not good. I wanted to try this:

$newXML = new SimpleXMLElement($xml);

But this takes only plain XML code as a parameter. How could I get the whole XML code from the object? Or how else could I create a new UTF-8 XML object and insert all the data from the old file?

Body:
I tried this out and saw problems importing the XML directly with SimpleXML. Despite the correct encoding declaration in the XML, it would output the wrong characters. So the alternative is to use a function like iconv which can do the conversion for you.

If you don't need to parse the XML, you can just do this directly:

<?php
$remote_file = "data/test/import/test.xml";
$new_file    = "data/test/import/utf8/test.xml";

$baltic_xml  = file_get_contents($remote_file);
$unicode_xml = iconv("CP1257", "UTF-8", $baltic_xml);

file_put_contents($new_file, $unicode_xml);

If you need to do stuff with the XML, it gets a little more complicated because you have to update the character set in the XML declaration.

<?php
$remote_file = "data/test/import/test.xml";
$new_file    = "data/test/import/utf8/test.xml";

$baltic_xml  = file_get_contents($remote_file);
$unicode_xml = iconv("CP1257", "UTF-8", $baltic_xml);
$unicode_xml = str_replace('encoding="CP1257"', 'encoding="UTF-8"', $unicode_xml);

$xml         = new SimpleXMLElement($unicode_xml);
// do stuff with $xml
$xml->asXml($new_file);

I tested this out with the following file (saved as CP1257) and it worked fine:

<?xml version="1.0" encoding="CP1257"?>
<Root-Element>
    <Test>ŁųßŻĒČ</Test>
</Root-Element>