问:
Problem with max SQL function
I have this code in PHP

```<code>$max="SELECT MAX(num) FROM info";
$maxquery= mysql_query($max) or die (died);
while($row = mysql_fetch_array($maxquery)){
    echo "The max num is ". $row['num']."this is it";
}
$maxnum= mysql_fetch_array($maxquery);
echo "<br>".$maxnum."hh";
</code>```

then the output be:

The max num is this is it

hh

Why didn't the query get the max number?

The table is called info and it has these fields, ID, num, title, description, and answer.

After editing:

I tried my query in MySQL and it works fine!

"SELECT MAX(num) FROM info"

and this is my complete code if it can help:

```<code><?php
    $answer=$_GET["answerbox"];
    $ID=$_GET["TheID"];

    $host="localhost";
    $username="root";
    $password="";
    $db_name="game";
    mysql_connect("$host","$username","$password")or die("cannot connect");
    mysql_select_db("$db_name")or die("cannot select DB");

    $max="SELECT MAX(num) FROM info";
    $maxquery= mysql_query($max) or die (died);
    while($row = mysql_fetch_array($maxquery)) {
        echo "The max num is ". $row['num']."this is it";
    }

    $maxnum= mysql_fetch_array($maxquery);
    $sql="SELECT * FROM info  WHERE ID=".$ID;
    $query = mysql_query($sql) or die(errorquery);
    $row = mysql_fetch_array($query);
    $trueanswer = $row['Answer'];
    $num=$row['num'];
    if ($num<$maxnum)
    {
        $numto= $num +1 ;
        echo "<br>".$maxnum."hh";
    }
?>
</code>```

答: The query is looking fine. Please inspect your code of getting data from the result set step by step.</p>

Title: Problem with max SQL function

Body:
I have this code in PHP

$max="SELECT MAX(num) FROM info";
$maxquery= mysql_query($max) or die (died);
while($row = mysql_fetch_array($maxquery)){
    echo "The max num is ". $row['num']."this is it";
}
$maxnum= mysql_fetch_array($maxquery);
echo "
".$maxnum."hh";

then the output be:

The max num is this is it

hh

Why didn't the query get the max number?

The table is called info and it has these fields, ID, num, title, description, and answer.

After editing:

I tried my query in MySQL and it works fine!

"SELECT MAX(num) FROM info"

and this is my complete code if it can help:

<?php
    $answer=$_GET["answerbox"];
    $ID=$_GET["TheID"];

    $host="localhost";
    $username="root";
    $password="";
    $db_name="game";
    mysql_connect("$host","$username","$password")or die("cannot connect");
    mysql_select_db("$db_name")or die("cannot select DB");

    $max="SELECT MAX(num) FROM info";
    $maxquery= mysql_query($max) or die (died);
    while($row = mysql_fetch_array($maxquery)) {
        echo "The max num is ". $row['num']."this is it";
    }

    $maxnum= mysql_fetch_array($maxquery);
    $sql="SELECT * FROM info  WHERE ID=".$ID;
    $query = mysql_query($sql) or die(errorquery);
    $row = mysql_fetch_array($query);
    $trueanswer = $row['Answer'];
    $num=$row['num'];
    if ($num<$maxnum)
    {
        $numto= $num +1 ;
        echo "
".$maxnum."hh";
    }
?>


来源: stackexchange

问:
an alternative for object_getInstanceVariable
I think to not really understand what is the best way to upgrade the object_getInstanceVariable used in an old project.

In other word, what is the best thing to use instead of the following instruction?

```<code>object_getInstanceVariable(self, [[@"t" stringByAppendingFormat:@"%d", x] UTF8String], (UITextField **)&textField);
</code>```

答:
You can use valueForKey:, e.g.:

```<code>textField = [self valueForKey:[@"t" stringByAppendingFormat:@"%d", x]];
</code>```

Unlike your code this will find both instance variables and properties.

This will also throw an exception if the variable or property does not exist. This can be addressed by overriding valueForUndefinedKey: on the target class (self in your case).

ContentLicense: CC BY-SA 3.0

Body:
I think to not really understand what is the best way to upgrade the object_getInstanceVariable used in an old project.

In other word, what is the best thing to use instead of the following instruction?

object_getInstanceVariable(self, [[@"t" stringByAppendingFormat:@"%d", x] UTF8String], (UITextField **)&textField);

Body:
You can use valueForKey:, e.g.:

textField = [self valueForKey:[@"t" stringByAppendingFormat:@"%d", x]];

Unlike your code this will find both instance variables and properties.

This will also throw an exception if the variable or property does not exist. This can be addressed by overriding valueForUndefinedKey: on the target class (self in your case).


问:
storm stream joins with parallelism
I have two spouts and both are emitting some data

```<code>Spout A tuple-> pid, data1, data2, data3
Spout B tuple -> pid, m1, m2
</code>```

I want join the data from above two spouts in bolt over "pid"

```<code>Spout A
   |------------------> joinBolt ----> pid, data1, data2, data3, m1, m2
Spout B
</code>```

JoinBolt will combine the data over "pid" and will emit tuple (pid, data1, data2, data3, m1, m2)

```<code>JoinBolt joinBolt = new JoinBolt()
BoltDeclarer bd = builder.setBolt("joinBoltId", joinBolt, 5);
bd.fieldsGrouping("spout1Id" "stream1",  new Fields("pid"));
bd.fieldsGrouping("spout2Id", "stream2", new Fields("pid"));
</code>```

If I have parallelism of 5 in JoinBolt, can I be sure that data from both spouts having same pid will land up on same instance of joinBolt.

In this case, since I have parallelism of 5, I will be having 5 instance of joinBolt (say b1, b2, b3, b4, b5). Now is it possible that pid1 from spout1 and pid1 from spout2 can go to different instance of joinBolt even if I have set fieldsGrouping on pid?

答:
If you are using fieldsGrouping on pid, for same values pid it will go to the same instance of JoinBolt.
FYI, Storm added JoinBolt functionality https://github.com/apache/storm/blob/master/storm-core/src/jvm/org/apache/storm/bolt/JoinBolt.java based on windowing.</p>

Title: storm stream joins with parallelism

Body:
I have two spouts and both are emitting some data

Spout A tuple-> pid, data1, data2, data3
Spout B tuple -> pid, m1, m2

I want join the data from above two spouts in bolt over "pid"

Spout A
   |------------------> joinBolt ----> pid, data1, data2, data3, m1, m2
Spout B

JoinBolt will combine the data over "pid" and will emit tuple (pid, data1, data2, data3, m1, m2)

JoinBolt joinBolt = new JoinBolt()
BoltDeclarer bd = builder.setBolt("joinBoltId", joinBolt, 5);
bd.fieldsGrouping("spout1Id" "stream1",  new Fields("pid"));
bd.fieldsGrouping("spout2Id", "stream2", new Fields("pid"));

If I have parallelism of 5 in JoinBolt, can I be sure that data from both spouts having same pid will land up on same instance of joinBolt.

In this case, since I have parallelism of 5, I will be having 5 instance of joinBolt (say b1, b2, b3, b4, b5). Now is it possible that pid1 from spout1 and pid1 from spout2 can go to different instance of joinBolt even if I have set fieldsGrouping on pid?


问:
How to use an Environment variable in an Azure Resource Management Template
I have searched and read the documentation of Resource Management Template, but i couldn't find any information over Environment variables. I tried to define 2 environment variables in a variable object, but it didn't work.

```<code>variables": {
    "mailPass": "TYUl5491",
    "SlackToken": "hrtu-12546233785-55454578422-56454412348-87845155121ht5621552521er55547123"
  }
</code>```

Is there any way to define environment variables in an Azure Resource Management Template and then use it for the web app or api app?

答:
Yes, for a WebApp you can do that, here's the snippet of a full WebApp resource, replace values and names with something you need:</p>

```<code>{
    "apiVersion": "2015-08-01",
    "name": "[parameters('siteName')]",
    "type": "Microsoft.Web/sites",
    "location": "[parameters('location')]",
    "properties": {
        "serverFarmId": "[parameters('hostingPlanName')]",
        "siteConfig": {
            "appSettings": [
                {
                    "name": "storageKey", # REPLACE ME
                    "value": "[listKeys(variables('storageid'),'2015-06-15').key1]" # REPLACE ME
                },
                {
                    "name": "storageAccount", # REPLACE ME
                    "value": "[parameters('storageAccountName')]" # REPLACE ME
                }
            ]
        }
    }
}
</code>```

Body:
I have searched and read the documentation of Resource Management Template, but i couldn't find any information over Environment variables. I tried to define 2 environment variables in a variable object, but it didn't work.

variables": {
    "mailPass": "TYUl5491",
    "SlackToken": "hrtu-12546233785-55454578422-56454412348-87845155121ht5621552521er55547123"
  }

Is there any way to define environment variables in an Azure Resource Management Template and then use it for the web app or api app?

Body:
Yes, for a WebApp you can do that, here's the snippet of a full WebApp resource, replace values and names with something you need:

{
    "apiVersion": "2015-08-01",
    "name": "[parameters('siteName')]",
    "type": "Microsoft.Web/sites",
    "location": "[parameters('location')]",
    "properties": {
        "serverFarmId": "[parameters('hostingPlanName')]",
        "siteConfig": {
            "appSettings": [
                {
                    "name": "storageKey", # REPLACE ME
                    "value": "[listKeys(variables('storageid'),'2015-06-15').key1]" # REPLACE ME
                },
                {
                    "name": "storageAccount", # REPLACE ME
                    "value": "[parameters('storageAccountName')]" # REPLACE ME
                }
            ]
        }
    }
}


问:
Is it possible to store a Type in a map and use it later to instantiate an object in Go lang?
I am new to Go and I have this problem. I need to make a kind of "dispatcher" that will receive a string and return a type to be instantiated based on the string. For example:

```<code>AnimalType := mymap["animal"]
newAnimal := new(AnimalType)
</code>```

Is there a way to do so?

Thanks in advance.

答:
You can do this with the reflect package, though it should be noted that eventually you have to know the concrete type to really do much with it.

EDIT: LET IT BE KNOWN. This is a very BAD idea in the first place, and if you are doing this, you should probably rethink things. Go is a statically typed language, and unless you REALLY need to use the reflect package, you should stay away from it if possible. Even then, in most cases, this has already been done for you. Take, for instance, the JSON Marshal/Unmarshaller. At its core, they do some nasty reflection stuff, but it is already taken care of for you, just use it.

It is important to note that the type assertions (the .(*Thing1) lines) will panic if it isn't the right type. See https://tour.golang.org/methods/15

Test on playground: https://play.golang.org/p/DhiTnCVJi1

```<code>package main

import (
    "fmt"
    "reflect"
)

type Thing1 bool

type Thing2 int

type Thing3 struct {
    Item string
}

func main() {
    m := map[string]reflect.Type{}
    var t1 Thing1
    var t2 Thing2
    var t3 Thing3
    m["thing1"] = reflect.TypeOf(t1)
    m["thing2"] = reflect.TypeOf(t2)
    m["thing3"] = reflect.TypeOf(t3)

    // later on

    // thing1
    newT1Value := reflect.New(m["thing1"])
    // you use * here because a pointer to a boolean type isn't useful
    newT1 := *newT1Value.Interface().(*Thing1) // cast to concrete type

    fmt.Printf("T1: %v\n", newT1)

    // thing2
    newT2Value := reflect.New(m["thing2"])
    // you use * here because a pointer to an int type isn't useful
    newT2 := *newT2Value.Interface().(*Thing2)

    fmt.Printf("T2: %v\n", newT2)

    // thing3
    newT3Value := reflect.New(m["thing3"])
    // you can choose to use * or not here. Pointers to structs are actually useful
    newT3 := newT3Value.Interface().(*Thing3)
    newT3.Item = "Hello world"

    fmt.Printf("T3: %#v\n", newT3)
}
</code>```

Body:
I am new to Go and I have this problem. I need to make a kind of "dispatcher" that will receive a string and return a type to be instantiated based on the string. For example:

AnimalType := mymap["animal"]
newAnimal := new(AnimalType)

Is there a way to do so?

Thanks in advance.

Body:
You can do this with the reflect package, though it should be noted that eventually you have to know the concrete type to really do much with it.

EDIT: LET IT BE KNOWN. This is a very BAD idea in the first place, and if you are doing this, you should probably rethink things. Go is a statically typed language, and unless you REALLY need to use the reflect package, you should stay away from it if possible. Even then, in most cases, this has already been done for you. Take, for instance, the JSON Marshal/Unmarshaller. At its core, they do some nasty reflection stuff, but it is already taken care of for you, just use it.

It is important to note that the type assertions (the .(*Thing1) lines) will panic if it isn't the right type. See https://tour.golang.org/methods/15

Test on playground: https://play.golang.org/p/DhiTnCVJi1

package main

import (
    "fmt"
    "reflect"
)

type Thing1 bool

type Thing2 int

type Thing3 struct {
    Item string
}

func main() {
    m := map[string]reflect.Type{}
    var t1 Thing1
    var t2 Thing2
    var t3 Thing3
    m["thing1"] = reflect.TypeOf(t1)
    m["thing2"] = reflect.TypeOf(t2)
    m["thing3"] = reflect.TypeOf(t3)

    // later on

    // thing1
    newT1Value := reflect.New(m["thing1"])
    // you use * here because a pointer to a boolean type isn't useful
    newT1 := *newT1Value.Interface().(*Thing1) // cast to concrete type

    fmt.Printf("T1: %v\n", newT1)

    // thing2
    newT2Value := reflect.New(m["thing2"])
    // you use * here because a pointer to an int type isn't useful
    newT2 := *newT2Value.Interface().(*Thing2)

    fmt.Printf("T2: %v\n", newT2)

    // thing3
    newT3Value := reflect.New(m["thing3"])
    // you can choose to use * or not here. Pointers to structs are actually useful
    newT3 := newT3Value.Interface().(*Thing3)
    newT3.Item = "Hello world"

    fmt.Printf("T3: %#v\n", newT3)
}


问:
PrimeFaces Datatable CellEditor - Different values for facet input and output
I have an editable DataTable for the entity User. This table has a field called username which has an unique constraint

```<code>    <h:form id="form">
<p:dataTable id="userTable" value="#{users}" var="entity" editable="true" editMode="cell" tableStyle="width:auto">
<p:ajax event="cellEdit" listener="#{userController.onCellEdit}" update="form:msgs form:display form:userTable" />
<p:column headerText="UserID">
<p:outputLabel value="#{entity.id}" />
</p:column>
<p:column headerText="Username">
<p:cellEditor>
<f:facet name="output"><p:outputLabel for="username" value="#{entity.username}" /></f:facet>
<f:facet name="input">
<p:inputText id="username" value="#{entity.username}" >
<f:validateRequired />
<f:validateLength maximum="50" />
</p:inputText>
</f:facet>
</p:cellEditor>
</p:column>
</p:dataTable>
</h:form>
</code>```

In the backing bean userController, I have the following method onCellEdit

```<code>public void onCellEdit(CellEditEvent event) {
        Object newValue = event.getNewValue();
        String columnName = event.getColumn().getHeaderText();
        facesContext = FacesContext.getCurrentInstance();
        User entity = facesContext.getApplication().evaluateExpressionGet(facesContext, "#{entity}", User.class);
        if(columnName.equals("Username") {
            entity.setUsername((String) newValue);
        }

        try {
            service.createOrUpdateEntity(entity);
        }
        catch (EJBTransactionRolledbackException ex) {
            Throwable t = ex.getCause();
            while (t != null) {
                t = t.getCause();
                if(t.getClass().getSimpleName().equals("SQLIntegrityConstraintViolationException")) {
                        entity.setUsername((String) event.getOldValue());
                    facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Duplicate entry for the field username. Write a different username", ""));
                    break;
                }
            }
            return;
        }
        catch (Exception e) {
            e.printStackTrace();
        }
</code>```

The problem is that when the exception is catched the final value for the facet input is different from the value from the facet output. In this case the facet output shows the right value while the facet input shows the value that produced the exception.

答:
You need to ensure that the UIInput component has been reset to original values. The UIInput component can be retrieved from the CellEditEvent.

```<code>((UIInput)event.getComponent()).resetValue();
</code>```

The above assumes that you've checked the return from getComponent() for null and type safety. Here's the API for UIInput

Body:
I have an editable DataTable for the entity User. This table has a field called username which has an unique constraint

    <h:form id="form">

<f:facet name="output">
</f:facet>
<f:facet name="input">

<f:validateRequired />
<f:validateLength maximum="50" />

</f:facet>

</h:form>

In the backing bean userController, I have the following method onCellEdit

public void onCellEdit(CellEditEvent event) {
        Object newValue = event.getNewValue();
        String columnName = event.getColumn().getHeaderText();
        facesContext = FacesContext.getCurrentInstance();
        User entity = facesContext.getApplication().evaluateExpressionGet(facesContext, "#{entity}", User.class);
        if(columnName.equals("Username") {
            entity.setUsername((String) newValue);
        }

        try {
            service.createOrUpdateEntity(entity);
        }
        catch (EJBTransactionRolledbackException ex) {
            Throwable t = ex.getCause();
            while (t != null) {
                t = t.getCause();
                if(t.getClass().getSimpleName().equals("SQLIntegrityConstraintViolationException")) {
                        entity.setUsername((String) event.getOldValue());
                    facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Duplicate entry for the field username. Write a different username", ""));
                    break;
                }
            }
            return;
        }
        catch (Exception e) {
            e.printStackTrace();
        }

The problem is that when the exception is catched the final value for the facet input is different from the value from the facet output. In this case the facet output shows the right value while the facet input shows the value that produced the exception.

Body:
You need to ensure that the UIInput component has been reset to original values. The UIInput component can be retrieved from the CellEditEvent.

((UIInput)event.getComponent()).resetValue();

The above assumes that you've checked the return from getComponent() for null and type safety. Here's the API for UIInput


问:
win32 resource file help
on this website, under the "Edit Control" title, there are a couple of lines of code like this..

```<code>case WM_CREATE:
    hwndEdit = CreateWindow(TEXT("Edit"), NULL, WS_CHILD | WS_VISIBLE | WS_BORDER,
                50, 50, 150, 20, hwnd, (HMENU) ID_EDIT,
                NULL, NULL);

    hwndButton = CreateWindow(
        TEXT("button"), TEXT("Set Title"),
        WS_VISIBLE | WS_CHILD,
        50, 100, 80, 25,
        hwnd, (HMENU) ID_BUTTON, NULL, NULL);

    break;
</code>```

I know that this method of creating buttons and such are done on the fly, But I was wondering how you would do it without doing it like this, instead using a resource file?.
In the Forgers Win32 tutorial it shows how to make a menu using a resource file, and how to describe a dialog box etc, But I cant seem to put any controls on the main(parent) window using a resource file??.

for example I have the following .rc file

```<code>#include "resource.h"
ID_MENU MENU
BEGIN
    POPUP "&File"
    BEGIN
        MENUITEM "E&xit", ID_FILE_EXIT
    END
    POPUP "&About"
    BEGIN
        MENUITEM "&Information", ID_ABOUT_INFO
    END
END

ID_ABOUT_INFO DIALOG DISCARDABLE  0,0,250,250
CAPTION "Information"
BEGIN
    CTEXT "some text",ID_BLA,15,15,144,33
END

//this is all fine but how do I decribe the main window?, instead of the menu and dialog boxes?.
</code>```

How do I describe the main window instead of creating things on the fly?. Is there some kind of keyword?

答:
You can create a dialog as your main window.

If you are using MFC in Visual Studio, use the project wizard to create a Dialog-Based app.

(File -> New Project -> Visual C++ / MFC -> MFC Application -> OK -> Application Type -> Dialog based.)

The generated application will then create your main dialog for you, and exit when it closes.

A simple example of such a beast, including source, is here:

http://www.pretentiousname.com/ICFRanger/index.html

If you are using straight Win32, you'd create the dialog using CreateDialogParam (or similar) and then show it like any other window, and run a message loop. (Or you could use DoModal, which runs its own message loop, but beware that modal dialogs need to behave slightly differently, especially when it comes to closing.)

A simple example of that, including source, is here:

http://www.pretentiousname.com/setpoint_aon/index.html

(Those are both programs I wrote, but very simple ones, so there's not much to get in the way of understanding what they do.)

ContentLicense: CC BY-SA 2.5

Title: win32 resource file help

Body:
on this website, under the "Edit Control" title, there are a couple of lines of code like this..

case WM_CREATE:
    hwndEdit = CreateWindow(TEXT("Edit"), NULL, WS_CHILD | WS_VISIBLE | WS_BORDER,
                50, 50, 150, 20, hwnd, (HMENU) ID_EDIT,
                NULL, NULL);

    hwndButton = CreateWindow(
        TEXT("button"), TEXT("Set Title"),
        WS_VISIBLE | WS_CHILD,
        50, 100, 80, 25,
        hwnd, (HMENU) ID_BUTTON, NULL, NULL);

    break;

I know that this method of creating buttons and such are done on the fly, But I was wondering how you would do it without doing it like this, instead using a resource file?.
In the Forgers Win32 tutorial it shows how to make a menu using a resource file, and how to describe a dialog box etc, But I cant seem to put any controls on the main(parent) window using a resource file??.

for example I have the following .rc file

#include "resource.h"
ID_MENU MENU
BEGIN
    POPUP "&File"
    BEGIN
        MENUITEM "E&xit", ID_FILE_EXIT
    END
    POPUP "&About"
    BEGIN
        MENUITEM "&Information", ID_ABOUT_INFO
    END
END

ID_ABOUT_INFO DIALOG DISCARDABLE  0,0,250,250
CAPTION "Information"
BEGIN
    CTEXT "some text",ID_BLA,15,15,144,33
END

//this is all fine but how do I decribe the main window?, instead of the menu and dialog boxes?.

How do I describe the main window instead of creating things on the fly?. Is there some kind of keyword?


问:
Why my service is still working when app is closed and screen is locked
Always when I was creating service that was supposed to for example listen to changes on server I've been always using AlarmManager and WakefulBroadcastReceiver to poll server every now and then because when I tried to do in with infinite loop inside Service it would stop once screen was locked.
But recently In my Service I was checking location with LocationListener. I wasn't using AlarmManager for this because location was supposed to be checked only once but I've forgotten to remove the listener after use and noticed it is still working even when I close the app and lock the screen. Could somebody explain to me why is that? I thought that Service should stop when screen is locked

答:
Set START_NOT_STICKY in service class.</p>

```<code>@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(TAG, "onStartCommand() called with: intent = [" + intent + "],

    return START_NOT_STICKY;
}
</code>```

Body:
Set START_NOT_STICKY in service class.

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(TAG, "onStartCommand() called with: intent = [" + intent + "],

    return START_NOT_STICKY;
}


问:
Inputting a list of duplicated values into the value for a dictionary with a certain key
I need to create a dictionarydict where each item has a key keytaken from a list keylist and a value valuelist that contains a word from list wordlist repeated n number of times.

I already have a way to get keylist,wordlist,and n.

I already have a dictionary in the form:
(key,word):n

If the inputs were

key= "A"

word = "OK"

n = 3

Therefore, the form of the dictionary result that I want is:

{(key):[word*n(each n instance of word is a separate list entry)]}

The resultant dictionary dict from my example that I want would be:

{("A"):["OK","OK","OK"]}

答:
You can use a dictionary comprehension:

```<code>dic = {('A', 'OK'): 3, ('B', 'NOT OK'): 2}
out = {key: [word]*n for ((key, word), n) in dic.iteritems()}
# {'A': ['OK', 'OK', 'OK'], 'B': ['NOT OK', 'NOT OK']}
</code>```

where dic is your dictionary with (key, word): n.

If you want to keep the same tuple as a key, you can do:

```<code>out = {(key, word): [word]*n for ((key, word), n) in dic.iteritems()}
# {('A', 'OK'): ['OK', 'OK', 'OK'], ('B', 'NOT OK'): ['NOT OK', 'NOT OK']}
</code>```

Body:
You can use a dictionary comprehension:

dic = {('A', 'OK'): 3, ('B', 'NOT OK'): 2}
out = {key: [word]*n for ((key, word), n) in dic.iteritems()}
# {'A': ['OK', 'OK', 'OK'], 'B': ['NOT OK', 'NOT OK']}

where dic is your dictionary with (key, word): n.

If you want to keep the same tuple as a key, you can do:

out = {(key, word): [word]*n for ((key, word), n) in dic.iteritems()}
# {('A', 'OK'): ['OK', 'OK', 'OK'], ('B', 'NOT OK'): ['NOT OK', 'NOT OK']}


问:
NumberFormatException error on returning largest number?
I'm practicing Java online and one of the practice problems is to:

"Write a method called largerAbsVal that takes two integers as parameters and returns the larger of the two absolute values. A call of largerAbsVal(11, 2) would return 11, and a call of largerAbsVal(4, -5) would return 5."

I have already wrote my method solution which so far is:

```<code>public static int largerAbsVal(int a, int b) {
    return Math.max(Math.abs(a), Math.abs(b));
}
</code>```

But for some reason, the website keeps telling me that my code caused an error of type NumberFormatException? I already declared the two parameters as integers at the heading so what exactly is wrong with my code in this case?

Any help is greatly appreciated!

答:
From NumberFormatExecpton:

Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.

The code you posted works great!  My guess is your error is somewhere before that piece of code where you're converting a string to an int. Example:

```<code>Integer.parseInt(string)
</code>```

And that the string given is malformed (i.e. not an int).  For example, something like "2.1" will throw an error like this.

Hope this helps!

Body:
I'm practicing Java online and one of the practice problems is to:

"Write a method called largerAbsVal that takes two integers as parameters and returns the larger of the two absolute values. A call of largerAbsVal(11, 2) would return 11, and a call of largerAbsVal(4, -5) would return 5."

I have already wrote my method solution which so far is:

public static int largerAbsVal(int a, int b) {
    return Math.max(Math.abs(a), Math.abs(b));
}

But for some reason, the website keeps telling me that my code caused an error of type NumberFormatException? I already declared the two parameters as integers at the heading so what exactly is wrong with my code in this case?

Any help is greatly appreciated!

Body:
From NumberFormatExecpton:

Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.

The code you posted works great!  My guess is your error is somewhere before that piece of code where you're converting a string to an int. Example:

Integer.parseInt(string)

And that the string given is malformed (i.e. not an int).  For example, something like "2.1" will throw an error like this.

Hope this helps!


问:
Create MEF part with Constructor parameters
I have a class that export

```<code>[Export(typeof(IService))]
</code>```

this class has a constructor that accept

```<code>Dictionary<string, object>
public MyService(Dictionary<string, object> model){}
</code>```

this is how I create parts

```<code>var catalog = new AggregateCatalog();
catalog.Catalogs.Add("c:\\[SomePath]"));
Container = new CompositionContainer(catalog);
Container.ComposeParts(this);
return Container.GetExportedValue<IService>();
</code>```

How do I go about injecting my paramter into my constructor when the part is exported ?

答:
```<code>Container.ComposeExportedValue(model);
</code>```

Assuming model is the Dictionary<string, object> that you want to inject.

Then you need to decorate the constructor for MyService with:

```<code>[ImportingConstructor]
public MyService(Dictionary<string, object> model){}
</code>```

Body:
I have a class that export

[Export(typeof(IService))]

this class has a constructor that accept

Dictionary<string, object>
public MyService(Dictionary<string, object> model){}

this is how I create parts

var catalog = new AggregateCatalog();
catalog.Catalogs.Add("c:\\[SomePath]"));
Container = new CompositionContainer(catalog);
Container.ComposeParts(this);
return Container.GetExportedValue<IService>();

How do I go about injecting my paramter into my constructor when the part is exported ?

Body:
Container.ComposeExportedValue(model);

Assuming model is the Dictionary<string, object> that you want to inject.

Then you need to decorate the constructor for MyService with:

[ImportingConstructor]
public MyService(Dictionary<string, object> model){}


问:
MS ACcess to SQL Server Where Clause conversion
I have a where clause in an OLD msaccess query which I am converting to SQL Server.  Just trying to get some input on this.

The where clause in this Access Query is not valid for SQL Server.

Here is the Access Where statement...

```<code>WHERE (((MyTable.MYField) <> IsNull([MYField])))
</code>```

Does anyone have a good replacement for this...  MyTable.MYField is an integer value and Isnull in MS Access returns a boolean true or false value but this syntax is incorrect for SQL Server and I have tried a few permutations of this to no avail.  Sorry can't provide data or real field names....

I understand about linking the tables and what not but with millions of rows that is not a good solution...

Any Takers on this?

答:
If I'm understanding the intent of your original query correctly as you're trying to filter out records where MyField has a NULL value, you need to use the IS NOT NULL construct.

WHERE MyTable.MyField IS NOT NULL

Body:
I have a where clause in an OLD msaccess query which I am converting to SQL Server.  Just trying to get some input on this.

The where clause in this Access Query is not valid for SQL Server.

Here is the Access Where statement...

WHERE (((MyTable.MYField) <> IsNull([MYField])))

Does anyone have a good replacement for this...  MyTable.MYField is an integer value and Isnull in MS Access returns a boolean true or false value but this syntax is incorrect for SQL Server and I have tried a few permutations of this to no avail.  Sorry can't provide data or real field names....

I understand about linking the tables and what not but with millions of rows that is not a good solution...

Any Takers on this?


问:
JavaScript non selectable text not working in Chrome/Internet Explorer
In Firefox seems fine, Chrome and Internet Explorer the text is still selectable, is there any way around this? The code was taken from another question, (which I can't find right now) so it may be out of date?

```<code>// Prevent selection
function disableSelection(target) {
    if (typeof target.onselectstart != "undefined") // Internet Explorer route
        target.onselectstart = function() { return false }
    else if (typeof target.style.MozUserSelect != "undefined") // Firefox route
        target.style.MozUserSelect = "none"
    else // All other routes (for example, Opera)
        target.onmousedown = function() { return false }
}
</code>```

Used in code as:

```<code>disableSelection(document.getElementById("gBar"));
</code>```

答:
For webkit use khtmlUserSelect instead of MozUserSelect .

In opera and MSIE you may set the unselectable-property to "On"

As the both styles related to gecko/webkit are CSS, you can use a class to apply it:

```<code><script type="text/javascript">
<!--
function disableSelection(target)
{
  target.className='unselectable';
  target.setAttribute('unselectable','on');
}
//-->
</script>
<style type="text/css">
<!--
.unselectable{
-moz-user-select:none;
-khtml-user-select: none;
}
-->
</style>
</code>```

Note: unselectable will not  pass on child-elements, so if you have there anything else than textNodes inside target, you need the workaround you already have there for MSIE/opera.

ContentLicense: CC BY-SA 4.0

Body:
In Firefox seems fine, Chrome and Internet Explorer the text is still selectable, is there any way around this? The code was taken from another question, (which I can't find right now) so it may be out of date?

// Prevent selection
function disableSelection(target) {
    if (typeof target.onselectstart != "undefined") // Internet Explorer route
        target.onselectstart = function() { return false }
    else if (typeof target.style.MozUserSelect != "undefined") // Firefox route
        target.style.MozUserSelect = "none"
    else // All other routes (for example, Opera)
        target.onmousedown = function() { return false }
}

Used in code as:

disableSelection(document.getElementById("gBar"));

Body:
For webkit use khtmlUserSelect instead of MozUserSelect .

In opera and MSIE you may set the unselectable-property to "On"

As the both styles related to gecko/webkit are CSS, you can use a class to apply it:

<script type="text/javascript">
<!--
function disableSelection(target)
{
  target.className='unselectable';
  target.setAttribute('unselectable','on');
}
//-->
</script>
<style type="text/css">
<!--
.unselectable{
-moz-user-select:none;
-khtml-user-select: none;
}
-->
</style>

Note: unselectable will not  pass on child-elements, so if you have there anything else than textNodes inside target, you need the workaround you already have there for MSIE/opera.


问:
Using JQuery to hide and show text
I want to use JQuery to hide text when web page is launched and when you click on an item it will show the hidden text.

When I load the page it shows the text in h2 and the text in h3 and hides the text in ptdeats as expected. When I click on the text containing "Jason O'Reilly", it doesn't show the text "Hi there, my name is Jay......".

The classes trainers ptpics, pt, center are configured in css.

The jquery is also configured to highlight h3 and also when h3 is click it shows the text and when you click on h3 it hides it again.

This is what I have configured in html:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <link href="style.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="trainersptjavascript.js"></script>
</head>
<body>
    <div class="trainers">
            <h2 class="center">Choose your Personal Trainer</h2>
            <div class="ptpics center">
                <h3 class="pt center">Jason O'Reilly</h3>
                <p class="center"><img src="images/ptjay.jpg" alt="Westside Fitness PT Jason" width="320" height="350"></p>
                <p class="ptdeats">Hi there , my name is Jay I am a personal trainer.</p>
            </div>
            <div class="ptpics center">
                <h3 class="pt center">Jean Meehan</h3>
                <p class="center"><img src="images/ptjean.jpg" alt="Westside Fitness PT Jean" width="320" height="350"></p>
                <p class="ptdeats">I am a qualified Level 4 Personal Trainer.</p>
            </div>
            <div class="ptpics center">
                <h3 class="pt center">Aoife McIntyre</h3>
                <p class="center"><img src="images/ptaoife.jpg" alt="Westside Fitness PT Aoifendrew" width="320" height="350"></p>
                <p class="ptdeats">I am Registered Nurse with a Personal Training Qualification.</p>
            </div>
    </div>
</body>
</html>
</code>```

This is the css configuration

```<code>.trainers
    {
    width: 80%;
    background-color: #36454F;
    color: #FFFFFF;
    text-align: justify;
    height: auto;
    margin-left: 10%;
    margin-left: 10%;
    padding-left: 6px;
    padding-right: 6px;
    float: left;
    }

.pt
    {
    width: 100%;
    cursor: pointer;
    color: #FFFFFF;
    padding-left: 6px;
    padding-right: 6px;
    float: left;
    }

.ptpics
    {
    width: 33%;
    background-color: #36454F;
    color: #FFFFFF;
    border: 1px;
    border-color:#009900;
    text-align: justify;
    height: auto;
    float: left;
    padding-left: 6px;
    padding-right: 6px;
    }
</code>```

JQuery configuration:

```<code>$(document).ready(function()
{
$(".me").hide();
$(".pt").click(function(){
$(".me").show();
});
});
</code>```

答:
Your code should work. I tested it out, and it did work.

Make sure you close the html tabs:

```<code><div class="ptpic center">
<h3 class="pt center">My Name</h3>
<p class="center"><img src="images/me.jpg" alt="Me" width="320" height="350"></p>
<p class="me">Hi there</p>
</code>```

Make sure you click on the actual text that says "My Name" because if you just click close to it, it might not exactly work. A good way to test it out is to put a background color on the target object (here it's either h3 or .pt) via CSS. Then, clicking anywhere inside that box should be okay!

If you instead wanted the text to toggle hide and show, then do this into your javascript:

```<code>$(document).ready(function(){
    $(".me").hide();
    $(".pt").click(function(){
        $(".me").toggle();
    });
});
</code>```

This will alternate between show and hide every time you chick on the .pt block.

Hope this helps!

Title: Using JQuery to hide and show text

Body:
I want to use JQuery to hide text when web page is launched and when you click on an item it will show the hidden text.

When I load the page it shows the text in h2 and the text in h3 and hides the text in ptdeats as expected. When I click on the text containing "Jason O'Reilly", it doesn't show the text "Hi there, my name is Jay......".

The classes trainers ptpics, pt, center are configured in css.

The jquery is also configured to highlight h3 and also when h3 is click it shows the text and when you click on h3 it hides it again.

This is what I have configured in html:

<!DOCTYPE html>

    <link href="style.css" rel="stylesheet">

Choose your Personal Trainer

Jason O'Reilly

Hi there , my name is Jay I am a personal trainer.

Jean Meehan

I am a qualified Level 4 Personal Trainer.

Aoife McIntyre

I am Registered Nurse with a Personal Training Qualification.

This is the css configuration

.trainers
    {
    width: 80%;
    background-color: #36454F;
    color: #FFFFFF;
    text-align: justify;
    height: auto;
    margin-left: 10%;
    margin-left: 10%;
    padding-left: 6px;
    padding-right: 6px;
    float: left;
    }

.pt
    {
    width: 100%;
    cursor: pointer;
    color: #FFFFFF;
    padding-left: 6px;
    padding-right: 6px;
    float: left;
    }

.ptpics
    {
    width: 33%;
    background-color: #36454F;
    color: #FFFFFF;
    border: 1px;
    border-color:#009900;
    text-align: justify;
    height: auto;
    float: left;
    padding-left: 6px;
    padding-right: 6px;
    }

JQuery configuration:

$(document).ready(function()
{
$(".me").hide();
$(".pt").click(function(){
$(".me").show();
});
});

Body:
Your code should work. I tested it out, and it did work.

Make sure you close the html tabs:

<div class="ptpic center">
<h3 class="pt center">My Name</h3>
<p class="center"><img src="images/me.jpg" alt="Me" width="320" height="350"></p>
<p class="me">Hi there</p>

Make sure you click on the actual text that says "My Name" because if you just click close to it, it might not exactly work. A good way to test it out is to put a background color on the target object (here it's either h3 or .pt) via CSS. Then, clicking anywhere inside that box should be okay!

If you instead wanted the text to toggle hide and show, then do this into your javascript:

$(document).ready(function(){
    $(".me").hide();
    $(".pt").click(function(){
        $(".me").toggle();
    });
});

This will alternate between show and hide every time you chick on the .pt block.

Hope this helps!


问:
New react-native project can't run-ios: The following build commands failed: CompileC
I am just trying to spin up a new react-native app but no luck.

react-native init NewApp
cd NewApp
npm install
react-native run-ios

Then see the below error:

```<code>** BUILD FAILED **

The following build commands failed:
    CompileC /Users/arc/Desktop/websites-dev/react-native/testing_rn/ios/build/Build/Intermediates/React.build/Debug-iphonesimulator/React.build/Objects-normal/x86_64/RCTProfile.o Profiler/RCTProfile.m normal x86_64 objective-c com.apple.compilers.llvm.clang.1_0.compiler

(1 failure)

Installing build/Build/Products/Debug-iphonesimulator/testing_rn.app
An error was encountered processing the command (domain=NSPOSIXErrorDomain, code=2):
Failed to install the requested application
An application bundle was not found at the provided path.
Provide a valid path to the desired application bundle.
Print: Entry, ":CFBundleIdentifier", Does Not Exist

Command failed: /usr/libexec/PlistBuddy -c Print:CFBundleIdentifier build/Build/Products/Debug-iphonesimulator/testing_rn.app/Info.plist
Print: Entry, ":CFBundleIdentifier", Does Not Exist
</code>```

Using:

```<code>npm 4.1.2
node v7.5.0
El Capitan 10.11.6
Xcode 8.2
</code>```

package.json:

```<code>{
    "name": "testing_rn",
    "version": "0.0.1",
    "private": true,
    "scripts": {
        "start": "node node_modules/react-native/local-cli/cli.js start",
        "test": "jest"
    },
    "dependencies": {
        "react": "15.4.2",
        "react-native": "0.42.3"
    },
    "devDependencies": {
        "babel-jest": "19.0.0",
        "babel-preset-react-native": "1.9.1",
        "jest": "19.0.2",
        "react-test-renderer": "15.4.2"
    },
    "jest": {
        "preset": "react-native"
    }
}
</code>```

It seems like this may be related to the build via terminal but app may still work in xcode?

Print: Entry, ":CFBundleIdentifier", Does Not Exist have tried most solutions

github issue from 25 days ago:

https://github.com/facebook/react-native/issues/12737

Some related questions:

https://github.com/facebook/react-native/issues/7308

React-native run-ios commands fails

=========================================================

UPDATE:

For me, this seemed to have something to do with 0.42.0 and above. I can run a 0.41.2 project that I install with

```<code>react-native init --version 0.41.2 example412
cd example412
npm install
react-native run-ios
</code>```

And boom. It works. But this gets errors:

```<code>react-native init example_latest
cd example_latest
npm install
react-native run-ios
</code>```

then above errors are back. Same errors with init version at 0.42.0:

```<code>react-native init --version 0.42.0 example420
cd example420
npm install
react-native run-ios
</code>```

答: For me, I guess I needed to update xcode. I thought I was on 8.3 but apparently not. I also needed to update osx to 10.12.4 prior to updating my xcode. Now I'm all good and running a react-native init app at 0.42.3</p>

Body:
I am just trying to spin up a new react-native app but no luck.

react-native init NewApp
cd NewApp
npm install
react-native run-ios

Then see the below error:

** BUILD FAILED **

The following build commands failed:
    CompileC /Users/arc/Desktop/websites-dev/react-native/testing_rn/ios/build/Build/Intermediates/React.build/Debug-iphonesimulator/React.build/Objects-normal/x86_64/RCTProfile.o Profiler/RCTProfile.m normal x86_64 objective-c com.apple.compilers.llvm.clang.1_0.compiler

(1 failure)

Installing build/Build/Products/Debug-iphonesimulator/testing_rn.app
An error was encountered processing the command (domain=NSPOSIXErrorDomain, code=2):
Failed to install the requested application
An application bundle was not found at the provided path.
Provide a valid path to the desired application bundle.
Print: Entry, ":CFBundleIdentifier", Does Not Exist

Command failed: /usr/libexec/PlistBuddy -c Print:CFBundleIdentifier build/Build/Products/Debug-iphonesimulator/testing_rn.app/Info.plist
Print: Entry, ":CFBundleIdentifier", Does Not Exist

Using:

npm 4.1.2
node v7.5.0
El Capitan 10.11.6
Xcode 8.2

package.json:

{
    "name": "testing_rn",
    "version": "0.0.1",
    "private": true,
    "scripts": {
        "start": "node node_modules/react-native/local-cli/cli.js start",
        "test": "jest"
    },
    "dependencies": {
        "react": "15.4.2",
        "react-native": "0.42.3"
    },
    "devDependencies": {
        "babel-jest": "19.0.0",
        "babel-preset-react-native": "1.9.1",
        "jest": "19.0.2",
        "react-test-renderer": "15.4.2"
    },
    "jest": {
        "preset": "react-native"
    }
}

It seems like this may be related to the build via terminal but app may still work in xcode?

Print: Entry, ":CFBundleIdentifier", Does Not Exist have tried most solutions

github issue from 25 days ago:

https://github.com/facebook/react-native/issues/12737

Some related questions:

https://github.com/facebook/react-native/issues/7308

React-native run-ios commands fails

=========================================================

UPDATE:

For me, this seemed to have something to do with 0.42.0 and above. I can run a 0.41.2 project that I install with

react-native init --version 0.41.2 example412
cd example412
npm install
react-native run-ios

And boom. It works. But this gets errors:

react-native init example_latest
cd example_latest
npm install
react-native run-ios

then above errors are back. Same errors with init version at 0.42.0:

react-native init --version 0.42.0 example420
cd example420
npm install
react-native run-ios


问:
How to block calling function while multiple asynchronous calls are executed, then contiune processing the collected data?
I would like to process an XML file in JavaScript, read every sheet asynchronously (because oviously it would be faster), and return the final result. I have the parser functions, I got stuck on the part when I would like to wait for every async call to finish, then return the result. A callback isn't the best practice for me in this case, because this function would be called at the beggining of another module, where I wouldn't like to put the rest of the code (let's say for example 500 lines) in a callback.

I have tried many approaches, the last one looks like the one below. But it seems to result in an infinite loop. All the other attempts returned undefined value, because the caller function ended before async calls would finish, and the accumulator haven't got any value.

1. To collect every async call's result, I used promise.

```<code>function getAllSheets(callback) {
    accumulator = {};

    promise.all([
        processOneSheetAsync(workbook, sheetname1, ..., callback(data) {
            accumulator.one = data;
        }),
        processOneSheetAsync(workbook, sheetname2, ..., callback(data) {
            acc.two = data;
        }),
        /* some more function calls */
    ]).then(function(result) {
        callback(acc);
    });
}
</code>```

Note: processOneSheetAsync() is function that returns a new Promise and calls the parser(), as expected.

2. Then I tried to wait for it's callback in a function like this:

```<code>function getResult() {
    var result;
    var callback = false;

    getAllSheets(function(data) {
        result = data;
        callback = true;
    });

    while(!callback){};
    return result;
}
</code>```

I thought this would block the getResult() function until the variable callback is set to true. However, it seems that the while loop never detects the change of callback's.

Is there any good approach to solve this problem?

答:
You should really use a callback. I'd probably do something like:

```<code>var myResults=[];
var waiting=0;

data.forEach(function(datum){
    waiting++;
    asyncCall(datum, callback);
}

function callback(result){
    myResults.push(result);
    waiting--;
    if (waiting == 0){
         doStuffOn(myResults);
    }
}
</code>```

However, if you're still against everything that is good in the world, you should check this, found here

Body:
I would like to process an XML file in JavaScript, read every sheet asynchronously (because oviously it would be faster), and return the final result. I have the parser functions, I got stuck on the part when I would like to wait for every async call to finish, then return the result. A callback isn't the best practice for me in this case, because this function would be called at the beggining of another module, where I wouldn't like to put the rest of the code (let's say for example 500 lines) in a callback.

I have tried many approaches, the last one looks like the one below. But it seems to result in an infinite loop. All the other attempts returned undefined value, because the caller function ended before async calls would finish, and the accumulator haven't got any value.

1. To collect every async call's result, I used promise.

function getAllSheets(callback) {
    accumulator = {};

    promise.all([
        processOneSheetAsync(workbook, sheetname1, ..., callback(data) {
            accumulator.one = data;
        }),
        processOneSheetAsync(workbook, sheetname2, ..., callback(data) {
            acc.two = data;
        }),
        /* some more function calls */
    ]).then(function(result) {
        callback(acc);
    });
}

Note: processOneSheetAsync() is function that returns a new Promise and calls the parser(), as expected.

2. Then I tried to wait for it's callback in a function like this:

function getResult() {
    var result;
    var callback = false;

    getAllSheets(function(data) {
        result = data;
        callback = true;
    });

    while(!callback){};
    return result;
}

I thought this would block the getResult() function until the variable callback is set to true. However, it seems that the while loop never detects the change of callback's.

Is there any good approach to solve this problem?

Body:
You should really use a callback. I'd probably do something like:

var myResults=[];
var waiting=0;

data.forEach(function(datum){
    waiting++;
    asyncCall(datum, callback);
}

function callback(result){
    myResults.push(result);
    waiting--;
    if (waiting == 0){
         doStuffOn(myResults);
    }
}

However, if you're still against everything that is good in the world, you should check this, found here


问:
Jquery - Function Inside DIV not working after refreshed
I have a table "group1" contains table and rows. I use this plugin (tableDnD) to drag the row up/down, and it is all working fine. I have another Jquery function that delete row inside the DIV "group1" and the refresh the DIV only, this also works fine.

```<code>    $('#group1').tableDnD({
    onDrop: function(table, row) {
        $.post('updateRecord.asp?', {
            pagesid : "1",
            arr : $.tableDnD.serialize()
        });
    }
});
</code>```

Now, after the rows deleted, updated DB, then refreshed the DIV, the jQuery above with option drag row up/down is no longer working (if I refresh entire page, it would work).  I did some research and see people suggested about using delegate option, but I am not sure how to apply to the $('#group1').tableDnD function.

Updated - I tried this, but no luck.

```<code>$(document).on('tableDnD', '#group1', function(){
onDrop: function(table, row) {
    $.post('updateRecord.asp?', {
        pagesid : "1",
        arr : $.tableDnD.serialize()
    });
}
</code>```

});

Any suggestions would be appreciated.

答:
Update: It looks like this question has already been asked - Drag and drop not working after adding new row
Please look at the answer by meataxe.

Take a look at this documentation: http://api.jquery.com/on/

I'm not sure, but you may be able to pass the tableDnD function like this:

```<code>$(document).on('tableDnD', '#group1', function(){
    // code for on drag
});
</code>```

Body:
I have a table "group1" contains table and rows. I use this plugin (tableDnD) to drag the row up/down, and it is all working fine. I have another Jquery function that delete row inside the DIV "group1" and the refresh the DIV only, this also works fine.

    $('#group1').tableDnD({
    onDrop: function(table, row) {
        $.post('updateRecord.asp?', {
            pagesid : "1",
            arr : $.tableDnD.serialize()
        });
    }
});

Now, after the rows deleted, updated DB, then refreshed the DIV, the jQuery above with option drag row up/down is no longer working (if I refresh entire page, it would work).  I did some research and see people suggested about using delegate option, but I am not sure how to apply to the $('#group1').tableDnD function.

Updated - I tried this, but no luck.

$(document).on('tableDnD', '#group1', function(){
onDrop: function(table, row) {
    $.post('updateRecord.asp?', {
        pagesid : "1",
        arr : $.tableDnD.serialize()
    });
}

});

Any suggestions would be appreciated.

Body:
Update: It looks like this question has already been asked - Drag and drop not working after adding new row
Please look at the answer by meataxe.

Take a look at this documentation: http://api.jquery.com/on/

I'm not sure, but you may be able to pass the tableDnD function like this:

$(document).on('tableDnD', '#group1', function(){
    // code for on drag
});


问:
Play Framework 2.5 - Reverse route to a variable in .java file from scala.html file
I'm trying to refactor my Controllers & scala.html files to reduce the amount of parameters I'm passing from the Java Controller classes to the scala.html frontend files.

My plan is to refactor the code so that rather than passing the variables from the Java class to the scala.html, the scala.html files could reverse route back to the variables in the Java files.

E.g. rather than this:

```<code>@(someInteger: Int, someString: String, stringList: List[String], anotherInteger: Int)
</code>```

Just have one or two variables:

```<code>@(someInteger: Int, someString: String)
</code>```

And use reverse routes for the other variables where needed in the scala.html file like this:

```<code>@routes.SomeController.SomeMethod
</code>```

Also, I'd like to add a scala comparison in the scala.html file to some of these variables such as:

```<code>@if(@routes.SomeController.SomeMethod == true){
    ...
}
</code>```

The above works when passed in from the Java Controller classes as scala variables, but not (currently) when attempting to reverse route from the scala.html.

It's worth noting that the /GET route for controllers.SomeController.SomeMethod has been setup in the conf/routes file, I think it is a syntactical or logical issue.

Any help in accessing variables by reverse routing from the scala.html would be greatly appreciated!

答:
On your controllers you can use the map that is attached to the current request like this: ctx().args.put("key", "value");

On your views you can access the data that you placed on the map like this:
@Controller.ctx().args.get("key").

Body:
I'm trying to refactor my Controllers & scala.html files to reduce the amount of parameters I'm passing from the Java Controller classes to the scala.html frontend files.

My plan is to refactor the code so that rather than passing the variables from the Java class to the scala.html, the scala.html files could reverse route back to the variables in the Java files.

E.g. rather than this:

@(someInteger: Int, someString: String, stringList: List[String], anotherInteger: Int)

Just have one or two variables:

@(someInteger: Int, someString: String)

And use reverse routes for the other variables where needed in the scala.html file like this:

@routes.SomeController.SomeMethod

Also, I'd like to add a scala comparison in the scala.html file to some of these variables such as:

@if(@routes.SomeController.SomeMethod == true){
    ...
}

The above works when passed in from the Java Controller classes as scala variables, but not (currently) when attempting to reverse route from the scala.html.

It's worth noting that the /GET route for controllers.SomeController.SomeMethod has been setup in the conf/routes file, I think it is a syntactical or logical issue.

Any help in accessing variables by reverse routing from the scala.html would be greatly appreciated!


问:
What does the jsr keyword mean?
I'm looking at some Java code, and I've noticed the following:

```<code>if (!foo(bar, baz, qux)) {
    i = 0; jsr 433;
}
</code>```

javac chokes on it, saying it's not a statement and that a semicolon is expected after the keyword jsr.

I did some Googling, and I found some code containing the same thing, which leads me to believe it's there intentionally (even though they weren't able to get it to compile either). So what does jsr do? How does one get code containing it to compile?

答: It is not in the list of Java keywords. So I don't believe it has any meaning. And I doubt it's possible to compile it.</p>

Title: What does the jsr keyword mean?

Body:
I'm looking at some Java code, and I've noticed the following:

if (!foo(bar, baz, qux)) {
    i = 0; jsr 433;
}

javac chokes on it, saying it's not a statement and that a semicolon is expected after the keyword jsr.

I did some Googling, and I found some code containing the same thing, which leads me to believe it's there intentionally (even though they weren't able to get it to compile either). So what does jsr do? How does one get code containing it to compile?


问:
Using rawpy to convert multiple raw .NEF Images to TIFF
I have been searching through this forum but cannot find a relevant answer to my problem. I have only found solutions for single file conversions.

I want to convert a directory of Nikon RAW images (.NEF) into TIFF (.tiff).
This can be achieved with the rawpy plugin apparently. I am not well versed in python and have done my best. You will probably find my script laughable :)

I'd like to ideally be able to paste the directory path into the command line and have it convert everything for me, into 16-bit tiffs.

```<code>import rawpy
import imageio

paths = 'C:\Users\Jake\Desktop\Exposuretests\Darks'

for i in paths:
    with rawpy.imread(paths) as raw:
        rgb = raw.postprocess()
imageio.imsave(paths + '.tiff', rgb)
</code>```

Thanks all in advance for any help. I am sure this is quite simple for those versed in python!

答:
I imagine you already fixed this, but there are a few typos:

```<code>import rawpy
import imageio

paths = 'C:\Users\Jake\Desktop\Exposuretests\Darks'

for i in paths:
    with rawpy.imread(paths) as raw:
        rgb = raw.postprocess()
    imageio.imsave(paths + '\file_' + i + '.tiff', rgb)
</code>```

Might do the trick.

Steve

Body:
I have been searching through this forum but cannot find a relevant answer to my problem. I have only found solutions for single file conversions.

I want to convert a directory of Nikon RAW images (.NEF) into TIFF (.tiff).
This can be achieved with the rawpy plugin apparently. I am not well versed in python and have done my best. You will probably find my script laughable :)

I'd like to ideally be able to paste the directory path into the command line and have it convert everything for me, into 16-bit tiffs.

import rawpy
import imageio

paths = 'C:\Users\Jake\Desktop\Exposuretests\Darks'

for i in paths:
    with rawpy.imread(paths) as raw:
        rgb = raw.postprocess()
imageio.imsave(paths + '.tiff', rgb)

Thanks all in advance for any help. I am sure this is quite simple for those versed in python!

Body:
I imagine you already fixed this, but there are a few typos:

import rawpy
import imageio

paths = 'C:\Users\Jake\Desktop\Exposuretests\Darks'

for i in paths:
    with rawpy.imread(paths) as raw:
        rgb = raw.postprocess()
    imageio.imsave(paths + '\file_' + i + '.tiff', rgb)

Might do the trick.

Steve


问:
Subclass UIEvent to embed additional information?
Is it possible to subclass UIEvent to embed some additional information?
I tried but keep getting exceptions and can't find anything about subclassing UIEvent.

```<code>class CustomEvent: UIEvent {
      let payload: CustomData
      override init(payload: CustomData) {
            super.init()
            self.payload = payload
      }
}

017-03-30 08:51:17.504497 StealingTouches[1041:778674] -[StealingTouches.TouchEvent _firstTouchForView:]: unrecognized selector sent to instance 0x170053950
2017-03-30 08:51:17.505470 StealingTouches[1041:778674] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[StealingTouches.TouchEvent _firstTouchForView:]: unrecognized selector sent to instance 0x170053950'
*** First throw call stack:
(0x18bf991b8 0x18a9d055c 0x18bfa0268 0x18bf9d270 0x18be9680c 0x191e8494c 0x100026278 0x100026550 0x100026fc4 0x100027214 0x191e7be98 0x191e77328 0x191e47da0 0x19263175c 0x19262b130 0x18bf46b5c 0x18bf464a4 0x18bf440a4 0x18be722b8 0x18d926198 0x191eb27fc 0x191ead534 0x100029418 0x18ae555b8)
libc++abi.dylib: terminating with uncaught exception of type NSException
</code>```

I have a collection of views nested 3 levels deep inside superviews. I want the deeply nested view to add some custom data to the event, and forward this data up to the outermost view.

See image. The green views should handle the event, do the appropriate calculations, save the data into the event, and forward the data up to the red view. Only the green views respond to events, but only the red view knows what to do with that event.

Green view handles the touches...

```<code>class GreenView: UIControl {
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)

        //do some complicated calculation then save in custom event
        let customEvent = CustomEvent.init(payload: calculations)

        if let nextRespoonder = self.next {
            nextRespoonder.touchesBegan(touches, with: customEvent)
        }
    }
}
</code>```

Which then gets forwarded up to the yellow view...

```<code> class YellowView: UIControl {
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        if let nextRespoonder = self.next {
            nextRespoonder.touchesBegan(touches, with: event)
        }
    }
}
</code>```

And finally the red view can extract the event payload and do what it needs to do...

```<code> class RedView: UIControl {
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        if let customEvent = event as? CustomEvent {
               let payload = customEvent.payload
               //do something with the payload
        }

    }
}
</code>```

Another option is to store the payload data locally in the green view, and then the only thing the red view needs to do is identify which green view initiated the event. This is fairly simple to do with hit test, but I have over a hundred of these green views and it can get fairly complicated to figure out which one is which based on hit test alone as sometimes green views overlap each other.

答:
I learned that this pattern is the wrong way to handle this. The better thing to do is to use delegation. Assign redView as the delegate for greenView and just pass info up.</p>

```<code>protocol GreenViewDelegate {
     func onTouchesBegan(greenView: GreenView)
}

class GreenView: UIControl {

    var delegate: GreenViewDelegate?

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        self.delegate?.onTouchesBegan(greenView: self)
    }

}

class RedView: UIControl, GreenViewDelegate {

    init() {
        greenView.delegate = self
    }

    func onTochesBegan(greenView: GreenView) {
         //extract whatever data you want
    }

}
</code>```

Body:
Is it possible to subclass UIEvent to embed some additional information?
I tried but keep getting exceptions and can't find anything about subclassing UIEvent.

class CustomEvent: UIEvent {
      let payload: CustomData
      override init(payload: CustomData) {
            super.init()
            self.payload = payload
      }
}

017-03-30 08:51:17.504497 StealingTouches[1041:778674] -[StealingTouches.TouchEvent _firstTouchForView:]: unrecognized selector sent to instance 0x170053950
2017-03-30 08:51:17.505470 StealingTouches[1041:778674] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[StealingTouches.TouchEvent _firstTouchForView:]: unrecognized selector sent to instance 0x170053950'
*** First throw call stack:
(0x18bf991b8 0x18a9d055c 0x18bfa0268 0x18bf9d270 0x18be9680c 0x191e8494c 0x100026278 0x100026550 0x100026fc4 0x100027214 0x191e7be98 0x191e77328 0x191e47da0 0x19263175c 0x19262b130 0x18bf46b5c 0x18bf464a4 0x18bf440a4 0x18be722b8 0x18d926198 0x191eb27fc 0x191ead534 0x100029418 0x18ae555b8)
libc++abi.dylib: terminating with uncaught exception of type NSException

I have a collection of views nested 3 levels deep inside superviews. I want the deeply nested view to add some custom data to the event, and forward this data up to the outermost view.

See image. The green views should handle the event, do the appropriate calculations, save the data into the event, and forward the data up to the red view. Only the green views respond to events, but only the red view knows what to do with that event.

Green view handles the touches...

class GreenView: UIControl {
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)

        //do some complicated calculation then save in custom event
        let customEvent = CustomEvent.init(payload: calculations)

        if let nextRespoonder = self.next {
            nextRespoonder.touchesBegan(touches, with: customEvent)
        }
    }
}

Which then gets forwarded up to the yellow view...

 class YellowView: UIControl {
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        if let nextRespoonder = self.next {
            nextRespoonder.touchesBegan(touches, with: event)
        }
    }
}

And finally the red view can extract the event payload and do what it needs to do...

 class RedView: UIControl {
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        if let customEvent = event as? CustomEvent {
               let payload = customEvent.payload
               //do something with the payload
        }

    }
}

Another option is to store the payload data locally in the green view, and then the only thing the red view needs to do is identify which green view initiated the event. This is fairly simple to do with hit test, but I have over a hundred of these green views and it can get fairly complicated to figure out which one is which based on hit test alone as sometimes green views overlap each other.

Body:
I learned that this pattern is the wrong way to handle this. The better thing to do is to use delegation. Assign redView as the delegate for greenView and just pass info up.

protocol GreenViewDelegate {
     func onTouchesBegan(greenView: GreenView)
}

class GreenView: UIControl {

    var delegate: GreenViewDelegate?

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        self.delegate?.onTouchesBegan(greenView: self)
    }

}

class RedView: UIControl, GreenViewDelegate {

    init() {
        greenView.delegate = self
    }

    func onTochesBegan(greenView: GreenView) {
         //extract whatever data you want
    }

}


问:
SSIS Package with Excel as source
I have an Excel sheet with some headers and logos in it. I want to create a SSIS package of that Excel but when I created the package I am not getting the required column names. How do I get the exact column names in SQl as in Excel sheet ?

This is the sheet i am working with

答:
As user LONG started to say in the comments, if you have an oddly laid out Excel sheet, you will need to explicitly specify the range of data within the larger sheet.

You are particularly worse off because your column names span multiple rows. There's no workaround for this, so the connection manager is going to give you column names like F1, F2, and so on.

In this screenshot, I've specified in the "OpenRowset" property of my SSIS package that my data lives on the sheet named "DATA INPUT SECTIONS" and I want the range starting from A2 through column AE. I've not specified an end row so as to pull in all available rows.

Title: SSIS Package with Excel as source


问:
Auth::login($user) in laravel not able to login the user
I am using laravel 5.4 and Auth::login($user) is showing Type error:

Argument 1 passed to Illuminate\Auth\SessionGuard::login() must
  implement interface Illuminate\Contracts\Auth\Authenticatable,
  instance of Illuminate\Database\Eloquent\Builder given, called in
  /home/vendor/laravel/framework/src/Illuminate/Auth/AuthManager.php on
  line 294

My User.php file is:

```<code>namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'name', 'email', 'role', 'password',
];

/**
 * The attributes that should be hidden for arrays.
 *
 * @var array
 */
protected $hidden = [
    'password', 'remember_token',
];
}
</code>```

My AuthController.php is:

```<code>namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;
use Auth;
use Illuminate\Support\Facades\Input;
use \Hash;

class AuthController extends Controller
{
//
public function register(Request $request){
    $this->validate($request, [
        'name' => 'required|max:30',
        'email' => 'required|email|unique:users',
        'regpassword' => 'required|alpha_num|confirmed'
        ]);

    /*$user = new User();
    $user['name'] = $request['name'];
    $user['email'] = $request['email'];
    $user['password'] = bcrypt($request['password']);
    $user['role'] = 'user';
    $user->save();
    */
    $user = User::create(array(
        'email' => Input::get('email'),
        'name' => Input::get('name'),
        'password' => Hash::make(Input::get('password')),
        'role' => 'user'));
    return 'success';

 }

public function userLogin(Request $request){
    $this->validate($request,[
        'email' => 'required|email',
        'password' => 'required'
        ]);

    $user = User::where('email', '=', $request['email'])-> where('password' ,'=', Hash::make($request['password']))->where('role','=','user');

    if($user){
        Auth::login($user);
        return $next($request);
    }
    else{
        return redirect()->back();
    }

}
}
</code>```

My web.php

```<code>Route::get('/', function () {
return view('welcome');
});

Auth::routes();

Route::get('/home', 'HomeController@index');
Route::post('/register', 'AuthController@register');
Route::post('/UserLogin','AuthController@userLogin');
</code>```

答:
This:

```<code>$user = User::where('email', '=', $request['email'])-> where('password' ,'=', Hash::make($request['password']))->where('role','=','user');
</code>```

is not the way you will get the user.

Instead of

```<code>$user = User::where('email', '=', $request['email'])-> where('password' ,'=', Hash::make($request['password']))->where('role','=','user');

if($user){
    Auth::login($user);
    return $next($request);
}
else{
    return redirect()->back();
}
</code>```

you could use:

```<code>   $logged = auth()->attempt(
          ['email' => $request['email'],
           'password' => $request['password'],
           'role' => 'user']);

    if($logged) {
        return $next($request); // probably it won't work. This is fine in middleware but not in controller
    }
    else{
        return redirect()->back();
    }
</code>```

Body:
I am using laravel 5.4 and Auth::login($user) is showing Type error:

Argument 1 passed to Illuminate\Auth\SessionGuard::login() must
  implement interface Illuminate\Contracts\Auth\Authenticatable,
  instance of Illuminate\Database\Eloquent\Builder given, called in
  /home/vendor/laravel/framework/src/Illuminate/Auth/AuthManager.php on
  line 294

My User.php file is:

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'name', 'email', 'role', 'password',
];

/**
 * The attributes that should be hidden for arrays.
 *
 * @var array
 */
protected $hidden = [
    'password', 'remember_token',
];
}

My AuthController.php is:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;
use Auth;
use Illuminate\Support\Facades\Input;
use \Hash;

class AuthController extends Controller
{
//
public function register(Request $request){
    $this->validate($request, [
        'name' => 'required|max:30',
        'email' => 'required|email|unique:users',
        'regpassword' => 'required|alpha_num|confirmed'
        ]);

    /*$user = new User();
    $user['name'] = $request['name'];
    $user['email'] = $request['email'];
    $user['password'] = bcrypt($request['password']);
    $user['role'] = 'user';
    $user->save();
    */
    $user = User::create(array(
        'email' => Input::get('email'),
        'name' => Input::get('name'),
        'password' => Hash::make(Input::get('password')),
        'role' => 'user'));
    return 'success';

 }

public function userLogin(Request $request){
    $this->validate($request,[
        'email' => 'required|email',
        'password' => 'required'
        ]);

    $user = User::where('email', '=', $request['email'])-> where('password' ,'=', Hash::make($request['password']))->where('role','=','user');

    if($user){
        Auth::login($user);
        return $next($request);
    }
    else{
        return redirect()->back();
    }

}
}

My web.php

Route::get('/', function () {
return view('welcome');
});

Auth::routes();

Route::get('/home', 'HomeController@index');
Route::post('/register', 'AuthController@register');
Route::post('/UserLogin','AuthController@userLogin');

Body:
This:

$user = User::where('email', '=', $request['email'])-> where('password' ,'=', Hash::make($request['password']))->where('role','=','user');

is not the way you will get the user.

Instead of

$user = User::where('email', '=', $request['email'])-> where('password' ,'=', Hash::make($request['password']))->where('role','=','user');

if($user){
    Auth::login($user);
    return $next($request);
}
else{
    return redirect()->back();
}

you could use:

   $logged = auth()->attempt(
          ['email' => $request['email'],
           'password' => $request['password'],
           'role' => 'user']);

    if($logged) {
        return $next($request); // probably it won't work. This is fine in middleware but not in controller
    }
    else{
        return redirect()->back();
    }


问:
PHP Script does not seem to work
I run a script on my webspace which is used for an android application. Though, it does not seem to work. On some webspaces I get a blank site when I try reaching it, on others I receive a 500 Internal Server Error. Though this script should work properly because it used to do so.

It is supposed to get all information from a table and echo it after some INNER JOINs. I could not track the error even after some mysqli_error checks and some echos to check variables etc.

The variable $con does exist, the connection should work properly. I just removed it for stack overflow ^^.

```<code> <?php

$subId = 1;

$sql = "SELECT articles.a_id, sciences.science, articles.title, articles.content, login.username, articles.date, articles.viewed, articles.timestamp FROM articles
                INNER JOIN sciences ON articles.s_id = sciences.s_id
                INNER JOIN login ON articles.author = login.id
                WHERE articles.s_id = ".$subId."
                ORDER BY timestamp DESC";

if (!$res = mysqli_query($con,$sql)) {
    echo "FAIL";
    echo mysqli_error($con);
}
else {

$result = array();

while($row = mysqli_fetch_array($res)){
array_push($result,
array('a_id'=>$row[0],
'science'=>$row[1],
'title'=>$row[2],
'content'=>$row[3],
'author'=>$row[4],
'date'=>$row[5],
'viewed'=>$row[6],
'timestamp'=>$row[7]
));
}

echo json_encode(array("result"=>$result));
}
mysqli_close($con);

?>
</code>```

EDIT: I updated my code:

```<code>    <?php

$subId = 1;

$con = mysqli_connect("HOST", "USER", "PASSWORD", "DATABASE");

if (!$con)
{
echo "Cant't connect to MySQL.<br>";
echo "Debug: " . mysqli_connect_errno()
}

$sql = "SELECT articles.a_id, sciences.science, articles.title, articles.content, login.username, articles.date, articles.viewed, articles.timestamp FROM articles
INNER JOIN sciences ON articles.s_id = sciences.s_id
INNER JOIN login ON articles.author = login.id
WHERE articles.s_id = ".$subId."
ORDER BY timestamp DESC";

if (!$res = $con->query($sql))
{
    echo "FAIL";
}
else
{

    $result = array();

    while($row = $con->fetchArray($res))
    {
        array_push($result); //use the query to rename fields, if needed
    }

    echo json_encode(array("result"=>$result));
}

?>
</code>```

答: change timestamp to timestamp because it's reserved word add backticks

Title: PHP Script does not seem to work

Body:
I run a script on my webspace which is used for an android application. Though, it does not seem to work. On some webspaces I get a blank site when I try reaching it, on others I receive a 500 Internal Server Error. Though this script should work properly because it used to do so.

It is supposed to get all information from a table and echo it after some INNER JOINs. I could not track the error even after some mysqli_error checks and some echos to check variables etc.

The variable $con does exist, the connection should work properly. I just removed it for stack overflow ^^.

 <?php

$subId = 1;

$sql = "SELECT articles.a_id, sciences.science, articles.title, articles.content, login.username, articles.date, articles.viewed, articles.timestamp FROM articles
                INNER JOIN sciences ON articles.s_id = sciences.s_id
                INNER JOIN login ON articles.author = login.id
                WHERE articles.s_id = ".$subId."
                ORDER BY timestamp DESC";

if (!$res = mysqli_query($con,$sql)) {
    echo "FAIL";
    echo mysqli_error($con);
}
else {

$result = array();

while($row = mysqli_fetch_array($res)){
array_push($result,
array('a_id'=>$row[0],
'science'=>$row[1],
'title'=>$row[2],
'content'=>$row[3],
'author'=>$row[4],
'date'=>$row[5],
'viewed'=>$row[6],
'timestamp'=>$row[7]
));
}

echo json_encode(array("result"=>$result));
}
mysqli_close($con);

?>

EDIT: I updated my code:

    <?php

$subId = 1;

$con = mysqli_connect("HOST", "USER", "PASSWORD", "DATABASE");

if (!$con)
{
echo "Cant't connect to MySQL.
";
echo "Debug: " . mysqli_connect_errno()
}

$sql = "SELECT articles.a_id, sciences.science, articles.title, articles.content, login.username, articles.date, articles.viewed, articles.timestamp FROM articles
INNER JOIN sciences ON articles.s_id = sciences.s_id
INNER JOIN login ON articles.author = login.id
WHERE articles.s_id = ".$subId."
ORDER BY timestamp DESC";

if (!$res = $con->query($sql))
{
    echo "FAIL";
}
else
{

    $result = array();

    while($row = $con->fetchArray($res))
    {
        array_push($result); //use the query to rename fields, if needed
    }

    echo json_encode(array("result"=>$result));
}

?>


问:
Upload image and store locally, save file name in db, show in view MVC 5
Spent a lot of time going through similar articles in search for an answer to this question, here are some of them:

1Link, (Unable to show more than 2 links, but i have a bunch of them)

And most relevant
8 Link but that project is not working

But after going through this examples i still unable to sort it out. At the moment my project works without images, im able to CRUD new articles to page and remove it. But now i need to add image.
First of all, i need an image to be as part of a class (i'm creating a new article with some title, short description, text body and image) here is model i came up with, this is non working code. As i want to store link to file to db so i guess i need to create new variable ImagePath

```<code>namespace PhClub.Models
{
    public class Media
    {
        public int Id { get; set; }

        public string title { get; set; }
        public string description { get; set; }
        [Required, StringLength(2048), DataType(DataType.MultilineText)]
        public string body { get; set; }
        public string ImagePath { get; set; }
    }
}
</code>```

Next i need to add create form to get a filename to upload it.  Here is Create view code snippet

```<code>@using (Html.BeginForm("Create", "Medias", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <hr />
        @Html.ValidationSummary(true)

        <div class="form-group">
            @Html.LabelFor(model => model.title, "Title", new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.title)
                @Html.ValidationMessageFor(model => model.title)
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.description, "Description",new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.description)
                @Html.ValidationMessageFor(model => model.description)
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.body,  "Media",new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.body)
                @Html.ValidationMessageFor(model => model.body)
            </div>
        </div>
        **<div class="form-group">
            File name
            <div class="uploadfile">
                @Html.TextBoxFor(model => model.file, new { type = "file" })
                @Html.ValidationMessageFor(model => model.file)
                <input type="submit" value="Submit" />
            </div>
        </div>**

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Создать" class="btn btn-default" />
            </div>
        </div>
    </div>
}
</code>```

However here i have two uncertainties:
1. I already have a Create method in in Controller, it was generated by EF for me:

```<code>[HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,title,description,body")] Media media)
        {
            if (ModelState.IsValid)
            {
                db.Medias.Add(media);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(media);
        }
</code>```

But i need to integrate it somehow with this method somehow (i took this one from one of the examples)

```<code>   [HttpPost]
    public ActionResult FileUpload(Media mRegister)
    {
        //Check server side validation using data annotation
        if (ModelState.IsValid)
        {
            //TO:DO
            var fileName = Path.GetFileName(mRegister.file.FileName);
            var path = Path.Combine(Server.MapPath("~/Content/Upload"), fileName);
            mRegister.file.SaveAs(path);
            ViewBag.Message = "File has been uploaded successfully";
            ModelState.Clear();
        }
        return View();
    }
</code>```

I cannot have two methods with the same name - CREATE doing different things on one hand and on other I cannot give different name to it as i don't need other View for it, it needs to be shown on Create view if im understanding what is going on here.
2. Secondary  - do i need to have two buttons for this? one for upload image and one for creating object?

And finally i need to show image as part of the article somehow in my Media view. At the moment it looks like that

```<code>    <h2>@Model.title</h2>
    <br>

    <div class="media">
        <p>
            <strong>@Html.Raw(Model.title)</strong>
        </p>
        <p>
            @Html.Raw(Model.description)
        </p>
        <p>
            @Html.Raw(Model.body)
        </p>
    </div>
   <div style ="float:right margin: 0px; 0px; 15px; 15px;">
          @Html.Raw(Model.file)
   </div>
</code>```

From here I'm lost. I need to place that image in certain place, but don't know how.In other examples people creating bunch of other classes for file. Do i need it? What the easiest way of doing it? I know I'm not the first who came up with this question, but i could really use your help guys.

答:
Ok, after further research i managed to make it working. This is how it looks

My class

```<code>public class Media
{
    public int Id { get; set; }

    public string title { get; set; }
    public string description { get; set; }
    [Required, StringLength(2048), DataType(DataType.MultilineText)]
    public string body { get; set; }
    public string ImagePath { get; set; }

}
</code>```

Controller method

```<code>public ActionResult Create([Bind(Include = "Id,title,description,body")] Media media, HttpPostedFileBase file)
        {
            if (ModelState.IsValid)
            {
                if (file != null)
                {
                    file.SaveAs(HttpContext.Server.MapPath("~/Images/")
                                                          + file.FileName);
                    media.ImagePath = file.FileName;
                }
                db.Medias.Add(media);
                db.Medias.Add(media);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

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

Piece of code to upload image

```<code> <fieldset>
            <legend>Image</legend>
            <div class="editor-label">
                @Html.LabelFor(model => model.ImagePath)
            </div>
            <div class="editor-field">
                <input id="ImagePath" title="Upload a product image"
                       type="file" name="file" />
            </div>
 </fieldset>
</code>```

Media view to show final result

```<code><div class="media">
    <div style="float: right; margin: 0px 0px 15px 15px; height: 300px; width:450px">
        <div id="imageContainer">
            @*@Html.Raw(Model.ImagePath)*@
            <img src="~/Images/@Html.Raw(Model.ImagePath)" />
        </div>
    </div>
    <p>
        <strong>@Html.Raw(Model.title)</strong>
    </p>
    <p>
        @Html.Raw(Model.description)
    </p>
    <p>
        @Html.Raw(Model.body)
    </p>
</div>
</code>```

and css formatting to resize image to div dimensions

```<code>div > img {

  width: auto;
  height : auto;
  max-height: 100%;
  max-width: 100%;
}
</code>```

Link i was using for solving it is here Uploading/Displaying Images in MVC 4

Thanks everyone.

Body:
Spent a lot of time going through similar articles in search for an answer to this question, here are some of them:

1Link, (Unable to show more than 2 links, but i have a bunch of them)

And most relevant
8 Link but that project is not working

But after going through this examples i still unable to sort it out. At the moment my project works without images, im able to CRUD new articles to page and remove it. But now i need to add image.
First of all, i need an image to be as part of a class (i'm creating a new article with some title, short description, text body and image) here is model i came up with, this is non working code. As i want to store link to file to db so i guess i need to create new variable ImagePath

namespace PhClub.Models
{
    public class Media
    {
        public int Id { get; set; }

        public string title { get; set; }
        public string description { get; set; }
        [Required, StringLength(2048), DataType(DataType.MultilineText)]
        public string body { get; set; }
        public string ImagePath { get; set; }
    }
}

Next i need to add create form to get a filename to upload it.  Here is Create view code snippet

@using (Html.BeginForm("Create", "Medias", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()

        @Html.ValidationSummary(true)

            @Html.LabelFor(model => model.title, "Title", new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.title)
                @Html.ValidationMessageFor(model => model.title)

            @Html.LabelFor(model => model.description, "Description",new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.description)
                @Html.ValidationMessageFor(model => model.description)

            @Html.LabelFor(model => model.body,  "Media",new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.body)
                @Html.ValidationMessageFor(model => model.body)

        **

            File name

                @Html.TextBoxFor(model => model.file, new { type = "file" })
                @Html.ValidationMessageFor(model => model.file)
                <input type="submit" value="Submit" />

**

                <input type="submit" value="Создать" class="btn btn-default" />

}

However here i have two uncertainties:
1. I already have a Create method in in Controller, it was generated by EF for me:

[HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,title,description,body")] Media media)
        {
            if (ModelState.IsValid)
            {
                db.Medias.Add(media);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(media);
        }

But i need to integrate it somehow with this method somehow (i took this one from one of the examples)

   [HttpPost]
    public ActionResult FileUpload(Media mRegister)
    {
        //Check server side validation using data annotation
        if (ModelState.IsValid)
        {
            //TO:DO
            var fileName = Path.GetFileName(mRegister.file.FileName);
            var path = Path.Combine(Server.MapPath("~/Content/Upload"), fileName);
            mRegister.file.SaveAs(path);
            ViewBag.Message = "File has been uploaded successfully";
            ModelState.Clear();
        }
        return View();
    }

I cannot have two methods with the same name - CREATE doing different things on one hand and on other I cannot give different name to it as i don't need other View for it, it needs to be shown on Create view if im understanding what is going on here.
2. Secondary  - do i need to have two buttons for this? one for upload image and one for creating object?

And finally i need to show image as part of the article somehow in my Media view. At the moment it looks like that

@Model.title

            @Html.Raw(Model.title)

            @Html.Raw(Model.description)

            @Html.Raw(Model.body)

          @Html.Raw(Model.file)

From here I'm lost. I need to place that image in certain place, but don't know how.In other examples people creating bunch of other classes for file. Do i need it? What the easiest way of doing it? I know I'm not the first who came up with this question, but i could really use your help guys.

Body:
Ok, after further research i managed to make it working. This is how it looks

My class

public class Media
{
    public int Id { get; set; }

    public string title { get; set; }
    public string description { get; set; }
    [Required, StringLength(2048), DataType(DataType.MultilineText)]
    public string body { get; set; }
    public string ImagePath { get; set; }

}

Controller method

public ActionResult Create([Bind(Include = "Id,title,description,body")] Media media, HttpPostedFileBase file)
        {
            if (ModelState.IsValid)
            {
                if (file != null)
                {
                    file.SaveAs(HttpContext.Server.MapPath("~/Images/")
                                                          + file.FileName);
                    media.ImagePath = file.FileName;
                }
                db.Medias.Add(media);
                db.Medias.Add(media);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(media);
        }

Piece of code to upload image

 <fieldset>
            <legend>Image</legend>
            <div class="editor-label">
                @Html.LabelFor(model => model.ImagePath)
            </div>
            <div class="editor-field">
                <input id="ImagePath" title="Upload a product image"
                       type="file" name="file" />
            </div>
 </fieldset>

Media view to show final result

<div class="media">
    <div style="float: right; margin: 0px 0px 15px 15px; height: 300px; width:450px">
        <div id="imageContainer">
            @*@Html.Raw(Model.ImagePath)*@
            <img src="~/Images/@Html.Raw(Model.ImagePath)" />
        </div>
    </div>
    <p>
        <strong>@Html.Raw(Model.title)</strong>
    </p>
    <p>
        @Html.Raw(Model.description)
    </p>
    <p>
        @Html.Raw(Model.body)
    </p>
</div>

and css formatting to resize image to div dimensions

div > img {

  width: auto;
  height : auto;
  max-height: 100%;
  max-width: 100%;
}

Link i was using for solving it is here Uploading/Displaying Images in MVC 4

Thanks everyone.


问:
Bootstrap table won't fill container width
I'm writing a web site using bootstrap (3.3.2) with a simple table on one of the pages.  I just have a simple header panel in one container, and another content container with a title and table.  For some reason, text fills the width of the container, but the table left aligns and only spans the width required by the text within.  Anyone have any ideas?  I know I can add in a width="100%" to the table, but this should be default bootstrap behaviour...

Cheers

```<code><html>
  <head>
    <title>Page title</title>
    <link type="text/css" rel="stylesheet" href="bootstrap.min.css">
  </head>
  <body>

    <div class="navbar navbar-inverse navbar-static-top">
      <div class="container-fluid">
        <div class="navbar-header">
          <a class="navbar-brand" href="index.html">Home</a>
        </div>
        <div id="navbar" class="navbar-collapse collapse" >
          <ul class="nav navbar-nav">
            <li><a class="navbar-brand" href="modules.html">Modules</a></li>
            <li><a class="navbar-brand" href="sites.html">Sites</a></li>
            <li><a class="navbar-brand" href="search.html">Search</a></li>
          </ul>
        </div>
      </div>
    </div>

    <div class="container">
      <div class="page-header">
        <h2>Why won't the table align!?</h2>
      </div>

      <div class="table-responsive">
        <table>
          <thead>
            <th>Head1</th><th>Head2</th><th>Head3</th>
          </thead>
          <tbody>
            <tr>
              <td>Body1</td><td>Body2</td><td>Body3</td>
            </tr>
            <tr>
              <td>Body1</td><td>Body2</td><td>Body3</td>
            </tr>
            <tr>
              <td>Body1</td><td>Body2</td><td>Body3</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </body>
</html>
</code>```

答:
NOTE: If you're using bootstrap v4 alpha, even though the documentation says that you can use:

```<code><table class="table table-responsive">
  ...
</table>
</code>```

I still had to use the accepted answer to make it fill the container's width:

```<code><div class="table-responsive">
  <table class="table">
    ...
  </table>
</div>
</code>```

Body:
I'm writing a web site using bootstrap (3.3.2) with a simple table on one of the pages.  I just have a simple header panel in one container, and another content container with a title and table.  For some reason, text fills the width of the container, but the table left aligns and only spans the width required by the text within.  Anyone have any ideas?  I know I can add in a width="100%" to the table, but this should be default bootstrap behaviour...

Cheers

    <title>Page title</title>
    <link type="text/css" rel="stylesheet" href="bootstrap.min.css">

          Home

Modules

Sites

Search

Why won't the table align!?

            Head1	Head2	Head3

              Body1	Body2	Body3

              Body1	Body2	Body3

              Body1	Body2	Body3

Body:
NOTE: If you're using bootstrap v4 alpha, even though the documentation says that you can use:

<table class="table table-responsive">
  ...
</table>

I still had to use the accepted answer to make it fill the container's width:

<div class="table-responsive">
  <table class="table">
    ...
  </table>
</div>


问:
IS there a do not match function
I am trying to do 2 functions. The first is to match all the values (text) from 1 range with another and return the values that match. I would also like a second formula that returns the values that do not match. The 2 lists may not be in the same order nor can they be as they are ranked.

```<code>=IFERROR(INDEX($L$4:$L$23,MATCH($B15,$L$4:$L$23,0)),$L15&" Different")
</code>```

Could anyone suggest an answer?

Thank you in advance

答: I think that IFNA(INDEX($L$4:$L$23,MATCH($B15,$L$4:$L$23,0)), "NO MATCH") would help you solve this.</p>

Title: IS there a do not match function

Body:
I am trying to do 2 functions. The first is to match all the values (text) from 1 range with another and return the values that match. I would also like a second formula that returns the values that do not match. The 2 lists may not be in the same order nor can they be as they are ranked.

=IFERROR(INDEX($L$4:$L$23,MATCH($B15,$L$4:$L$23,0)),$L15&" Different")

Could anyone suggest an answer?

Thank you in advance