问:
Python: How can I merge these 2 overloaded constructors into 1 constructor
I have a class called Portfolio & right now I have 2 constructors (although as I just discovered u cant overload functions in python) so I have to merge these 2 constructors.

I am an experienced python programmer but this merging 2 constructors that are pretty contradictory is really doing my head in! :P

The first constructor:

+ Purpose is to create a .db file & initialise class variables

- Initialises class member variables

- Checks whether a file with the path&name db_path exists: if it does we exit coz we dont want to overwrite an existing database so we return None

- We create the database (sql database) & set up the necessary tables

- import portfolio data (date created, etc)

The 2nd constructor:

+ Purpose is to import all stock data from an existing sql database file & initialise variables

- Initialises class member variables

- Checks whether a file with the path&name db_path exists: if it does NOT we exit coz we dont want to overwrite an existing database so we return None

- We call the function to import all stocks from the database

- import portfolio data (date created, etc)

How can I merge these two constructors, ugh, why doesn't python allow overloading

```<code>class Portfolio:
""" Portfolio class implementation """

# Class Variables:

# self.db_path
# self.app_parent
# self.tracking_stocks
# self.registered_stocks
# self.total_purchase_exp
# self.ytd_roi
# self.cash_reserve

# Class Functions:

def __init__( self, _app_parent, _db_path, stock_list ):
    """ Constructor: """

    self.db_path            = _db_path
    self.app_parent         = _app_parent
    self.tracking_stocks    = []
    self.registered_stocks  = []
    self.total_purchase_exp = 0
    self.ytd_roi            = 0
    self.cash_reserve       = 500

    if database_exists( self.db_path ):
        return None

    self.create_database()
    self.import_portfolio_data()

    for stock_data in stock_list:

        self.add_stock( stock_data )

def __init__( self, _app_parent, _db_path ):
    """ Constructor: """

    self.db_path            = _db_path
    self.app_parent         = _app_parent
    self.tracking_stocks    = []
    self.registered_stocks  = []
    self.total_purchase_exp = 0
    self.ytd_roi            = 0
    self.cash_reserve       = 500

    if not self.database_exists( self.db_path ):
        return None

    self.import_portfolio_data()
    self.import_stocks()
</code>```

答:
Why does this all have to happen in constructors?

You could construct your object, then call separate methods on it for for importing the stock lists, or creating the database.

Wrapping that up in the Builder pattern may suit your existing design.

Body:
I have a class called Portfolio & right now I have 2 constructors (although as I just discovered u cant overload functions in python) so I have to merge these 2 constructors.

I am an experienced python programmer but this merging 2 constructors that are pretty contradictory is really doing my head in! :P

The first constructor:

+ Purpose is to create a .db file & initialise class variables

- Initialises class member variables

- Checks whether a file with the path&name db_path exists: if it does we exit coz we dont want to overwrite an existing database so we return None

- We create the database (sql database) & set up the necessary tables

- import portfolio data (date created, etc)

The 2nd constructor:

+ Purpose is to import all stock data from an existing sql database file & initialise variables

- Initialises class member variables

- Checks whether a file with the path&name db_path exists: if it does NOT we exit coz we dont want to overwrite an existing database so we return None

- We call the function to import all stocks from the database

- import portfolio data (date created, etc)

How can I merge these two constructors, ugh, why doesn't python allow overloading

class Portfolio:
""" Portfolio class implementation """

# Class Variables:

# self.db_path
# self.app_parent
# self.tracking_stocks
# self.registered_stocks
# self.total_purchase_exp
# self.ytd_roi
# self.cash_reserve

# Class Functions:

def __init__( self, _app_parent, _db_path, stock_list ):
    """ Constructor: """

    self.db_path            = _db_path
    self.app_parent         = _app_parent
    self.tracking_stocks    = []
    self.registered_stocks  = []
    self.total_purchase_exp = 0
    self.ytd_roi            = 0
    self.cash_reserve       = 500

    if database_exists( self.db_path ):
        return None

    self.create_database()
    self.import_portfolio_data()

    for stock_data in stock_list:

        self.add_stock( stock_data )

def __init__( self, _app_parent, _db_path ):
    """ Constructor: """

    self.db_path            = _db_path
    self.app_parent         = _app_parent
    self.tracking_stocks    = []
    self.registered_stocks  = []
    self.total_purchase_exp = 0
    self.ytd_roi            = 0
    self.cash_reserve       = 500

    if not self.database_exists( self.db_path ):
        return None

    self.import_portfolio_data()
    self.import_stocks()


来源: stackexchange

问:
I want to load ajax response data into dropdown
I want to load ajax resonse data into dropdown list. I have one dropdown list on my page. I just want to load ajax response data which will contain list of options into dropdown list.

This is my dropdown.

```<code><select title="Basic example" id="muliSelect6" class="multipleCheckbox" multiple="multiple" name="example-basic6[]" size="5">

</select>
</code>```

I am using the following ajax script :

```<code>         $.ajax({
                url: "GetPerPersonData.php",
                type: "POST",
                data:           {
             building: $('#muliSelect1').val(),wing:$('#muliSelect3').val()

            },
                success: function(data)
                    {
               $("#muliSelect6").html('');
                       $("#muliSelect6").html(data);
                    }

            });
</code>```

I am getting the response as a list of options as following

```<code><option value="yogesh">Yogesh kale</option>
</code>```

But it does not get loaded in dropdown list. So please help me in getting the output correctly.

答:
Here is the My code,it worked fine.

List item

Jsp AJAX:

function changeVal(){

```<code>    var name = $('select#company').val();

    $.post('myActionForm.do?parameter=getMOLCodesList', {

        userName : name

    }, function(response) {

        var select = $('#molcode');

        select.find('option').remove();

        $.each(response, function(index,value) {

        $('<option>').val(value).text(value).appendTo(select);

     });

    }); }
</code>```

My Java class code:

In java am getting the MOL Codes from DB and i am assigning to DROP Down.
please make a note on it..its struts class(DispatchAction).

public ActionForward getMOLCodesList(ActionMapping mapping,ActionForm fm,
            HttpServletRequest request,HttpServletResponse response)throws Exception {
        ArrayList molList = new ArrayList();

```<code>    String companyname = request.getParameter("userName");

    String json = null;
    System.out.println("company name is"+companyname);

    connection = (SybConnection)getXchgConnect();

    if(companyname!=null && !(companyname.equalsIgnoreCase(""))) {

        System.out.println("Hello,i am from MOL codes");

        cstmt1 = connection
                .prepareCall("{call allied.dbo.p_getMOLcodes(?)}");

        cstmt1.setString(1, companyname);
        molCodes = cstmt1.executeQuery();

        while (molCodes.next()) {

            molList.add(molCodes.getString("MOLCode").trim());

        }
        System.out.println("Mol lIst size is-->"+molList.size());

        response.setContentType("text/plain");

        json = new Gson().toJson(molList);
        response.setContentType("application/json");

        response.getWriter().write(json);

        if(connection!=null && molCodes!=null) {
            connection.close();
            molCodes.close();
        }
    }

    //return mapping.findForward("welcome1");
    return null;
}
</code>```

Jsp Page:

```<code>        <div align="center"
            style="border: 2px solid LightGreen; padding: 12px; font-size: 12px; width: 1050px">

            Company Name <select id="company" name="companyList"
                style="border: 2px solid LightGreen; font-size: 12px; width: 138px;"
                onchange="changeVal(this.value)">
                <option selected value="default">--Select Company Name--</option>

                <c:forEach var="item" items="${companiesList}">
                    <option value="${item}">${item}</option>
                </c:forEach>

            </select>   MOLCode<select id="molcode" name="mol"
                style="border: 2px solid LightGreen; font-size: 12px; width: 138px;">

                <!--        <option selected value="default">--Select--</option>

                <option value="835725">835725</option>
                <option value="54322">54322</option> -->
                <option selected value="default">Select MOLCode</option>
            </select>    Month<select id='gMonth1' name="month">
                <option selected value="12">--Select Month--</option>
                <option value='0'>Janaury</option>
                <option value='1'>February</option>
                <option value='2'>March</option>
                <option value='3'>April</option>
                <option value='4'>May</option>
                <option value='5'>June</option>
                <option value='6'>July</option>
                <option value='7'>August</option>
                <option value='8'>September</option>
                <option value='9'>October</option>
                <option value='10'>November</option>
                <option value='11'>December</option>
            </select>    Year<input type="text" name="year" id="year" style="font-size: 10px" maxlength="4"
                placeholder="Enter a valid Year"
                onkeypress="return isNumber(event)"
                onblur="return checkyear(this.value)">
                <input type="submit" value="submit"
                style="font-size: 7pt; color: white; background-color: green; border: 2px solid #336600; padding: 3px"/>
            <!-- <input type="button" value="submit"
                style="font-size: 7pt; color: white; background-color: green; border: 2px solid #336600; padding: 3px"
                onclick="return checkyear(this.value),getCustomers()"/> -->
                <input type="RESET" value="Reset" style="font-size: 7pt; color: white; background-color: green;
</code>```

border: 2px solid #336600; padding: 3px" />

Hope This will be helpfull to someone.

List item

ContentLicense: CC BY-SA 3.0

Body:
I want to load ajax resonse data into dropdown list. I have one dropdown list on my page. I just want to load ajax response data which will contain list of options into dropdown list.

This is my dropdown.

<select title="Basic example" id="muliSelect6" class="multipleCheckbox" multiple="multiple" name="example-basic6[]" size="5">

</select>

I am using the following ajax script :

         $.ajax({
                url: "GetPerPersonData.php",
                type: "POST",
                data:           {
             building: $('#muliSelect1').val(),wing:$('#muliSelect3').val()

            },
                success: function(data)
                    {
               $("#muliSelect6").html('');
                       $("#muliSelect6").html(data);
                    }

            });

I am getting the response as a list of options as following

<option value="yogesh">Yogesh kale</option>

But it does not get loaded in dropdown list. So please help me in getting the output correctly.

Body:
Here is the My code,it worked fine.

List item

Jsp AJAX:

function changeVal(){

    var name = $('select#company').val();

    $.post('myActionForm.do?parameter=getMOLCodesList', {

        userName : name

    }, function(response) {

        var select = $('#molcode');

        select.find('option').remove();

        $.each(response, function(index,value) {

        $('<option>').val(value).text(value).appendTo(select);

     });

    }); }

My Java class code:

In java am getting the MOL Codes from DB and i am assigning to DROP Down.
please make a note on it..its struts class(DispatchAction).

public ActionForward getMOLCodesList(ActionMapping mapping,ActionForm fm,
            HttpServletRequest request,HttpServletResponse response)throws Exception {
        ArrayList molList = new ArrayList();

    String companyname = request.getParameter("userName");

    String json = null;
    System.out.println("company name is"+companyname);

    connection = (SybConnection)getXchgConnect();

    if(companyname!=null && !(companyname.equalsIgnoreCase(""))) {

        System.out.println("Hello,i am from MOL codes");

        cstmt1 = connection
                .prepareCall("{call allied.dbo.p_getMOLcodes(?)}");

        cstmt1.setString(1, companyname);
        molCodes = cstmt1.executeQuery();

        while (molCodes.next()) {

            molList.add(molCodes.getString("MOLCode").trim());

        }
        System.out.println("Mol lIst size is-->"+molList.size());

        response.setContentType("text/plain");

        json = new Gson().toJson(molList);
        response.setContentType("application/json");

        response.getWriter().write(json);

        if(connection!=null && molCodes!=null) {
            connection.close();
            molCodes.close();
        }
    }

    //return mapping.findForward("welcome1");
    return null;
}

Jsp Page:

        <div align="center"
            style="border: 2px solid LightGreen; padding: 12px; font-size: 12px; width: 1050px">

            Company Name <select id="company" name="companyList"
                style="border: 2px solid LightGreen; font-size: 12px; width: 138px;"
                onchange="changeVal(this.value)">
                <option selected value="default">--Select Company Name--</option>

                <c:forEach var="item" items="${companiesList}">
                    <option value="${item}">${item}</option>
                </c:forEach>

            </select>&nbsp;&nbsp; MOLCode<select id="molcode" name="mol"
                style="border: 2px solid LightGreen; font-size: 12px; width: 138px;">

                <!--        <option selected value="default">--Select--</option>

                <option value="835725">835725</option>
                <option value="54322">54322</option> -->
                <option selected value="default">Select MOLCode</option>
            </select> &nbsp;&nbsp; Month<select id='gMonth1' name="month">
                <option selected value="12">--Select Month--</option>
                <option value='0'>Janaury</option>
                <option value='1'>February</option>
                <option value='2'>March</option>
                <option value='3'>April</option>
                <option value='4'>May</option>
                <option value='5'>June</option>
                <option value='6'>July</option>
                <option value='7'>August</option>
                <option value='8'>September</option>
                <option value='9'>October</option>
                <option value='10'>November</option>
                <option value='11'>December</option>
            </select> &nbsp;&nbsp; Year<input type="text" name="year" id="year" style="font-size: 10px" maxlength="4"
                placeholder="Enter a valid Year"
                onkeypress="return isNumber(event)"
                onblur="return checkyear(this.value)"> &nbsp;&nbsp;
                <input type="submit" value="submit"
                style="font-size: 7pt; color: white; background-color: green; border: 2px solid #336600; padding: 3px"/>
            <!-- <input type="button" value="submit"
                style="font-size: 7pt; color: white; background-color: green; border: 2px solid #336600; padding: 3px"
                onclick="return checkyear(this.value),getCustomers()"/> -->
            &nbsp;&nbsp;  <input type="RESET" value="Reset" style="font-size: 7pt; color: white; background-color: green;

border: 2px solid #336600; padding: 3px" />

Hope This will be helpfull to someone.

List item


问:
QBWC: "Index Out Of Range" in do_authenticate()
I'm using QuickBooks WebConnector 2.2.0.71 and my WCF web service (on .NET 4.6.1). After pressing "Update selected" in WebConnector serverVersion and clientVersion requests successfully processed, but authenticate failed:

```<code>20170705.06:31:00 UTC   : QBWebConnector.SOAPWebService.do_authenticate() : *** Calling authenticate() with following parameters:<userName="username"><password=<MaskedForSecurity>
20170705.06:31:00 UTC   : QBWebConnector.SOAPWebService.do_authenticate() : QBWC1012: Authentication failed due to following error message.
Index Out Of Range.
More info:
StackTrace =    в QBWebConnector.WebService.do_authenticate(String& ticket, String& companyFileName)
Source = QBWebConnector
</code>```

Response of my WCF service (from WCF Test Client):

```<code><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Header />
  <s:Body>
    <authenticateResponse xmlns="http://developer.intuit.com/">
      <authenticateResult xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
        <a:string>a3f10876-e027-419d-8dd8-3752a852ddae</a:string>
        <a:string>nvu</a:string>
        <a:string>3</a:string>
        <a:string>60</a:string>
        <a:string>60</a:string>
      </authenticateResult>
    </authenticateResponse>
  </s:Body>
</s:Envelope>
</code>```

Docs says "Your callback must return A string array with 4 possible elements. The first element contains either NONE or NVU (invalid user) or BUSY., or empty
string, or a string that is the QB company file name." but in samples first element is guid token, so I send array of 5 elements.

Same error occured when I send not an array, but int value, so I guess - maybe something wrong with my xml?

答:
Page 21 of the QBWC Programmers Guide.

Your return to the authenticate call will be a string array with a maximum of four strings.

The first member of the array is a session token, which could be a GUID or anything else that you want to use to identify the session. This token will be returned by QBWC in subsequent callbacks in the session.

The second member of the string array can contain a variety of things.

a. If the username and password in the authenticate call is invalid, you would supply the value “nvu”.

b. If on the other hand the user data is valid but you have no work to do for that user, you would supply the value “none”.

c. If you do have work to do for the that user, you can supply the full pathname of the company to be used in the current update.

d. If you want to use whatever QuickBooks company is currently open at the client end, simply supply an empty string.

The optional third member of the string array contains the number of seconds to wait before the next update. You would use this to in effect tell that QBWC client not to bother you for a specified time.

The optional fourth member of the string array contains the number of seconds to be used as the MinimumRunEveryNSeconds time for your web service, which tells QBWC how frequently your web service needs to be contacted.

I am not sure why the Authenticate at the end of the doc is different than this.

Body:
I'm using QuickBooks WebConnector 2.2.0.71 and my WCF web service (on .NET 4.6.1). After pressing "Update selected" in WebConnector serverVersion and clientVersion requests successfully processed, but authenticate failed:

20170705.06:31:00 UTC   : QBWebConnector.SOAPWebService.do_authenticate() : *** Calling authenticate() with following parameters:<userName="username"><password=<MaskedForSecurity>
20170705.06:31:00 UTC   : QBWebConnector.SOAPWebService.do_authenticate() : QBWC1012: Authentication failed due to following error message.
Index Out Of Range.
More info:
StackTrace =    в QBWebConnector.WebService.do_authenticate(String& ticket, String& companyFileName)
Source = QBWebConnector

Response of my WCF service (from WCF Test Client):

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Header />
  <s:Body>
    <authenticateResponse xmlns="http://developer.intuit.com/">
      <authenticateResult xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
        a3f10876-e027-419d-8dd8-3752a852ddae
        nvu
        3
        60
        60
      </authenticateResult>
    </authenticateResponse>
  </s:Body>
</s:Envelope>

Docs says "Your callback must return A string array with 4 possible elements. The first element contains either NONE or NVU (invalid user) or BUSY., or empty
string, or a string that is the QB company file name." but in samples first element is guid token, so I send array of 5 elements.

Same error occured when I send not an array, but int value, so I guess - maybe something wrong with my xml?


问:
How to declare array value in Kotlin annotations?
I have some problem with creating my own annotations in Kotlin. I have to create some annotations and in some of them i need to declare values with array type.
In java we can do this:

```<code>public @interface JoinTable {
...
    JoinColumn[] inverseJoinColumns() default {};
...
}
</code>```

Where JoinColumn is also an annotation type.

I want to do something like that in Kotlin:

```<code>annotation class JoinTable(
    val name: String,
    val joinColumns: Array<JoinColumn>
)
</code>```

I also tried to do this:

```<code>annotation class JoinTable(
    val name: String,
    val joinColumns: List<JoinColumn>
)
</code>```

But my IDe says:

Invalid type of annotation member

What should i do?

Thank you!

答:
As in java, the values for annotations must be available at compile time.
That means that val joinColumns: List<JoinColumn> is not possible if the JoinColumn is a usual class or data-class.
If it's an enum class (enum class JoinColumn), than it's possible to use it.

See also the official kotlin documentation for allowed types https://kotlinlang.org/docs/reference/annotations.html

Allowed parameter types are:

types that correspond to Java primitive types (Int, Long etc.);

strings;

classes (Foo::class);

enums;

other annotations;

arrays of the types listed above.

Annotation parameters cannot have nullable types, because the JVM does
  not support storing null as a value of an annotation attribute.

Body:
I have some problem with creating my own annotations in Kotlin. I have to create some annotations and in some of them i need to declare values with array type.
In java we can do this:

public @interface JoinTable {
...
    JoinColumn[] inverseJoinColumns() default {};
...
}

Where JoinColumn is also an annotation type.

I want to do something like that in Kotlin:

annotation class JoinTable(
    val name: String,
    val joinColumns: Array<JoinColumn>
)

I also tried to do this:

annotation class JoinTable(
    val name: String,
    val joinColumns: List<JoinColumn>
)

But my IDe says:

Invalid type of annotation member

What should i do?

Thank you!


答:
```<code>def __init__(self, _app_parent, _db_path, stock_list=None):
    self.db_path            = _db_path
    self.app_parent         = _app_parent
    self.tracking_stocks    = []
    self.registered_stocks  = []
    self.total_purchase_exp = 0
    self.ytd_roi            = 0
    self.cash_reserve       = 500

    if stock_list:
        if database_exists( self.db_path ):
            return None
        self.create_database()
        self.import_portfolio_data()
        for stock_data in stock_list:
            self.add_stock( stock_data )
    else:
        if not self.database_exists( self.db_path ):
            return None

        self.import_portfolio_data()
        self.import_stocks()
</code>```

Most of this is copy-pasted, so I can't attest to the accuracy of the indentation, etc., but this is the general pattern for creating versatile __init__ methods in Python (note that __init__ by itself is not a constructor, it's an initializer). Since Python supports keyword args and default values for keyword args, there's really no reason to ever use overloading (in fact, we save a lot of repetitious code by not having overloading). Instead, we just use a keyword arg stock_list with a default value of None.

This isn't perfectly fixed up, either; some of the problems persist (since it's copy-pasted). I don't know the details of what the constructor does, but I think with a little more refactoring you could get things set up where the __init__ is much shorter and much more elegant (consider separating out pieces of the initialization into methods, like _init_db() and call those from __init__).

ContentLicense: CC BY-SA 2.5

Title: Python: How can I merge these 2 overloaded constructors into 1 constructor

Body:
def __init__(self, _app_parent, _db_path, stock_list=None):
    self.db_path            = _db_path
    self.app_parent         = _app_parent
    self.tracking_stocks    = []
    self.registered_stocks  = []
    self.total_purchase_exp = 0
    self.ytd_roi            = 0
    self.cash_reserve       = 500

    if stock_list:
        if database_exists( self.db_path ):
            return None
        self.create_database()
        self.import_portfolio_data()
        for stock_data in stock_list:
            self.add_stock( stock_data )
    else:
        if not self.database_exists( self.db_path ):
            return None

        self.import_portfolio_data()
        self.import_stocks()

Most of this is copy-pasted, so I can't attest to the accuracy of the indentation, etc., but this is the general pattern for creating versatile __init__ methods in Python (note that __init__ by itself is not a constructor, it's an initializer). Since Python supports keyword args and default values for keyword args, there's really no reason to ever use overloading (in fact, we save a lot of repetitious code by not having overloading). Instead, we just use a keyword arg stock_list with a default value of None.

This isn't perfectly fixed up, either; some of the problems persist (since it's copy-pasted). I don't know the details of what the constructor does, but I think with a little more refactoring you could get things set up where the __init__ is much shorter and much more elegant (consider separating out pieces of the initialization into methods, like _init_db() and call those from __init__).


问:
Insert Multiple Bitmap Image into Multiple Worksheet
In my folder, there is AA.bmp, AA.txt, BB.bmp and BB.txt

I am able to extract the data for AA.txt and BB.txt in a separate worksheet.

Am I also able to insert AA.bmp in the same sheet as AA.txt, and BB.bmp in the same sheet as BB.txt?

```<code>Sub ExtractData()
iPath = "C:\Users\NHWD78\Desktop\Report\Radiated Immunity\"
ifile = Dir(iPath & "*.txt")

Do While Len(ifile)
Sheets.Add , Sheets(Sheets.Count), , iPath & ifile
ifile = Dir
Range("A10:B10, A16:B19").Copy Destination:=Sheets(Sheets.Count).Range("A1")

Application.CutCopyMode = False
Range("A6:K600").Clear
Columns.AutoFit

Loop
End Sub
</code>```

I have search throughout the website but only found a way to insert a fixed image with image name.

答:
This will answer your query, its more of a solution than an answer which is not what this site is for, but take the time to read through it as it should be educationally useful too.

You are trying to parse a folder that has content similar to below:-

The result os for these to be in an Excel workbook, with a worksheet containing the text and image for each group (AA, BB, and CC)

First step I would take is to use Microsoft Scripting Runtime, this makes parsing the folder a lot easier. To enable this, within the VBA environment (known as the IDE), select 'Tools' > 'References...', scroll down to 'Microsoft Scripting Runtime' and tick it, then click 'OK' to close the dialog box.

That allows us to the File System Object, which is a very useful file and folder manipulation and interrogation feature set.

Firstly we care most about the *.txt files so lets begin by looping through them:-

```<code>Dim FSO     As New FileSystemObject
Dim Fldr    As Folder
Dim Fl      As File

'First we set Fldr to be the folder we care about
Set Fldr = FSO.GetFolder("C:\Users\garye\Desktop\Work")

    'Then start a loop to look through each file in the folder
    For Each Fl In Fldr.Files

        'If the files ends in .txt then we care about it (UCASE used to make it case insensitive)
        If Right(UCase(Fl.Name), 4) = ".TXT" Then

            'We have found a file

        End If

        'Do events returns the processor to the system for any other items to be process
        'very useful in a loop on a Windows based machine to stop resource hogging and lock ups
        DoEvents
    Next
Set Fldr = Nothing
</code>```

Next on the discovery of a text file we want to create a worksheet and import the text. For the sake of this example, it will all be done in a new workbook as well.

```<code>Dim WkBk        As Workbook
Dim WkBk_Tmp    As Workbook
Dim WkSht       As Worksheet
Dim WkSht_Tmp   As Worksheet
Dim StrName     As String

'Create a new workbook
Set WkBk = Application.Workbooks.Add

'...

'Collect the name (i.e. AA from AA.txt)
StrName = Left(Fl.Name, Len(Fl.Name) - 4)

'Create a new worksheet in out new workbook
Set WkSht = WkBk.Worksheets.Add

    'Change the worksheet name to the file name
    WkSht.Name = StrName

    'Open the file in Excel
    Set WkBk_Tmp = Application.Workbooks.Open(Fl.Path)
        Set WkSht_Tmp = WkBk_Tmp.Worksheets(1)

            'Copy its contents into out worksheet
            WkSht_Tmp.Cells.Copy WkSht.Cells
        Set WkSht_Tmp = Nothing

        'Close the file
        WkBk_Tmp.Close 0
    Set WkBk_Tmp = Nothing
</code>```

Next we want to insert the image if it is there:-

```<code>Dim Rng         As Range

'...

'See it a bmp file exists (i.e. AA.bmp)
If FSO.FileExists(Fldr.Path & "\" & StrName & ".bmp") Then

    'This get the bottom row of data as a position to insert the image
    Set Rng = WkSht.Range(WkSht.Range("A1").End(xlDown).Address).Next(2, 0)

        'Add the picture
        WkSht.Shapes.AddPicture Fldr.Path & "\" & StrName & ".bmp", msoFalse, msoCTrue, Rng.Left, Rng.Top, -1, -1

    Set Rng = Nothing

 End If
</code>```

If we put all the above together it looks as below, hopefully this has been education in what is happening in the code, some good practices, how to approaching a task.

Option Explicit

```<code>Sub ExtractData()
Dim FSO         As New FileSystemObject
Dim Fldr        As Folder
Dim Fl          As File
Dim WkBk        As Workbook
Dim WkBk_Tmp    As Workbook
Dim WkSht       As Worksheet
Dim WkSht_Tmp   As Worksheet
Dim StrName     As String
Dim Rng         As Range

'Create a new workbook
Set WkBk = Application.Workbooks.Add

    'First we set Fldr to be the folder we care about
    Set Fldr = FSO.GetFolder("C:\Users\garye\Desktop\Work")

        'Then start a loop to look through each file in the folder
        For Each Fl In Fldr.Files

            'If the files ends in .txt then we care about it (UCASE used to make it case insensitive)
            If Right(UCase(Fl.Name), 4) = ".TXT" Then

                'Collect the name (i.e. AA from AA.txt)
                StrName = Left(Fl.Name, Len(Fl.Name) - 4)

                'Create a new worksheet in out new workbook
                Set WkSht = WkBk.Worksheets.Add

                    'Change the worksheet name to the file name
                    WkSht.Name = StrName

                    'Open the file in Excel
                    Set WkBk_Tmp = Application.Workbooks.Open(Fl.Path)
                        Set WkSht_Tmp = WkBk_Tmp.Worksheets(1)

                            'Copy its contents into out worksheet
                            WkSht_Tmp.Cells.Copy WkSht.Cells
                        Set WkSht_Tmp = Nothing

                        'Close the file
                        WkBk_Tmp.Close 0
                    Set WkBk_Tmp = Nothing

                    'See it a bmp file exists (i.e. AA.bmp)
                    If FSO.FileExists(Fldr.Path & "\" & StrName & ".bmp") Then

                        'This get the bottom row of data as a position to insert the image
                        Set Rng = WkSht.Range(WkSht.Range("A1").End(xlDown).Address).Next(2, 0)

                            'Add the picture
                            WkSht.Shapes.AddPicture Fldr.Path & "\" & StrName & ".bmp", msoFalse, msoCTrue, Rng.Left, Rng.Top, -1, -1

                        Set Rng = Nothing

                    End If

                Set WkSht = Nothing

            End If

            'Do events returns the processor to the system for any other items to be process
            'very useful in a loop on a Windows based machine to stop resource hogging and lock ups
            DoEvents
        Next
    Set Fldr = Nothing

Set WkBk = Nothing

MsgBox "Done!"

End Sub
</code>```

Body:
In my folder, there is AA.bmp, AA.txt, BB.bmp and BB.txt

I am able to extract the data for AA.txt and BB.txt in a separate worksheet.

Am I also able to insert AA.bmp in the same sheet as AA.txt, and BB.bmp in the same sheet as BB.txt?

Sub ExtractData()
iPath = "C:\Users\NHWD78\Desktop\Report\Radiated Immunity\"
ifile = Dir(iPath & "*.txt")

Do While Len(ifile)
Sheets.Add , Sheets(Sheets.Count), , iPath & ifile
ifile = Dir
Range("A10:B10, A16:B19").Copy Destination:=Sheets(Sheets.Count).Range("A1")

Application.CutCopyMode = False
Range("A6:K600").Clear
Columns.AutoFit

Loop
End Sub

I have search throughout the website but only found a way to insert a fixed image with image name.

Body:
This will answer your query, its more of a solution than an answer which is not what this site is for, but take the time to read through it as it should be educationally useful too.

You are trying to parse a folder that has content similar to below:-

The result os for these to be in an Excel workbook, with a worksheet containing the text and image for each group (AA, BB, and CC)

First step I would take is to use Microsoft Scripting Runtime, this makes parsing the folder a lot easier. To enable this, within the VBA environment (known as the IDE), select 'Tools' > 'References...', scroll down to 'Microsoft Scripting Runtime' and tick it, then click 'OK' to close the dialog box.

That allows us to the File System Object, which is a very useful file and folder manipulation and interrogation feature set.

Firstly we care most about the *.txt files so lets begin by looping through them:-

Dim FSO     As New FileSystemObject
Dim Fldr    As Folder
Dim Fl      As File

'First we set Fldr to be the folder we care about
Set Fldr = FSO.GetFolder("C:\Users\garye\Desktop\Work")

    'Then start a loop to look through each file in the folder
    For Each Fl In Fldr.Files

        'If the files ends in .txt then we care about it (UCASE used to make it case insensitive)
        If Right(UCase(Fl.Name), 4) = ".TXT" Then

            'We have found a file

        End If

        'Do events returns the processor to the system for any other items to be process
        'very useful in a loop on a Windows based machine to stop resource hogging and lock ups
        DoEvents
    Next
Set Fldr = Nothing

Next on the discovery of a text file we want to create a worksheet and import the text. For the sake of this example, it will all be done in a new workbook as well.

Dim WkBk        As Workbook
Dim WkBk_Tmp    As Workbook
Dim WkSht       As Worksheet
Dim WkSht_Tmp   As Worksheet
Dim StrName     As String

'Create a new workbook
Set WkBk = Application.Workbooks.Add

'...

'Collect the name (i.e. AA from AA.txt)
StrName = Left(Fl.Name, Len(Fl.Name) - 4)

'Create a new worksheet in out new workbook
Set WkSht = WkBk.Worksheets.Add

    'Change the worksheet name to the file name
    WkSht.Name = StrName

    'Open the file in Excel
    Set WkBk_Tmp = Application.Workbooks.Open(Fl.Path)
        Set WkSht_Tmp = WkBk_Tmp.Worksheets(1)

            'Copy its contents into out worksheet
            WkSht_Tmp.Cells.Copy WkSht.Cells
        Set WkSht_Tmp = Nothing

        'Close the file
        WkBk_Tmp.Close 0
    Set WkBk_Tmp = Nothing

Next we want to insert the image if it is there:-

Dim Rng         As Range

'...

'See it a bmp file exists (i.e. AA.bmp)
If FSO.FileExists(Fldr.Path & "\" & StrName & ".bmp") Then

    'This get the bottom row of data as a position to insert the image
    Set Rng = WkSht.Range(WkSht.Range("A1").End(xlDown).Address).Next(2, 0)

        'Add the picture
        WkSht.Shapes.AddPicture Fldr.Path & "\" & StrName & ".bmp", msoFalse, msoCTrue, Rng.Left, Rng.Top, -1, -1

    Set Rng = Nothing

 End If

If we put all the above together it looks as below, hopefully this has been education in what is happening in the code, some good practices, how to approaching a task.

Option Explicit

Sub ExtractData()
Dim FSO         As New FileSystemObject
Dim Fldr        As Folder
Dim Fl          As File
Dim WkBk        As Workbook
Dim WkBk_Tmp    As Workbook
Dim WkSht       As Worksheet
Dim WkSht_Tmp   As Worksheet
Dim StrName     As String
Dim Rng         As Range

'Create a new workbook
Set WkBk = Application.Workbooks.Add

    'First we set Fldr to be the folder we care about
    Set Fldr = FSO.GetFolder("C:\Users\garye\Desktop\Work")

        'Then start a loop to look through each file in the folder
        For Each Fl In Fldr.Files

            'If the files ends in .txt then we care about it (UCASE used to make it case insensitive)
            If Right(UCase(Fl.Name), 4) = ".TXT" Then

                'Collect the name (i.e. AA from AA.txt)
                StrName = Left(Fl.Name, Len(Fl.Name) - 4)

                'Create a new worksheet in out new workbook
                Set WkSht = WkBk.Worksheets.Add

                    'Change the worksheet name to the file name
                    WkSht.Name = StrName

                    'Open the file in Excel
                    Set WkBk_Tmp = Application.Workbooks.Open(Fl.Path)
                        Set WkSht_Tmp = WkBk_Tmp.Worksheets(1)

                            'Copy its contents into out worksheet
                            WkSht_Tmp.Cells.Copy WkSht.Cells
                        Set WkSht_Tmp = Nothing

                        'Close the file
                        WkBk_Tmp.Close 0
                    Set WkBk_Tmp = Nothing

                    'See it a bmp file exists (i.e. AA.bmp)
                    If FSO.FileExists(Fldr.Path & "\" & StrName & ".bmp") Then

                        'This get the bottom row of data as a position to insert the image
                        Set Rng = WkSht.Range(WkSht.Range("A1").End(xlDown).Address).Next(2, 0)

                            'Add the picture
                            WkSht.Shapes.AddPicture Fldr.Path & "\" & StrName & ".bmp", msoFalse, msoCTrue, Rng.Left, Rng.Top, -1, -1

                        Set Rng = Nothing

                    End If

                Set WkSht = Nothing

            End If

            'Do events returns the processor to the system for any other items to be process
            'very useful in a loop on a Windows based machine to stop resource hogging and lock ups
            DoEvents
        Next
    Set Fldr = Nothing

Set WkBk = Nothing

MsgBox "Done!"

End Sub


问:
i have an error in column application can't get data from some column in table android
```<code>public void onCreate(SQLiteDatabase db) {
   String CREATE_TABLE= "CREATE TABLE " + Constants.TABLE1_NAME + "(" +
           Constants.KEY_ID + " INTEGER PRIMARY KEY, "+Constants.EMP_NAME+" Text, " + Constants.PHONE_NUMBER_NAME+" TEXT, " + Constants.EMP_ID+" INT ); ";
    db.execSQL(CREATE_TABLE);
}

public int getEmpId(){
    int EmpId=0;
    SQLiteDatabase db=this.getReadableDatabase();

    String query="SELECT "+Constants.EMP_ID +" FROM "+Constants.TABLE1_NAME;
    Cursor cursor=db.rawQuery(query,null);
    if(cursor.moveToFirst())
    {EmpId=cursor.getInt(0);}

    cursor.close();
    db.close();

    return EmpId;

}
</code>```

android.database.sqlite.SQLiteException: no such column: id (code 1):
  , while compiling: SELECT id FROM info
                                                                                at
  android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native
  Method)
                                                                                at
  android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
                                                                                at
  android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
                                                                                at
  android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                                                at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:58)
                                                                                at android.database.sqlite.SQLiteQuery.(SQLiteQuery.java:37)
                                                                                at
  android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
                                                                                at
  android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1316)
                                                                                at
  android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1255)
                                                                                at Data.DatabaseHandeler$override.getEmpId(DatabaseHandeler.java:61)
                                                                                at
  Data.DatabaseHandeler$override.access$dispatch(DatabaseHandeler.java)
                                                                                at Data.DatabaseHandeler.getEmpId(DatabaseHandeler.java:0)
                                                                                at
  imageview.example.maged.taskforseautomation.MainActivity$override.suresignin(MainActivity.java:60)
                                                                                at
  imageview.example.maged.taskforseautomation.MainActivity$override.onClick(MainActivity.java:75)
                                                                                at
  imageview.example.maged.taskforseautomation.MainActivity$override.access$dispatch(MainActivity.java)
                                                                                at
  imageview.example.maged.taskforseautomation.MainActivity.onClick(MainActivity.java:0)
                                                                                at android.view.View.performClick(View.java:4780)
                                                                                at android.view.View$PerformClick.run(View.java:19866)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

答:
In your table you did not create colum id, and you are specifying in your SQL query, so thats why its showing error.
Try loggin your table create query and watch clearly</p>

Body:
public void onCreate(SQLiteDatabase db) {
   String CREATE_TABLE= "CREATE TABLE " + Constants.TABLE1_NAME + "(" +
           Constants.KEY_ID + " INTEGER PRIMARY KEY, "+Constants.EMP_NAME+" Text, " + Constants.PHONE_NUMBER_NAME+" TEXT, " + Constants.EMP_ID+" INT ); ";
    db.execSQL(CREATE_TABLE);
}

public int getEmpId(){
    int EmpId=0;
    SQLiteDatabase db=this.getReadableDatabase();

    String query="SELECT "+Constants.EMP_ID +" FROM "+Constants.TABLE1_NAME;
    Cursor cursor=db.rawQuery(query,null);
    if(cursor.moveToFirst())
    {EmpId=cursor.getInt(0);}

    cursor.close();
    db.close();

    return EmpId;

}

android.database.sqlite.SQLiteException: no such column: id (code 1):
  , while compiling: SELECT id FROM info
                                                                                at
  android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native
  Method)
                                                                                at
  android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
                                                                                at
  android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
                                                                                at
  android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                                                at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:58)
                                                                                at android.database.sqlite.SQLiteQuery.(SQLiteQuery.java:37)
                                                                                at
  android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
                                                                                at
  android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1316)
                                                                                at
  android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1255)
                                                                                at Data.DatabaseHandeler$override.getEmpId(DatabaseHandeler.java:61)
                                                                                at
  Data.DatabaseHandeler$override.access$dispatch(DatabaseHandeler.java)
                                                                                at Data.DatabaseHandeler.getEmpId(DatabaseHandeler.java:0)
                                                                                at
  imageview.example.maged.taskforseautomation.MainActivity$override.suresignin(MainActivity.java:60)
                                                                                at
  imageview.example.maged.taskforseautomation.MainActivity$override.onClick(MainActivity.java:75)
                                                                                at
  imageview.example.maged.taskforseautomation.MainActivity$override.access$dispatch(MainActivity.java)
                                                                                at
  imageview.example.maged.taskforseautomation.MainActivity.onClick(MainActivity.java:0)
                                                                                at android.view.View.performClick(View.java:4780)
                                                                                at android.view.View$PerformClick.run(View.java:19866)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)


问:
Postgres View Returning correct rows when executing SQL, but with REST query returns one row multiple times
Morning folks, I have the following View named user_popular_photos. Let me give a bit of explanation regarding the query here. feed_item is a table and feed_item_counts is a another view which combines the number of likes from entries in another table for that specific feed_item

```<code>SELECT f.author,
    f.thumbnail_url,
    f.feed_id
   FROM feed_item f
     JOIN ( SELECT f2.feed_item_id,
            f2.like_count AS count
           FROM feed_item_counts f2
          WHERE f2.like_count > 0) t2 ON f.feed_id = t2.feed_item_id
  ORDER BY t2.count DESC;
</code>```

When I run this query against the database (PGAdmin View Data - View All Rows) I get the desired results

```<code>author | thumbnail_url | feed_id   |
user1  | thumb 1       | feed_id 1 |
user1  | thumb 2       | feed_id 2 |
user1  | thumb 3       | feed_id 3 |
user2  | thumb 1       | feed_id 1 |
user2  | thumb 2       | feed_id 2 | and so on...
</code>```

However with my REST (Spring Boot) when I attempt to get the results back I get the following

```<code>{
  "username" : "user1",
  "popularPhotos" : [ {
    "feedId" : feed_id 3,
    "thumbnailUrl" : "thumb 3"
  }, {
    "feedId" : feed_id 3,
    "thumbnailUrl" : "thumb 3"
  }, {
    "feedId" : feed_id 3,
    "thumbnailUrl" : "thumb 3"
  } ]
}
</code>```

Which is generated via the following;

User.Java

```<code>@Entity
@Table(name = "user_details")
public class User {

    @Id
    @NotNull @NotEmpty
    @JsonView(UserView.Summary.class)
    private String username;

    @JsonView(UserView.Summary.class)
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "username")
    public List<UserPopularPhotos> popularPhotos;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public List<UserPopularPhotos> getPopularPhotos(){
        return popularPhotos;
    }

    public void setPopularPhotos(List<UserPopularPhotos> popularPhotos){
        this.popularPhotos = popularPhotos;
    }
</code>```

UserPopularPhotos

```<code>@Entity
@Table(name = "user_popular_photos")
@Immutable
public class UserPopularPhotos {

    @Id
    @Column(name = "author", insertable = false, updatable = false)
    @JsonIgnore
    public String username;

    @JsonView(UserView.Summary.class)
    @Column(name = "id", insertable = false, updatable = false)
    public Integer feedId;

    @JsonView(UserView.Summary.class)
    @Column(name = "thumbnail_url", insertable = false, updatable = false)
    public String thumbnailUrl;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Integer getFeedId(){
        return feedId;
    }
    public void setFeedId(Integer feedId){
        this.feedId = feedId;
    }

    public String getThumbnailUrl() {
        return thumbnailUrl;
    }

    public void setThumbnailUrl(String thumbnailUrl) {
        this.thumbnailUrl = thumbnailUrl;
    }
}
</code>```

What am I missing here, I can't put a finger on why the query in PGAdmin returns correct results but the API query returns the same result (top entry for that user) multiple times?

答:
The @Id annotation is not on the unique identifier for the user_popular_photos view. Removed it from the username and added to the feedId.

UserPopularPhotos.java

```<code>@Entity
@Table(name = "user_popular_photos")
@Immutable

public class UserPopularPhotos {

@Column(name = "author", insertable = false, updatable = false)
@JsonIgnore
public String username;

@Id
@JsonView(UserView.Summary.class)
@Column(name = "id", insertable = false, updatable = false)
public Integer feedId;

@JsonView(UserView.Summary.class)
@Column(name = "thumbnail_url", insertable = false, updatable = false)
public String thumbnailUrl;

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public Integer getFeedId(){
    return feedId;
}
public void setFeedId(Integer feedId){
    this.feedId = feedId;
}

public String getThumbnailUrl() {
    return thumbnailUrl;
}

public void setThumbnailUrl(String thumbnailUrl) {
    this.thumbnailUrl = thumbnailUrl;
}
</code>```

}

Making this change gives the desired return result from the API

Body:
Morning folks, I have the following View named user_popular_photos. Let me give a bit of explanation regarding the query here. feed_item is a table and feed_item_counts is a another view which combines the number of likes from entries in another table for that specific feed_item

SELECT f.author,
    f.thumbnail_url,
    f.feed_id
   FROM feed_item f
     JOIN ( SELECT f2.feed_item_id,
            f2.like_count AS count
           FROM feed_item_counts f2
          WHERE f2.like_count > 0) t2 ON f.feed_id = t2.feed_item_id
  ORDER BY t2.count DESC;

When I run this query against the database (PGAdmin View Data - View All Rows) I get the desired results

author | thumbnail_url | feed_id   |
user1  | thumb 1       | feed_id 1 |
user1  | thumb 2       | feed_id 2 |
user1  | thumb 3       | feed_id 3 |
user2  | thumb 1       | feed_id 1 |
user2  | thumb 2       | feed_id 2 | and so on...

However with my REST (Spring Boot) when I attempt to get the results back I get the following

{
  "username" : "user1",
  "popularPhotos" : [ {
    "feedId" : feed_id 3,
    "thumbnailUrl" : "thumb 3"
  }, {
    "feedId" : feed_id 3,
    "thumbnailUrl" : "thumb 3"
  }, {
    "feedId" : feed_id 3,
    "thumbnailUrl" : "thumb 3"
  } ]
}

Which is generated via the following;

User.Java

@Entity
@Table(name = "user_details")
public class User {

    @Id
    @NotNull @NotEmpty
    @JsonView(UserView.Summary.class)
    private String username;

    @JsonView(UserView.Summary.class)
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "username")
    public List<UserPopularPhotos> popularPhotos;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public List<UserPopularPhotos> getPopularPhotos(){
        return popularPhotos;
    }

    public void setPopularPhotos(List<UserPopularPhotos> popularPhotos){
        this.popularPhotos = popularPhotos;
    }

UserPopularPhotos

@Entity
@Table(name = "user_popular_photos")
@Immutable
public class UserPopularPhotos {

    @Id
    @Column(name = "author", insertable = false, updatable = false)
    @JsonIgnore
    public String username;

    @JsonView(UserView.Summary.class)
    @Column(name = "id", insertable = false, updatable = false)
    public Integer feedId;

    @JsonView(UserView.Summary.class)
    @Column(name = "thumbnail_url", insertable = false, updatable = false)
    public String thumbnailUrl;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Integer getFeedId(){
        return feedId;
    }
    public void setFeedId(Integer feedId){
        this.feedId = feedId;
    }

    public String getThumbnailUrl() {
        return thumbnailUrl;
    }

    public void setThumbnailUrl(String thumbnailUrl) {
        this.thumbnailUrl = thumbnailUrl;
    }
}

What am I missing here, I can't put a finger on why the query in PGAdmin returns correct results but the API query returns the same result (top entry for that user) multiple times?

Body:
The @Id annotation is not on the unique identifier for the user_popular_photos view. Removed it from the username and added to the feedId.

UserPopularPhotos.java

@Entity
@Table(name = "user_popular_photos")
@Immutable

public class UserPopularPhotos {

@Column(name = "author", insertable = false, updatable = false)
@JsonIgnore
public String username;

@Id
@JsonView(UserView.Summary.class)
@Column(name = "id", insertable = false, updatable = false)
public Integer feedId;

@JsonView(UserView.Summary.class)
@Column(name = "thumbnail_url", insertable = false, updatable = false)
public String thumbnailUrl;

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public Integer getFeedId(){
    return feedId;
}
public void setFeedId(Integer feedId){
    this.feedId = feedId;
}

public String getThumbnailUrl() {
    return thumbnailUrl;
}

public void setThumbnailUrl(String thumbnailUrl) {
    this.thumbnailUrl = thumbnailUrl;
}

}

Making this change gives the desired return result from the API


问:
Is there an ExecutorService that creates a new thread for every task?
I need to unit-test some functionality that works across threads, for which I need to guarantee that two jobs are run on different threads.

Using Executors.newCachedThreadPool() introduces a race-condition, because the test may or may not use the cached thread-pool.

Is there an ExecutorService that always uses a new thread?

答:
Use a java.util.concurrent.ThreadPoolExecutor with a corePoolSize of 0 and a keepAliveTime of 0. This will make new tasks spawn a new thread, and threads will be killed immediately after tasks are terminated.

For example:

```<code>final ExecutorService executorService = new ThreadPoolExecutor(
    0, 2, 0, TimeUnit.SECONDS, new SynchronousQueue<>());

executorService.submit(task1);
executorService.submit(task2);
</code>```

Body:
Use a java.util.concurrent.ThreadPoolExecutor with a corePoolSize of 0 and a keepAliveTime of 0. This will make new tasks spawn a new thread, and threads will be killed immediately after tasks are terminated.

For example:

final ExecutorService executorService = new ThreadPoolExecutor(
    0, 2, 0, TimeUnit.SECONDS, new SynchronousQueue<>());

executorService.submit(task1);
executorService.submit(task2);


问:
Prestashop product combination display on product list
I am trying to get available product combination (size) in product list page on each product. Basically there is a image, product name, available combinations, price, buy button.

I tried to out put $product object, but it does not have combination variable to it.

Is there any way to achieve that?

答:
There is function assignAttributesGroups() in the ProductController.php from where you can get code for size combination.

```<code>protected function assignAttributesGroups()
{
...
...
...
$this->context->smarty->assign(array(
            'groups' => $groups,
            'colors' => (count($colors)) ? $colors : false,
            'combinations' => $combinations,
            'combinationImages' => $combination_images
        ));
}
</code>```

If you print the value of groups you will get desired output. The combinations has been arranged to show dropdown in product.tpl(/PRESTASHOP_FOLDER/themes/default-bootstrap/product.tpl) as shown in image

You can take a code from the function mentioned above and run it for every product in the list. You have to create a product object and receive combination through it. And create a drop down for the same.

Body:
There is function assignAttributesGroups() in the ProductController.php from where you can get code for size combination.

protected function assignAttributesGroups()
{
...
...
...
$this->context->smarty->assign(array(
            'groups' => $groups,
            'colors' => (count($colors)) ? $colors : false,
            'combinations' => $combinations,
            'combinationImages' => $combination_images
        ));
}

If you print the value of groups you will get desired output. The combinations has been arranged to show dropdown in product.tpl(/PRESTASHOP_FOLDER/themes/default-bootstrap/product.tpl) as shown in image

You can take a code from the function mentioned above and run it for every product in the list. You have to create a product object and receive combination through it. And create a drop down for the same.


问:
How to fill all rows in a column with data from other columns?
I have a dataset called 'names' as shown below. The 'expected.entry.in.this.col' column is currently empty, but below I have shown how it should look. How can I write the logic?

Basically I think I'll need to run a loop through every row and for each row, use an 'if' condition to check the format and then enter the data into 'expected.entry.in.this.col' appropriately. How would I go about doing this? (a bit unfamiliar with R syntax for these kind of tasks).

names

EDIT: row 3 is a mistake and should read williams.harry

答:
I've made like this, I hope you'll get the logic ! Tell me if it's what you want</p>

```<code>first = c('John','Michael',"Harry","Stephen","Simon",'Rachael',"Paul")
last = c("smith","Johnson","Williams","Jones","Adams","Moore","Taylor")
format = c("first.last","firstlast","last.first","f.last","flast","f_last","f_last")

names = data.frame(cbind(first,last,format))

names$first = as.character(names$first)
names$last = as.character(names$last)
names$format = as.character(names$format)

library(stringr)

for (i in 1:dim(names)[1]){
  if (names[i,"format"] == "first.last"){
    names[i,"new_var"] = paste(tolower(names[i,"first"]),tolower(names[i,"last"]), sep = '.')
  }else if (names[i,"format"] == "firstlast"){
    names[i,"new_var"]= paste(tolower(names[i,"first"]),tolower(names[i,"last"]), sep = '')
  }else if (names[i,"format"] == "last.first"){
    names[i,"new_var"] = paste(tolower(names[i,"last"]),tolower(names[i,"first"]), sep = '.')
  }else if (names[i,"format"] == "f.last"){
    names[i,"new_var"] = paste(tolower(str_sub(names[i,"first"],1,1)),tolower(names[i,"last"]),sep=".")
  }else if (names[i,"format"] == "flast"){
    names[i,"new_var"] = paste(tolower(str_sub(names[i,"first"],1,1)),tolower(names[i,"last"]),sep="")
  }else{
    names[i,"new_var"] = paste(tolower(str_sub(names[i,"first"],1,1)),tolower(names[i,"last"]),sep="_")
  }
}

names

    first     last     format        new_var
1    John    smith first.last     john.smith
2 Michael  Johnson  firstlast michaeljohnson
3   Harry Williams last.first williams.harry
4 Stephen    Jones     f.last        s.jones
5   Simon    Adams      flast         sadams
6 Rachael    Moore     f_last        r_moore
7    Paul   Taylor     f_last       p_taylor
>
</code>```

Body:
I've made like this, I hope you'll get the logic ! Tell me if it's what you want

first = c('John','Michael',"Harry","Stephen","Simon",'Rachael',"Paul")
last = c("smith","Johnson","Williams","Jones","Adams","Moore","Taylor")
format = c("first.last","firstlast","last.first","f.last","flast","f_last","f_last")

names = data.frame(cbind(first,last,format))

names$first = as.character(names$first)
names$last = as.character(names$last)
names$format = as.character(names$format)

library(stringr)

for (i in 1:dim(names)[1]){
  if (names[i,"format"] == "first.last"){
    names[i,"new_var"] = paste(tolower(names[i,"first"]),tolower(names[i,"last"]), sep = '.')
  }else if (names[i,"format"] == "firstlast"){
    names[i,"new_var"]= paste(tolower(names[i,"first"]),tolower(names[i,"last"]), sep = '')
  }else if (names[i,"format"] == "last.first"){
    names[i,"new_var"] = paste(tolower(names[i,"last"]),tolower(names[i,"first"]), sep = '.')
  }else if (names[i,"format"] == "f.last"){
    names[i,"new_var"] = paste(tolower(str_sub(names[i,"first"],1,1)),tolower(names[i,"last"]),sep=".")
  }else if (names[i,"format"] == "flast"){
    names[i,"new_var"] = paste(tolower(str_sub(names[i,"first"],1,1)),tolower(names[i,"last"]),sep="")
  }else{
    names[i,"new_var"] = paste(tolower(str_sub(names[i,"first"],1,1)),tolower(names[i,"last"]),sep="_")
  }
}

names

    first     last     format        new_var
1    John    smith first.last     john.smith
2 Michael  Johnson  firstlast michaeljohnson
3   Harry Williams last.first williams.harry
4 Stephen    Jones     f.last        s.jones
5   Simon    Adams      flast         sadams
6 Rachael    Moore     f_last        r_moore
7    Paul   Taylor     f_last       p_taylor
>


问:
Knockout JS - textInput binding update is delayed by one character
I'm currently trying to display a message that depends on instant update of the contents of my input text box using knockout.js. the textInput binding seems to work great except it only updates after I've already typed one character. On the first character, it says it is not defined.

HTML:

```<code> <input id="userResponse"
                       data-bind="textInput: textInput,
                              hasFocus: responseSelected,
                              ojComponent: {component: 'ojInputText',
                                            value: userResponse,
                                            rootAttributes: {
                                            style:'font-size:32px; max-width:100%;'}}"
                       autofocus/>
</code>```

JS

```<code>self.textInput = ko.observable();
self.responseTypeValidation = function (keyCode) {
                oj.Logger.log("input: " +self.textInput());
                if (self.promptMetadata()) {

                    if(self.textInput().match(/[a-z]/))
                    {
                        self.responseErrorMessage("Numbers only");
                    }
                    else {
                       self.responseErrorMessage('');
                    }
                }
            };
</code>```

For example when I type "hello" it will throw error saying textInput is undefined on the "h" and then while I type "ello" it does what I actually want it to do (which is display the "numbers only" message). Why would it not be updating on the first input character? Any help figuring this out would be appreciated

EDIT:
Here is my log when the input box reads "he", with the "h" throwing the error and the "e" not yet being read

```<code>jobCommand.js:81 Uncaught TypeError: Cannot read property 'match' of undefined
at jobCommandContentViewModel.self.responseTypeValidation (jobCommand.js:81)
at ControllerViewModel.keyDown (jobCommand.js:33)
at HTMLDivElement.<anonymous> (appController.js:60)
at HTMLDivElement.dispatch (jquery-3.1.1.js:5201)
at HTMLDivElement.elemData.handle (jquery-3.1.1.js:5009)

ojcore.js:262 input: h
</code>```

答:
Since using textInput this updates your model immediately on each keystroke or other text entry mechanism (such as cutting or dragging text, which don’t necessarily raise any focus change events).

Therefore:

Solution 1 (Computed):

```<code>self.Validation = ko.computed(function () {
    if(self.textInput().match(/[a-z]/))
        self.responseErrorMessage("Numbers only");
    else
        self.responseErrorMessage('');
}, self);
</code>```

Solution 2 (subscribe):

```<code>self.textInput.subscribe(function (newValue) {
    if(newValue.match(/[a-z]/))
        self.responseErrorMessage("Numbers only");
    else
        self.responseErrorMessage('');
});
</code>```

Body:
I'm currently trying to display a message that depends on instant update of the contents of my input text box using knockout.js. the textInput binding seems to work great except it only updates after I've already typed one character. On the first character, it says it is not defined.

HTML:

 <input id="userResponse"
                       data-bind="textInput: textInput,
                              hasFocus: responseSelected,
                              ojComponent: {component: 'ojInputText',
                                            value: userResponse,
                                            rootAttributes: {
                                            style:'font-size:32px; max-width:100%;'}}"
                       autofocus/>

JS

self.textInput = ko.observable();
self.responseTypeValidation = function (keyCode) {
                oj.Logger.log("input: " +self.textInput());
                if (self.promptMetadata()) {

                    if(self.textInput().match(/[a-z]/))
                    {
                        self.responseErrorMessage("Numbers only");
                    }
                    else {
                       self.responseErrorMessage('');
                    }
                }
            };

For example when I type "hello" it will throw error saying textInput is undefined on the "h" and then while I type "ello" it does what I actually want it to do (which is display the "numbers only" message). Why would it not be updating on the first input character? Any help figuring this out would be appreciated

EDIT:
Here is my log when the input box reads "he", with the "h" throwing the error and the "e" not yet being read

jobCommand.js:81 Uncaught TypeError: Cannot read property 'match' of undefined
at jobCommandContentViewModel.self.responseTypeValidation (jobCommand.js:81)
at ControllerViewModel.keyDown (jobCommand.js:33)
at HTMLDivElement.<anonymous> (appController.js:60)
at HTMLDivElement.dispatch (jquery-3.1.1.js:5201)
at HTMLDivElement.elemData.handle (jquery-3.1.1.js:5009)

ojcore.js:262 input: h

Body:
Since using textInput this updates your model immediately on each keystroke or other text entry mechanism (such as cutting or dragging text, which don’t necessarily raise any focus change events).

Therefore:

Solution 1 (Computed):

self.Validation = ko.computed(function () {
    if(self.textInput().match(/[a-z]/))
        self.responseErrorMessage("Numbers only");
    else
        self.responseErrorMessage('');
}, self);

Solution 2 (subscribe):

self.textInput.subscribe(function (newValue) {
    if(newValue.match(/[a-z]/))
        self.responseErrorMessage("Numbers only");
    else
        self.responseErrorMessage('');
});


问:
Why stdin of parent process still accepts inputs after closing stdin file descriptor from a forked child process?
fork(2) manual page on the Linux system I'm running says the following:

The child inherits copies of the parent's set of open file descriptors.  Each file descriptor in the  child  refers  to  the  same  open file description (see open(2)) as the corresponding file descriptor in the parent.  This means that the two  file  descriptors  share  open  file  status flags, file offset, and signal-driven I/O attributes (see the description of F_SETOWN and F_SET‐SIG in fcntl(2)).

And Python Documentation mentions

_exit() should normally only be used in the child process after a fork().

Of course, _exit won't call cleanup handlers, the problem is that, if you look at this code for instance:

```<code>newpid = os.fork()
if newpid == 0:
    os.close(0)
else:
    time.sleep(.25)
    input()
</code>```

The parent process still accepts inputs from stdin despite the fact the child process closes stdin. That's good and here's the code reversed:

```<code>newpid = os.fork()
if newpid == 0:
    input()
else:
    time.sleep(.25)
    os.close(0)
</code>```

Now, it's the opposite, this time the parent process that closes stdin not the child. And this raises EOFError for the input() call in the child process.

This looks like when the [child] process writes/modifies the parent's file descriptors, it does not affect the [parent]. That is, the child process gets newer file descriptions.

Then why call _exit as Python Docs states to prevent invoking cleanup handlers if operations performed by the child process does not affect the parent process? Let's take a look at _EXIT(2) man page:

The function _exit() terminates the calling process "immediately". Any open file descriptors belonging to the process are closed; any children of the process are inherited by process 1, init, and the process's parent is sent a SIGCHLD`  signal.

The function _exit() is like exit(3), but does not call any functions registered with atexit(3) or on_exit(3). Open stdio(3) streams are not flushed. On the other hand, _exit() does close open file descriptors, and this may cause an unknown delay, waiting for pending output to finish.

fork() manual page doesn't mention that the cleanup handlers of the child process are inherited from the parent. How does this affect the parent in any way? In other words, why not just let the child process clean up after itself and why not?

答:
I'm assuming you're running this from a shell within a terminal.

The shell launches the Python process in a new process group and uses tcsetpgrp() to set it as the foreground process group on the TTY.

Once the parent Python process terminates, the shell reclaims control of the terminal (it sets itself as the foreground process group). The shell does not know the forked child from Python is still running.

When a process which is not part of the foreground process group tries to read from the terminal, it normally receives a SIGTTIN signal. However, in this case, the process group has been orphaned because its leader has terminated, thus the child process gets an EIO error from read() on the TTY. Python treats this as EOFError.

Body:
fork(2) manual page on the Linux system I'm running says the following:

The child inherits copies of the parent's set of open file descriptors.  Each file descriptor in the  child  refers  to  the  same  open file description (see open(2)) as the corresponding file descriptor in the parent.  This means that the two  file  descriptors  share  open  file  status flags, file offset, and signal-driven I/O attributes (see the description of F_SETOWN and F_SET‐SIG in fcntl(2)).

And Python Documentation mentions

_exit() should normally only be used in the child process after a fork().

Of course, _exit won't call cleanup handlers, the problem is that, if you look at this code for instance:

newpid = os.fork()
if newpid == 0:
    os.close(0)
else:
    time.sleep(.25)
    input()

The parent process still accepts inputs from stdin despite the fact the child process closes stdin. That's good and here's the code reversed:

newpid = os.fork()
if newpid == 0:
    input()
else:
    time.sleep(.25)
    os.close(0)

Now, it's the opposite, this time the parent process that closes stdin not the child. And this raises EOFError for the input() call in the child process.

This looks like when the [child] process writes/modifies the parent's file descriptors, it does not affect the [parent]. That is, the child process gets newer file descriptions.

Then why call _exit as Python Docs states to prevent invoking cleanup handlers if operations performed by the child process does not affect the parent process? Let's take a look at _EXIT(2) man page:

The function _exit() terminates the calling process "immediately". Any open file descriptors belonging to the process are closed; any children of the process are inherited by process 1, init, and the process's parent is sent a SIGCHLD`  signal.

The function _exit() is like exit(3), but does not call any functions registered with atexit(3) or on_exit(3). Open stdio(3) streams are not flushed. On the other hand, _exit() does close open file descriptors, and this may cause an unknown delay, waiting for pending output to finish.

fork() manual page doesn't mention that the cleanup handlers of the child process are inherited from the parent. How does this affect the parent in any way? In other words, why not just let the child process clean up after itself and why not?


问:
jQuery $(this).nextUntil('h3').toggle(); - hidden ul inside an ul
I'm struggling for two days now on how to toggle specific content for my first project (started coding about a week ago, so I'm a newbie). I have searched other topics and read articles/done tutorials, and they helped me in the right direction, but I'm still not there yet. Who knows how to tackle this?

Goal:
Only the h3s should be visible when the page loads. When I click on h3, I want everything until the next h3 to toggle (thus, the ul and the 'sub' ul).

Current situation: List Items 1 and 2 toggle, but the Sublist items are not (they stay hidden).

```<code><div>
<h3>Heading</h3>
  <ul>
    <li>List item 1</li>
      <ul>
       <li>Sublist item 1</li>
       <li>Sublist item 2</li>
      </ul>
    <li>List item 2</li>
      <ul>
        <li></li>
      </ul>
  </ul>
<h3>Next heading</h3>
...
</div>
</code>```

This is the jQuery code:

```<code> $(document).ready(function() {
   $('h3').click(function() {
     $(this).nextUntil('h3').toggle();
   });
 });
</code>```

And the CSS that hides the ul when the page loads:

```<code>ul {
  display: none;
  visibility: inherit;
}
</code>```

I think the problem is in my CSS (because List Item 2 does load), but after two days I'm still not able to fix it. Who can help me?

答:
Another suggestion :

add a class to the "main"
s (for example : section), not on the sub elements :

```<code><div>
<h3>First Heading</h3>
  <ul class="section">
    <li>List item 1</li>
      <ul>
       <li>Sublist item 1</li>
       <li>Sublist item 2</li>
      </ul>
    <li>List item 2</li>
      <ul>
        <li></li>
      </ul>
  </ul>
<h3>Second heading</h3>
  <ul class="section">
    <li>List item 1</li>
      <ul>
       <li>Sublist item 1</li>
       <li>Sublist item 2</li>
      </ul>
    <li>List item 2</li>
      <ul>
        <li></li>
      </ul>
  </ul>
<h3>Third heading</h3>
...
</div>
</code>```

apply your css hiding rule only on this class :

```<code>ul.section {
    display: none;
}
</code>```

your javascript handler should work :

```<code>$('h3').click(function() {
  $(this).nextUntil('h3').toggle();
});
</code>```

Body:
I'm struggling for two days now on how to toggle specific content for my first project (started coding about a week ago, so I'm a newbie). I have searched other topics and read articles/done tutorials, and they helped me in the right direction, but I'm still not there yet. Who knows how to tackle this?

Goal:
Only the h3s should be visible when the page loads. When I click on h3, I want everything until the next h3 to toggle (thus, the ul and the 'sub' ul).

Current situation: List Items 1 and 2 toggle, but the Sublist items are not (they stay hidden).

Heading

List item 1

Sublist item 1

Sublist item 2

List item 2

Next heading

...

This is the jQuery code:

 $(document).ready(function() {
   $('h3').click(function() {
     $(this).nextUntil('h3').toggle();
   });
 });

And the CSS that hides the ul when the page loads:

ul {
  display: none;
  visibility: inherit;
}

I think the problem is in my CSS (because List Item 2 does load), but after two days I'm still not able to fix it. Who can help me?

Body:
Another suggestion :

add a class to the "main" <ul>s (for example : section), not on the sub elements :

<div>
<h3>First Heading</h3>
  <ul class="section">
    <li>List item 1</li>
      <ul>
       <li>Sublist item 1</li>
       <li>Sublist item 2</li>
      </ul>
    <li>List item 2</li>
      <ul>
        <li></li>
      </ul>
  </ul>
<h3>Second heading</h3>
  <ul class="section">
    <li>List item 1</li>
      <ul>
       <li>Sublist item 1</li>
       <li>Sublist item 2</li>
      </ul>
    <li>List item 2</li>
      <ul>
        <li></li>
      </ul>
  </ul>
<h3>Third heading</h3>
...
</div>

apply your css hiding rule only on this class :

ul.section {
    display: none;
}

your javascript handler should work :

$('h3').click(function() {
  $(this).nextUntil('h3').toggle();
});


问:
How can I fill / populate DropDown with my IEnumerable<Model> value ASP.NET MVC
I tried to set my dropdown list values from my model as it is the value I need to see in the dropdown
But I'm facing an error:

The type arguments for method
  'System.Web.Mvc.Html.SelectExtensions.DropDownListFor(System.Web.Mvc.HtmlHelper,
  System.Linq.Expressions.Expression>,
  System.Collections.Generic.IEnumerable,
  string)' cannot be inferred from the usage. Try specifying the type
  arguments explicitly.

And here is my code:

```<code>@model IEnumerable<Language>
@using Web.Helpers
@{
    ViewBag.Title = "";
}
<div class="">
    <div class="row">
        <div class="col-md-12 col-sm-12 col-xs-12">
            <div class="x_panel">
                <div class="x_title">
                    <h2><i class="fa fa-filter"></i> </h2>
                    <div class="clearfix"></div>
                </div>
                <div class="x_content">
                    <br />
                    @using (Html.BeginForm("Settings","Language", FormMethod.Post, new { @class = "form-horizontal form-label-left" }))
                    {
                        @Html.AntiForgeryToken()
                        @Html.ValidationSummary(true)

                        <div class="col-md-12 col-sm-12">
                            <div class="col-md-12 col-sm-12">
                                @Html.DropDownListFor(WHATTOWRITEHERE, new SelectList(ViewBag.Languagess, "Id", "Name"), new { @class = "form-control" })
                            </div>
                        </div>

                    }

                }
            }
        }
    }
}
</code>```

Controller action:

```<code>public ActionResult Settings()
{
   List<Language> activeL = LanguageController.GetAll();
   ViewBag.Languagess = activeLanguages;

   return View(activeL);
}
</code>```

Maybe I could delete ViewBag.Languagess at all, so I can use  (Model, "Id", "Name") there instad of (ViewBag.Languagess, "Id", "Name")

答:
I thing your model could been an other type like Settings.

```<code>public class SettingsModel
{
    public int LanguageId { get; set; }
}

public class Language
{
    public int Id { get; set; }
    public string Name { get; set; }
}
</code>```

.cshtml

```<code>@model SettingsModel
@using Web.Helpers
@{
    ViewBag.Title = "";
}
<div class="">
    <div class="row">
        <div class="col-md-12 col-sm-12 col-xs-12">
            <div class="x_panel">
                <div class="x_title">
                    <h2><i class="fa fa-filter"></i> </h2>
                    <div class="clearfix"></div>
                </div>
                <div class="x_content">
                    <br />
                    @using (Html.BeginForm("Settings","Language", FormMethod.Post, new { @class = "form-horizontal form-label-left" }))
                    {
                        @Html.AntiForgeryToken()
                        @Html.ValidationSummary(true)

                        <div class="col-md-12 col-sm-12">
                            <div class="col-md-12 col-sm-12">
                                @Html.DropDownListFor(model => model.LanguageId, new SelectList(ViewBag.Languagess, "Id", "Name"), new { @class = "form-control" })
                            </div>
                        </div>

                    }

                }
            }
        }
    }
}
</code>```

controller

```<code>    [HttpGet]
    public ActionResult Language()
    {
        List<Language> activeL = LanguageController.GetAll();
        ViewBag.Languagess = activeLanguages;
        return View();
    }

   [HttpPost]
    public ActionResult Language(SettingsModel settings)
    {
        Language selectedLanguage = LanguageController.GetAll().Where(l => l.Id == settings.LanguageId).SingleOrDefault();
        //...   your post operations.

    }
</code>```

Body:
I tried to set my dropdown list values from my model as it is the value I need to see in the dropdown
But I'm facing an error:

The type arguments for method
  'System.Web.Mvc.Html.SelectExtensions.DropDownListFor(System.Web.Mvc.HtmlHelper,
  System.Linq.Expressions.Expression>,
  System.Collections.Generic.IEnumerable,
  string)' cannot be inferred from the usage. Try specifying the type
  arguments explicitly.

And here is my code:

@model IEnumerable<Language>
@using Web.Helpers
@{
    ViewBag.Title = "";
}

                    @using (Html.BeginForm("Settings","Language", FormMethod.Post, new { @class = "form-horizontal form-label-left" }))
                    {
                        @Html.AntiForgeryToken()
                        @Html.ValidationSummary(true)

                                @Html.DropDownListFor(WHATTOWRITEHERE, new SelectList(ViewBag.Languagess, "Id", "Name"), new { @class = "form-control" })

                    }

                }
            }
        }
    }
}

Controller action:

public ActionResult Settings()
{
   List<Language> activeL = LanguageController.GetAll();
   ViewBag.Languagess = activeLanguages;

   return View(activeL);
}

Maybe I could delete ViewBag.Languagess at all, so I can use  (Model, "Id", "Name") there instad of (ViewBag.Languagess, "Id", "Name")

Body:
I thing your model could been an other type like Settings.

public class SettingsModel
{
    public int LanguageId { get; set; }
}

public class Language
{
    public int Id { get; set; }
    public string Name { get; set; }
}

.cshtml

@model SettingsModel
@using Web.Helpers
@{
    ViewBag.Title = "";
}
<div class="">
    <div class="row">
        <div class="col-md-12 col-sm-12 col-xs-12">
            <div class="x_panel">
                <div class="x_title">
                    <h2><i class="fa fa-filter"></i> </h2>
                    <div class="clearfix"></div>
                </div>
                <div class="x_content">
                    <br />
                    @using (Html.BeginForm("Settings","Language", FormMethod.Post, new { @class = "form-horizontal form-label-left" }))
                    {
                        @Html.AntiForgeryToken()
                        @Html.ValidationSummary(true)

                        <div class="col-md-12 col-sm-12">
                            <div class="col-md-12 col-sm-12">
                                @Html.DropDownListFor(model => model.LanguageId, new SelectList(ViewBag.Languagess, "Id", "Name"), new { @class = "form-control" })
                            </div>
                        </div>

                    }

                }
            }
        }
    }
}

controller

    [HttpGet]
    public ActionResult Language()
    {
        List<Language> activeL = LanguageController.GetAll();
        ViewBag.Languagess = activeLanguages;
        return View();
    }

   [HttpPost]
    public ActionResult Language(SettingsModel settings)
    {
        Language selectedLanguage = LanguageController.GetAll().Where(l => l.Id == settings.LanguageId).SingleOrDefault();
        //...   your post operations.

    }


问:
Can local intranet application (built on php) query mysql database stored in offsite location?
I have a local intranet application which runs off a basic WAMP server in our offices. Every morning, one of our team members manually syncs our internal mysql db with our external mysql db (where our online enrollments occur). If a change is made during the day on the intranet application, it is not reflected on the external db until the following day.

I am wondering if it is possible to (essentially) tunnel to an external mysql connection from say a wamp or xampp server from within our offices and work in 'real-time'.

Anybody had any luck or advice?

答:
Just make your internal application use the database from the external one.  You may need to add permission to the external server to allow connections from your internal server IP, but otherwise this is just like having a webserver and sperate db server that need to access each other.

Can't really tell you how to do this here - it all depends on your specific configuration, something that I would thing is a little complicated (and too specialized) to figure out on SO.


问:
Missising DSYMs files for Fabric Craslytics
I am trouble to get crash report to Fabric Crashytics Dashboard.
After googling so much i found the DSYMs file missing for the fabric.
I have try so may way to upload DSYMs file using the Xcode - Organizer,
Iphone simulator build DSYMs. After successful upload I get same missing DSYMs file.

Please help me to proper way to upload DSYMs file to Fabric.

Thanks,

答:
iPhone simulator build DSYMs won't work as the architecture differs.
Fabric takes some time to process the symbols, please allow sufficient time. </p>

<p>Fabric will tell you which DSYMS are missing, ensure you upload those ones. </p>

Body:
iPhone simulator build DSYMs won't work as the architecture differs.
Fabric takes some time to process the symbols, please allow sufficient time.

Fabric will tell you which DSYMS are missing, ensure you upload those ones.


问:
Adding column between two other columns in SQL server
Can you add a column to a table inserting it in between two existing columns in SQL Server without dropping and re-creating the table?</p>

答:
Yes you can add here is the query for your concern:</p>

```<code>ALTER table table_name ADD column column_name(new) datatype AFTER column_name
</code>```

Body:
Yes you can add here is the query for your concern:

ALTER table table_name ADD column column_name(new) datatype AFTER column_name

ContentLicense: CC BY-SA 4.0


问:
Including Java .jar into RobotFramework
I am new at testing.
I have a jar-file. There are two classes. First class A which has method f(), second has class Main where I have main method and in this method I create the instanse of A and can use method f. I want to write test for this method, but I don't know how to use this method in RobotFramework. I want to make it with command line, without plugins. Can you advice something?
P.S Also I have Test.robot</p>

答:
Yes, I'll try to explain.
As example of my case. I have .jar where in package "my.package" I have class A with public method '

```<code>public String f(String name){
       return ("Hello " + name);
}
</code>```

'
And with robotframework I need to make simple test.
There was question: How to use method in this framework.
1. I need to write in

```<code>*** Settings ***
Library    my.package.A
</code>```

After it the "f" becomes key word and we can use it in
*** Test Cases *** as f      John

We need to write our .jar in class path as
'java -cp C:\.....\test-method.jar'

Execute test.robot file.
P/S
Sorry for my English

Title: Including Java .jar into RobotFramework

Body:
Yes, I'll try to explain.
As example of my case. I have .jar where in package "my.package" I have class A with public method '

public String f(String name){
       return ("Hello " + name);
}

'
And with robotframework I need to make simple test.
There was question: How to use method in this framework.
1. I need to write in

*** Settings ***
Library    my.package.A

After it the "f" becomes key word and we can use it in
*** Test Cases *** as f      John

We need to write our .jar in class path as
'java -cp C:\.....\test-method.jar'

Execute test.robot file.
P/S
Sorry for my English


问:
how to include 2 joins into a union statement
I want to merge plan and actual data into 1 view using Union.
For this I use two inner joins to make the rows match - then I use a union statement. Currently I do this in 3 steps - now I want to merge all this into 1 step.

Example

create vPlan2

```<code>Select
   a.step,
   a.[planned user],
   b.[actual user],
   a.[invoice plan] as 'invoice'
from vPlan a
inner join vActuals b on a.step = b.step
group by
   a.step,
   a.[planned user],
   b.[actual user],
   a.[invoice plan]
</code>```

create vActuals2

```<code>Select
    a.step,
    b.[planned user],
    a.[actual user],
    a.[invoice actuals] as 'invoice'
from vActuals a
inner join vPlan b on a.step = b.step
group by
    a.step,
    a.[actual user],
    b.[planned user],
    a.[invoice actuals]
</code>```

create vplanandactuals

```<code>select
    'Plan' as type,
    a.step,
    a.[planned user],
    a.invoice,
    a.[actual user]
from vPlan2 a
group by
    a.step,
    a.[planned user],
    a.invoice,
    a.[actual user]
Union
select
    'Actuals',
    b.step,
    b.[planned user],
    b.invoice,
    b.[actual user]
from vActuals2 b
group by
    b.step,
    b.[planned user],
    b.invoice,
    b.[actual user]
</code>```

答:
I think what you are looking for is:</p>

```<code>Select
   'Plan' as Type,
   a.step,
   a.[planned user],
   b.[actual user],
   a.[invoice plan] as 'invoice'
from vPlan a
inner join vActuals b on a.step = b.step
group by
   a.step,
   a.[planned user],
   b.[actual user],
   a.[invoice plan]

union all

Select
    'Actuals' as Type,
    a.step,
    b.[planned user],
    a.[actual user],
    a.[invoice actuals] as 'invoice'
from vActuals a
inner join vPlan b on a.step = b.step
group by
    a.step,
    a.[actual user],
    b.[planned user],
    a.[invoice actuals]
</code>```

Body:
I want to merge plan and actual data into 1 view using Union.
For this I use two inner joins to make the rows match - then I use a union statement. Currently I do this in 3 steps - now I want to merge all this into 1 step.

Example

create vPlan2

Select
   a.step,
   a.[planned user],
   b.[actual user],
   a.[invoice plan] as 'invoice'
from vPlan a
inner join vActuals b on a.step = b.step
group by
   a.step,
   a.[planned user],
   b.[actual user],
   a.[invoice plan]

create vActuals2

Select
    a.step,
    b.[planned user],
    a.[actual user],
    a.[invoice actuals] as 'invoice'
from vActuals a
inner join vPlan b on a.step = b.step
group by
    a.step,
    a.[actual user],
    b.[planned user],
    a.[invoice actuals]

create vplanandactuals

select
    'Plan' as type,
    a.step,
    a.[planned user],
    a.invoice,
    a.[actual user]
from vPlan2 a
group by
    a.step,
    a.[planned user],
    a.invoice,
    a.[actual user]
Union
select
    'Actuals',
    b.step,
    b.[planned user],
    b.invoice,
    b.[actual user]
from vActuals2 b
group by
    b.step,
    b.[planned user],
    b.invoice,
    b.[actual user]

Body:
I think what you are looking for is:

Select
   'Plan' as Type,
   a.step,
   a.[planned user],
   b.[actual user],
   a.[invoice plan] as 'invoice'
from vPlan a
inner join vActuals b on a.step = b.step
group by
   a.step,
   a.[planned user],
   b.[actual user],
   a.[invoice plan]

union all

Select
    'Actuals' as Type,
    a.step,
    b.[planned user],
    a.[actual user],
    a.[invoice actuals] as 'invoice'
from vActuals a
inner join vPlan b on a.step = b.step
group by
    a.step,
    a.[actual user],
    b.[planned user],
    a.[invoice actuals]