问:
calling soap webservices in an android
I am a newbie in soap web services calling in an android,I called Url, I send parameter also,

I got an error and error is :  Server was unable to process request. ---> Object reference not set to an instance of an object.' faultactor: 'null' detail: org.kxml2.kdom.Node

soap description link is as follows :
selticketprice

java code for calling soap webservices are :

```<code>                   protected String doInBackground(String... params) {
    // TODO Auto-generated method stub
    final SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME_memberRegistration);
        // SerializationUtils.serialize(bFile);
        request.addProperty("fareMediaType", "SJT");
        request.addProperty("fromValue", "1");
        request.addProperty("toValue", "3");
        request.addProperty("ticketDate", "2016-09-29");
        request.addProperty("lang", "en");
        final SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);
        envelope.headerIn = new Element[1];
        envelope.headerIn[0] = buildAuthHeader();
        new MarshalBase64().register(envelope);

        envelope.setOutputSoapObject(request);

        envelope.dotNet = true;
        HttpTransportSE androidHttpTransport = new HttpTransportSE(signUpURL);
        try {
            androidHttpTransport.call(SOAP_ACTION_memberRegistration, envelope);
            SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
            res = response.toString();

        } catch (Exception e) {
            Log.e("exception", e.getMessage(),e);
        }

    return res;
}

private Element buildAuthHeader() {
    Element h = new Element().createElement(NAMESPACE, "AuthHeader");
    Element username = new Element().createElement(NAMESPACE, "Username");
    username.addChild(Node.TEXT, "name");
    h.addChild(Node.ELEMENT, username);
    Element pass = new Element().createElement(NAMESPACE, "Password");
    pass.addChild(Node.TEXT, "*******");
    h.addChild(Node.ELEMENT, pass);

    return h;
}
</code>```

答:
Have you considered making the soap request without the use of Soap libraries?
This is more accurate and you can track down where an exception occurs as opposed to libs. Also its best for long term situations where the service changes and you cannot use the library. Go through my answer here Call a soap webservice in android</p>

Title: calling soap webservices in an android

Body:
I am a newbie in soap web services calling in an android,I called Url, I send parameter also,

I got an error and error is :  Server was unable to process request. ---> Object reference not set to an instance of an object.' faultactor: 'null' detail: org.kxml2.kdom.Node

soap description link is as follows :
selticketprice

java code for calling soap webservices are :

                   protected String doInBackground(String... params) {
    // TODO Auto-generated method stub
    final SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME_memberRegistration);
        // SerializationUtils.serialize(bFile);
        request.addProperty("fareMediaType", "SJT");
        request.addProperty("fromValue", "1");
        request.addProperty("toValue", "3");
        request.addProperty("ticketDate", "2016-09-29");
        request.addProperty("lang", "en");
        final SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);
        envelope.headerIn = new Element[1];
        envelope.headerIn[0] = buildAuthHeader();
        new MarshalBase64().register(envelope);

        envelope.setOutputSoapObject(request);

        envelope.dotNet = true;
        HttpTransportSE androidHttpTransport = new HttpTransportSE(signUpURL);
        try {
            androidHttpTransport.call(SOAP_ACTION_memberRegistration, envelope);
            SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
            res = response.toString();

        } catch (Exception e) {
            Log.e("exception", e.getMessage(),e);
        }

    return res;
}

private Element buildAuthHeader() {
    Element h = new Element().createElement(NAMESPACE, "AuthHeader");
    Element username = new Element().createElement(NAMESPACE, "Username");
    username.addChild(Node.TEXT, "name");
    h.addChild(Node.ELEMENT, username);
    Element pass = new Element().createElement(NAMESPACE, "Password");
    pass.addChild(Node.TEXT, "*******");
    h.addChild(Node.ELEMENT, pass);

    return h;
}


来源: stackexchange

问:
Naming a FK for a Post Author
I have the following tables

```<code>create table dbo.Users (
  UserId int identity not null,
  Name nvarchar (400) not null
)

create table dbo.Posts (
  PostId int identity not null,
  UserId int not null,
  Title nvarchar (400) not null,
  Content nvarchar (max) not null,
)
</code>```

On table Posts UserId is the author of the post and it is a FK to Users.UserId PK.

In this situations should I name the column UserId which is clear what the relation is or AuthorId describing of it is withing the post?

What is the most common approach for this naming?

答:
There's more than one reasonable naming standard, but a scheme I like for keys is:

Primary Key is the entity name followed by _ID (or Id if you're using camel-case as you show, but I typically don't in SQL).

Foregin Key is the referenced entity name followed by _ID (or Id blah blah); optionally preceded by a role identifier if needed for clarity.

So UserId (though I'd spell it USER_ID) is fine; or AuthorUserId.  I don't like AuthorId because there's no AUTHOR table.

It's just a layer of clarity.  Ideally you'd have descriptions in a data dictionary, and of course someone could look at the actual FK constraints (assuming you use actual FK constraints) but having conventions that let someone know at a glance what's happening is better.

...A minor update...

Regarding the very similar answer from Gordon Linoff, I think the only thing I'd put differently is the point about a role-naming prefix.  Certainly having multiple FK's that point to the same table is the most common case where role-naming is absolutely necessary, but I advocate using them any time the relationship meaning would otherwise be unclear.  Your ORDER table only has the billing address and not the shipping address or whatever?  Fine, but I'd still call it 'BILLING_ADDRESS_ID'

And there is one other case where a role name is basically required: self-reference.  EMPLOYEE_ID can have a MANAGER_EMPLOYEE_ID...

ContentLicense: CC BY-SA 3.0

Title: Naming a FK for a Post Author

Body:
I have the following tables

create table dbo.Users (
  UserId int identity not null,
  Name nvarchar (400) not null
)

create table dbo.Posts (
  PostId int identity not null,
  UserId int not null,
  Title nvarchar (400) not null,
  Content nvarchar (max) not null,
)

On table Posts UserId is the author of the post and it is a FK to Users.UserId PK.

In this situations should I name the column UserId which is clear what the relation is or AuthorId describing of it is withing the post?

What is the most common approach for this naming?


问:
S3 operator overloading for multiple classes
I defined two classes that can successfully add two of their own objects or a number and one of their own objects.

```<code>a <- structure(list(val = 1), class = 'customClass1')
b <- structure(list(val = 1), class = 'customClass2')
`+.customClass1` <- function(e1, e2, ...){
  val1 <- ifelse(is.numeric(e1), e1, e1$val)
  val2 <- ifelse(is.numeric(e2), e2, e2$val)
  val_res <- val1  + val2
  print('customClass1')
  return(structure(list(val = val_res), class = 'customClass1'))
}
`+.customClass2` <- function(e1, e2, ...){
  val1 <- ifelse(is.numeric(e1), e1, e1$val)
  val2 <- ifelse(is.numeric(e2), e2, e2$val)
  val_res <- val1  + val2
  print('customClass2')
  return(structure(list(val = val_res), class = 'customClass1'))
}
print.customClass1 <- function(x, ...){
  print(x$val)
}
print.customClass2 <- function(x, ...){
  print(x$val)
}
a + a
# [1] 2
a + 1
# [1] 2
b + b
# [1] 2
1 + b
# [1] 2
</code>```

But obviously, it goes wrong when I try to add the two custom classes.

```<code>a + b
# Error in a + b : non-numeric argument to binary operator
# In addition: Warning message:
# Incompatible methods ("+.customClass1", "+.customClass2") for "+"
</code>```

I could define just one function for customClass1, but then that function would not work when I try to add two customClass2 objects. Is there any way to prioritize one function over the other?

R seems to do this naturally by prioritizing my functions over the base functions (e.g. of the type numeric or integer). When one of both arguments has the customClass type, R automatically redirects it to my function instead of the default function.

答:
How R chooses which method to dispatch is discussed in the Details section of ?base::Ops

The classes of both arguments are considered in dispatching
  any member of this group.  For each argument its vector of
  classes is examined to see if there is a matching specific
  (preferred) or 'Ops' method.  If a method is found for just
  one argument or the same method is found for both, it is
  used.  If different methods are found, there is a warning
  about 'incompatible methods': in that case or if no method is
  found for either argument the internal method is used.

If customClass1 and customClass2 are related, you can use a virtual class to allow operations using the two different classes. For example, you can mix POSIXct and POSIXlt because they both inherit from POSIXt. This is documented in ?DateTimeClasses:

"POSIXct" is more convenient for including in data frames, and
  "POSIXlt" is closer to human-readable forms.  A virtual class
  "POSIXt" exists from which both of the classes inherit: it is
  used to allow operations such as subtraction to mix the two

For example:

```<code>class(pct <- Sys.time())
# [1] "POSIXct" "POSIXt"
Sys.sleep(1)
class(plt <- as.POSIXlt(Sys.time()))
# [1] "POSIXlt" "POSIXt"
plt - pct
# Time difference of 1.001677 secs
</code>```

If the classes aren't related in this way, there's some good information in the answers to Emulating multiple dispatch using S3 for “+” method - possible?.

Body:
I defined two classes that can successfully add two of their own objects or a number and one of their own objects.

a <- structure(list(val = 1), class = 'customClass1')
b <- structure(list(val = 1), class = 'customClass2')
`+.customClass1` <- function(e1, e2, ...){
  val1 <- ifelse(is.numeric(e1), e1, e1$val)
  val2 <- ifelse(is.numeric(e2), e2, e2$val)
  val_res <- val1  + val2
  print('customClass1')
  return(structure(list(val = val_res), class = 'customClass1'))
}
`+.customClass2` <- function(e1, e2, ...){
  val1 <- ifelse(is.numeric(e1), e1, e1$val)
  val2 <- ifelse(is.numeric(e2), e2, e2$val)
  val_res <- val1  + val2
  print('customClass2')
  return(structure(list(val = val_res), class = 'customClass1'))
}
print.customClass1 <- function(x, ...){
  print(x$val)
}
print.customClass2 <- function(x, ...){
  print(x$val)
}
a + a
# [1] 2
a + 1
# [1] 2
b + b
# [1] 2
1 + b
# [1] 2

But obviously, it goes wrong when I try to add the two custom classes.

a + b
# Error in a + b : non-numeric argument to binary operator
# In addition: Warning message:
# Incompatible methods ("+.customClass1", "+.customClass2") for "+"

I could define just one function for customClass1, but then that function would not work when I try to add two customClass2 objects. Is there any way to prioritize one function over the other?

R seems to do this naturally by prioritizing my functions over the base functions (e.g. of the type numeric or integer). When one of both arguments has the customClass type, R automatically redirects it to my function instead of the default function.

Body:
How R chooses which method to dispatch is discussed in the Details section of ?base::Ops

The classes of both arguments are considered in dispatching
  any member of this group.  For each argument its vector of
  classes is examined to see if there is a matching specific
  (preferred) or 'Ops' method.  If a method is found for just
  one argument or the same method is found for both, it is
  used.  If different methods are found, there is a warning
  about 'incompatible methods': in that case or if no method is
  found for either argument the internal method is used.

If customClass1 and customClass2 are related, you can use a virtual class to allow operations using the two different classes. For example, you can mix POSIXct and POSIXlt because they both inherit from POSIXt. This is documented in ?DateTimeClasses:

"POSIXct" is more convenient for including in data frames, and
  "POSIXlt" is closer to human-readable forms.  A virtual class
  "POSIXt" exists from which both of the classes inherit: it is
  used to allow operations such as subtraction to mix the two

For example:

class(pct <- Sys.time())
# [1] "POSIXct" "POSIXt"
Sys.sleep(1)
class(plt <- as.POSIXlt(Sys.time()))
# [1] "POSIXlt" "POSIXt"
plt - pct
# Time difference of 1.001677 secs

If the classes aren't related in this way, there's some good information in the answers to Emulating multiple dispatch using S3 for “+” method - possible?.


问:
Three.JS project - loaders don't load local models (with screenshot)
Example projects don't load 3d models to the scene. Or load but don't display, idk.

I tried both - the examples from three.js archive that I downloaded, also my own projects with my own models.

So I simply open three.js-master folder, open the index page in the examples folder, go through the list of examples. All examples work except the loaders examples. I just go through all of them and not a single format works, not obj, not fbx. What's wrong with local stuff? Online examples work but if I copy code from there it doesn't work.

See example

Can someone just open that freaking three.js master folder on your desktop and run any example locally? I mean an example with a mesh loader.

答:
You have to run through a local webserver or change your browsers local file security policy.  </p>

<p>It is all outlined at the three.js wiki at... Three.js, how to run things locally.  </p>

ContentLicense: CC BY-SA 4.0

Body:
You have to run through a local webserver or change your browsers local file security policy.

It is all outlined at the three.js wiki at... Three.js, how to run things locally.


问:
Strange namespace issue on php
I have found this article where I can found this syntax on php:

```<code>use Facades\ {
    App\Zonda
};
</code>```

I can't figure out how it works, Facades should be a namespace but I can't understand how it is related to the rest. I tried to check out documentation but I didn't find anything.

答:
In your case :

```<code>use Facades\ {
   App\Zonda
};
</code>```

Equals :

```<code>use Facades\App\Zonda;
</code>```

The group use declarations has been introduced in PHP 7 and are usefull when you need to include multiple classes defined in the same namespace.

The documentation can be found in here : http://php.net/manual/en/migration70.new-features.php#migration70.new-features.group-use-declarations

Title: Strange namespace issue on php

Body:
I have found this article where I can found this syntax on php:

use Facades\ {
    App\Zonda
};

I can't figure out how it works, Facades should be a namespace but I can't understand how it is related to the rest. I tried to check out documentation but I didn't find anything.

Body:
In your case :

use Facades\ {
   App\Zonda
};

Equals :

use Facades\App\Zonda;

The group use declarations has been introduced in PHP 7 and are usefull when you need to include multiple classes defined in the same namespace.

The documentation can be found in here : http://php.net/manual/en/migration70.new-features.php#migration70.new-features.group-use-declarations


问:
Aggregate by week in R
In R I frequently aggregate daily data (in a zoo) by month, using something like this:

result <- aggregate(x, as.yearmon, "mean", na.rm=TRUE)

Is there a way that I can do this by week?

答:
The easiest thing to do is to use the apply.weekly function from xts.

```<code>> apply.weekly(zoo(1:10, as.Date("2010-01-01") + 1:10), mean)
2010-01-03 2010-01-10 2010-01-11
         3         42         10
</code>```

ContentLicense: CC BY-SA 2.5

Title: Aggregate by week in R

Body:
The easiest thing to do is to use the apply.weekly function from xts.

> apply.weekly(zoo(1:10, as.Date("2010-01-01") + 1:10), mean)
2010-01-03 2010-01-10 2010-01-11
         3         42         10


问:
Using a blade file for a template?
I have a blade file that I wish to use as a vue component. So in the .vue file I would normally have it coded as:

```<code><template>
....
</tempalte>
....rest of vue file
</code>```

But how can I use a blade file for a template?

答:
What you can do is put the html in your vue-component file like:

```<code><template>
...put your html here
</tempalte>
</code>```

and then in the blade file insert the vue compoent like

```<code>@extends('layouts.app')
  <vue-component> </vue-component>
@section('content')
</code>```

Title: Using a blade file for a template?

Body:
I have a blade file that I wish to use as a vue component. So in the .vue file I would normally have it coded as:

<template>
....
</tempalte>
....rest of vue file

But how can I use a blade file for a template?

Body:
What you can do is put the html in your vue-component file like:

<template>
...put your html here
</tempalte>

and then in the blade file insert the vue compoent like

@extends('layouts.app')
  <vue-component> </vue-component>
@section('content')


问:
Check if android device rotation possible
I want to know if the android device supports device rotation.
I thought any Android device supports the screen rotation but my Samsung Galaxy View doesn't support any rotation.

I only found this code:

```<code>if (android.provider.Settings.System.getInt(getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0) == 1){
    Toast.makeText(getApplicationContext(), "Auto Rotate is ON", Toast.LENGTH_SHORT).show();

} else {
    Toast.makeText(getApplicationContext(), "Auto Rotate is OFF", Toast.LENGTH_SHORT).show();
}
</code>```

But this only lets me know if the user set the Screen rotation off or on, I want to know if it is at all possible.

Please help me,
best wishes

Leo

答:
With the aid of Kishore Jethava's answer, here is what it should look like.</p>

```<code>public static boolean isRotationPossible(Context context) {
    boolean hasAccelerometer = context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_SENSOR_ACCELEROMETER);

    return (hasAccelerometer && android.provider.Settings.System.getInt(getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0) == 1);
}
</code>```

Body:
I want to know if the android device supports device rotation.
I thought any Android device supports the screen rotation but my Samsung Galaxy View doesn't support any rotation.

I only found this code:

if (android.provider.Settings.System.getInt(getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0) == 1){
    Toast.makeText(getApplicationContext(), "Auto Rotate is ON", Toast.LENGTH_SHORT).show();

} else {
    Toast.makeText(getApplicationContext(), "Auto Rotate is OFF", Toast.LENGTH_SHORT).show();
}

But this only lets me know if the user set the Screen rotation off or on, I want to know if it is at all possible.

Please help me,
best wishes

Leo

Body:
With the aid of Kishore Jethava's answer, here is what it should look like.

public static boolean isRotationPossible(Context context) {
    boolean hasAccelerometer = context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_SENSOR_ACCELEROMETER);

    return (hasAccelerometer && android.provider.Settings.System.getInt(getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0) == 1);
}


问:
Accessing event.data from handler of input on textarea
I've been looking arround for a couple of days on this matter.

For some background I will explain the objective:
  I have a textarea and I want that when I type some special character defined by me (like @) it detects it as a part of a dictionary and show an autocomplete floating dive to choose from and if it's not in the dictionary it adds it.

The current status / problem is that I'm trying to capture the changes in the textarea with the input event and it works, it runs the handler code exactly when I want but I'm not able to access the data.

I guess I could capture the paste event and the key up events and take the clipboard from one and the key code from the other but I wonder if there is a way I can do it with the input event.

Here the relevant code:

function checkLastCharacter(event){
  console.log(event);
}

$( document ).ready(function() {
    console.log( "ready!" );
    //$( "#update" ).click(updateClick);
    var text=document.getElementById("text");
    text.addEventListener("input", checkLastCharacter);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<textarea id="text" rows="4" cols="50">Sample text</textarea></code>```

Result of execution: No mater what key I press or if I paste or not anything it shows:

"event: undefined"

Thanks in advance!

答:
EDIT:

This will handle the paste event from the clipboard. You will need to parse char by char to handle your specific token to show whatever you need to show.

```<code>$('target').on('paste', function () {
  var element = this;
  setTimeout(function () {
    var text = $(element).val();
    // do something with text
  }, 100);
});
</code>```

You will be much better of using jquerys .keypress() There's even an example on that page of capturing every keystroke (and a bunch of other information as well):

```<code><!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>keypress demo</title>
  <style>
  fieldset {
    margin-bottom: 1em;
  }
  input {
    display: block;
    margin-bottom: .25em;
  }
  #print-output {
    width: 100%;
  }
  .print-output-line {
    white-space: pre;
    padding: 5px;
    font-family: monaco, monospace;
    font-size: .7em;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<form>
  <fieldset>
    <label for="target">Type Something:</label>
    <input id="target" type="text">
  </fieldset>
</form>
<button id="other">
  Trigger the handler
</button>
<script src="/resources/events.js"></script>

<script>
var xTriggered = 0;
$( "#target" ).keypress(function( event ) {
  if ( event.which == 13 ) {
     event.preventDefault();
  }
  xTriggered++;
  var msg = "Handler for .keypress() called " + xTriggered + " time(s).";
  $.print( msg, "html" );
  $.print( event );
});

$( "#other" ).click(function() {
  $( "#target" ).keypress();
});
</script>

</body>
</html>
</code>```

The output of this script is:

```<code>Handler for .keypress() called 21 time(s).
{
originalEvent: [object KeyboardEvent],
type: keypress,
isDefaultPrevented: function returnFalse() {
    return false;
},
timeStamp: 41095.395000000004,
jQuery1102038791229348009115: true,
keyCode: 114,
key: r,
charCode: 114,
char: undefined,
which: 114,
view: [object Window],
target: <input id="target">,
shiftKey: false,
relatedTarget: undefined,
metaKey: false,
eventPhase: 2,
currentTarget: <input id="target">,
ctrlKey: false,
cancelable: true,
bubbles: true,
altKey: false,
delegateTarget: <input id="target">,
handleObj: [object Object],
data: null,
isPropagationStopped: function returnFalse() {
    return false;
},
isImmediatePropagationStopped: function returnFalse() {
    return false;
},
preventDefault: function () {
        var e = this.originalEvent;

        this.isDefaultPrevented = returnTrue;
        if ( !e ) {
            return;
        }

        // If preventDefault exists, run it on the original event
        if ( e.preventDefault ) {
            e.preventDefault();

        // Support: IE
        // Otherwise set the returnValue property of the original event to false
        } else {
            e.returnValue = false;
        }
    },
stopPropagation: function () {
        var e = this.originalEvent;

        this.isPropagationStopped = returnTrue;
        if ( !e ) {
            return;
        }
        // If stopPropagation exists, run it on the original event
        if ( e.stopPropagation ) {
            e.stopPropagation();
        }

        // Support: IE
        // Set the cancelBubble property of the original event to true
        e.cancelBubble = true;
    },
stopImmediatePropagation: function () {
        this.isImmediatePropagationStopped = returnTrue;
        this.stopPropagation();
    }
}
</code>```

Body:
I've been looking arround for a couple of days on this matter.

For some background I will explain the objective:
  I have a textarea and I want that when I type some special character defined by me (like @) it detects it as a part of a dictionary and show an autocomplete floating dive to choose from and if it's not in the dictionary it adds it.

The current status / problem is that I'm trying to capture the changes in the textarea with the input event and it works, it runs the handler code exactly when I want but I'm not able to access the data.

I guess I could capture the paste event and the key up events and take the clipboard from one and the key code from the other but I wonder if there is a way I can do it with the input event.

Here the relevant code:

function checkLastCharacter(event){
  console.log(event);
}

$( document ).ready(function() {
    console.log( "ready!" );
    //$( "#update" ).click(updateClick);
    var text=document.getElementById("text");
    text.addEventListener("input", checkLastCharacter);
});

<textarea id="text" rows="4" cols="50">Sample text</textarea>

Result of execution: No mater what key I press or if I paste or not anything it shows:

"event: undefined"

Thanks in advance!

Body:
EDIT:

This will handle the paste event from the clipboard. You will need to parse char by char to handle your specific token to show whatever you need to show.

$('target').on('paste', function () {
  var element = this;
  setTimeout(function () {
    var text = $(element).val();
    // do something with text
  }, 100);
});

You will be much better of using jquerys .keypress() There's even an example on that page of capturing every keystroke (and a bunch of other information as well):

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>keypress demo</title>
  <style>
  fieldset {
    margin-bottom: 1em;
  }
  input {
    display: block;
    margin-bottom: .25em;
  }
  #print-output {
    width: 100%;
  }
  .print-output-line {
    white-space: pre;
    padding: 5px;
    font-family: monaco, monospace;
    font-size: .7em;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<form>
  <fieldset>
    <label for="target">Type Something:</label>
    <input id="target" type="text">
  </fieldset>
</form>
<button id="other">
  Trigger the handler
</button>
<script src="/resources/events.js"></script>

<script>
var xTriggered = 0;
$( "#target" ).keypress(function( event ) {
  if ( event.which == 13 ) {
     event.preventDefault();
  }
  xTriggered++;
  var msg = "Handler for .keypress() called " + xTriggered + " time(s).";
  $.print( msg, "html" );
  $.print( event );
});

$( "#other" ).click(function() {
  $( "#target" ).keypress();
});
</script>

</body>
</html>

The output of this script is:

Handler for .keypress() called 21 time(s).
{
originalEvent: [object KeyboardEvent],
type: keypress,
isDefaultPrevented: function returnFalse() {
    return false;
},
timeStamp: 41095.395000000004,
jQuery1102038791229348009115: true,
keyCode: 114,
key: r,
charCode: 114,
char: undefined,
which: 114,
view: [object Window],
target: <input id="target">,
shiftKey: false,
relatedTarget: undefined,
metaKey: false,
eventPhase: 2,
currentTarget: <input id="target">,
ctrlKey: false,
cancelable: true,
bubbles: true,
altKey: false,
delegateTarget: <input id="target">,
handleObj: [object Object],
data: null,
isPropagationStopped: function returnFalse() {
    return false;
},
isImmediatePropagationStopped: function returnFalse() {
    return false;
},
preventDefault: function () {
        var e = this.originalEvent;

        this.isDefaultPrevented = returnTrue;
        if ( !e ) {
            return;
        }

        // If preventDefault exists, run it on the original event
        if ( e.preventDefault ) {
            e.preventDefault();

        // Support: IE
        // Otherwise set the returnValue property of the original event to false
        } else {
            e.returnValue = false;
        }
    },
stopPropagation: function () {
        var e = this.originalEvent;

        this.isPropagationStopped = returnTrue;
        if ( !e ) {
            return;
        }
        // If stopPropagation exists, run it on the original event
        if ( e.stopPropagation ) {
            e.stopPropagation();
        }

        // Support: IE
        // Set the cancelBubble property of the original event to true
        e.cancelBubble = true;
    },
stopImmediatePropagation: function () {
        this.isImmediatePropagationStopped = returnTrue;
        this.stopPropagation();
    }
}


问:
JPQL gives back java.langObject, instad of the expected type
I have an Employee class. A Worker class extends Employee, and Leader class extends Worker.

Every Leader has a list public List workersResponsibleFor = new ArrayList<>();. Which is a Join table, to illustrate if a Leader is responsible for one or many Workers.

```<code>@Entity
@Inheritance
@DiscriminatorColumn(name="EMP_TYPE")
@Table(name="EMPLOYEES")
public abstract class Employee implements Printable, Serializable {

    @Id
    @GeneratedValue
    @Column(name = "employee_id", unique = true)
    private int id;

    @Column(name = "position")
    @Enumerated(EnumType.STRING)
    private Position position;

    @Column(name = "name")
    private String name;

    @Column(name = "salary")
    private Double salary;

    @Transient
    public List<Project> projectsWorkingOn = new ArrayList<>();

    public Employee() {
    }
}
</code>```

Worker:

```<code>@Entity
public class Worker extends Employee {

    @Id
    @GeneratedValue
    @Column(name = "worker_id", unique = true)
    private int id;

    public Worker() {
    }
}
</code>```

Leader:

```<code>@Entity
public abstract class Leader extends Worker {

    public Leader() {
    }

    public Leader(Position position, String name, Double salary) {
        super(position, name, salary);
    }

    @OneToMany
    @JoinTable(name="WORKERS_RESPONSIBLE_FOR",
            joinColumns = {@JoinColumn(name="RES_ID")},
    inverseJoinColumns = {@JoinColumn(name="FOR_ID")})
    public List<Worker> workersResponsibleFor = new ArrayList<>();
}
</code>```

The problem is, every time I try to get a Worker back with the following method:

```<code>private static final EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("manager1");
private static final EntityManager entityManager = entityManagerFactory.createEntityManager();

public Worker exampleQuery() {
        Worker w;
        try {
            Query query = entityManager.createQuery("select e1, e2 from Employee e1 join e1.workersResponsibleFor e2 WHERE e1.name LIKE 'James%'");
            w = (Worker) query.getSingleResult();
        } finally {
            entityManager.close();
            entityManagerFactory.close();
        }
        System.out.println(w.getName());
        return w;
    }
</code>```

Error:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.company.employees.Worker

I get a java.lang.Object back, insted of a Worker. But all my other methods are able to return Workers, so could be the problem with the query I'm using? Thanks

答:
JPQL of

```<code>select e1, e2 from Employee e1 join e1.workersResponsibleFor e2 WHERE ...
</code>```

will always return rows of type Object[] (and the message tells you exactly that), since that is what the JPA spec defines it to do. And if you look at element 0 it will be of the type of e1, and element 1 will be of the type of e2. Suggest you look at the JPA spec or the documentation of whichever implementation you use.

If you had instead selected just the candidate alias then you get a row of type of e1. Again, defined in the JPA spec!

Body:
I have an Employee class. A Worker class extends Employee, and Leader class extends Worker.

Every Leader has a list public List workersResponsibleFor = new ArrayList<>();. Which is a Join table, to illustrate if a Leader is responsible for one or many Workers.

@Entity
@Inheritance
@DiscriminatorColumn(name="EMP_TYPE")
@Table(name="EMPLOYEES")
public abstract class Employee implements Printable, Serializable {

    @Id
    @GeneratedValue
    @Column(name = "employee_id", unique = true)
    private int id;

    @Column(name = "position")
    @Enumerated(EnumType.STRING)
    private Position position;

    @Column(name = "name")
    private String name;

    @Column(name = "salary")
    private Double salary;

    @Transient
    public List<Project> projectsWorkingOn = new ArrayList<>();

    public Employee() {
    }
}

Worker:

@Entity
public class Worker extends Employee {

    @Id
    @GeneratedValue
    @Column(name = "worker_id", unique = true)
    private int id;

    public Worker() {
    }
}

Leader:

@Entity
public abstract class Leader extends Worker {

    public Leader() {
    }

    public Leader(Position position, String name, Double salary) {
        super(position, name, salary);
    }

    @OneToMany
    @JoinTable(name="WORKERS_RESPONSIBLE_FOR",
            joinColumns = {@JoinColumn(name="RES_ID")},
    inverseJoinColumns = {@JoinColumn(name="FOR_ID")})
    public List<Worker> workersResponsibleFor = new ArrayList<>();
}

The problem is, every time I try to get a Worker back with the following method:

private static final EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("manager1");
private static final EntityManager entityManager = entityManagerFactory.createEntityManager();

public Worker exampleQuery() {
        Worker w;
        try {
            Query query = entityManager.createQuery("select e1, e2 from Employee e1 join e1.workersResponsibleFor e2 WHERE e1.name LIKE 'James%'");
            w = (Worker) query.getSingleResult();
        } finally {
            entityManager.close();
            entityManagerFactory.close();
        }
        System.out.println(w.getName());
        return w;
    }

Error:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.company.employees.Worker

I get a java.lang.Object back, insted of a Worker. But all my other methods are able to return Workers, so could be the problem with the query I'm using? Thanks

Body:
JPQL of

select e1, e2 from Employee e1 join e1.workersResponsibleFor e2 WHERE ...

will always return rows of type Object[] (and the message tells you exactly that), since that is what the JPA spec defines it to do. And if you look at element 0 it will be of the type of e1, and element 1 will be of the type of e2. Suggest you look at the JPA spec or the documentation of whichever implementation you use.

If you had instead selected just the candidate alias then you get a row of type of e1. Again, defined in the JPA spec!


问:
Git: "Corrupt loose object"
Whenever I pull from my remote, I get the following error about compression. When I run the manual compression, I get the same:

```<code>$ git gc
error: Could not read 3813783126d41a3200b35b6681357c213352ab31
fatal: bad tree object 3813783126d41a3200b35b6681357c213352ab31
error: failed to run repack
</code>```

Does anyone know, what to do about that?

From cat-file I get this:

```<code>$ git cat-file -t 3813783126d41a3200b35b6681357c213352ab31
error: unable to find 3813783126d41a3200b35b6681357c213352ab31
fatal: git cat-file 3813783126d41a3200b35b6681357c213352ab31: bad file
</code>```

And from git fsck I get this ( don't know if it's actually related):

```<code>$ git fsck
error: inflate: data stream error (invalid distance too far back)
error: corrupt loose object '45ba4ceb93bc812ef20a6630bb27e9e0b33a012a'
fatal: loose object 45ba4ceb93bc812ef20a6630bb27e9e0b33a012a (stored in .git/objects/45/ba4ceb93bc812ef20a6630bb27e9e0b33a012a) is corrupted
</code>```

Can anyone help me decipher this?

答:
I solved this way:
I decided to simply copy the uncorrupted object file from the backup's clone to my original repository. This worked just as well. (By the way: If you can't find the object in .git/objects/ by its name, it probably has been [packed][pack] to conserve space.)</p>

Title: Git: "Corrupt loose object"

Body:
Whenever I pull from my remote, I get the following error about compression. When I run the manual compression, I get the same:

$ git gc
error: Could not read 3813783126d41a3200b35b6681357c213352ab31
fatal: bad tree object 3813783126d41a3200b35b6681357c213352ab31
error: failed to run repack

Does anyone know, what to do about that?

From cat-file I get this:

$ git cat-file -t 3813783126d41a3200b35b6681357c213352ab31
error: unable to find 3813783126d41a3200b35b6681357c213352ab31
fatal: git cat-file 3813783126d41a3200b35b6681357c213352ab31: bad file

And from git fsck I get this ( don't know if it's actually related):

$ git fsck
error: inflate: data stream error (invalid distance too far back)
error: corrupt loose object '45ba4ceb93bc812ef20a6630bb27e9e0b33a012a'
fatal: loose object 45ba4ceb93bc812ef20a6630bb27e9e0b33a012a (stored in .git/objects/45/ba4ceb93bc812ef20a6630bb27e9e0b33a012a) is corrupted

Can anyone help me decipher this?


问:
How to summarize values of all first rows of sub-groups in a group while using MS SSRS?
In our DB, we have: (x means don't care)

```<code>GID   UID    COST
================================
A   1    100
A   1    x
A   2    200
A   2    x
B   3    330
B   3    x
</code>```

And the customer report required to look like:

```<code>   UID    COST
================================
[Group - A]
   1    100
   1
   2    200
   2
   ---Subtotal: 300
[Group - B]
   3    330
   3    x
   ---Subtotal: 330
                        ======Total:    630
</code>```

I've 2 groups in the SSRS report, one is group on GID, and one is group on UID, and I've tried many ways to summarize all the first COST of an UID in a group of GID. But no success.

If doing this in Crystal report, we can use "on group change formula" to achieve it. But in SSRS, I found no way to do it right.

Please kindly help!

答:
You maybe have to go back to the SQL and create the column you want to sum.

Using your example:

```<code>select
    GID,
    UID,
    Cost,
    case when row_number()  over(partition by GID,UID ORDER BY GID,UID,Cost) = 1 then Cost else 0 end as firstCostGroup
from
(
    select 'a' as GID, 1 as UID, 100 as Cost
    union
    select 'a', 1, 101
    union
    select 'a', 2, 200
    union
    select 'a', 2, 201
    union
    select 'b', 3, 300
    union
    select 'b', 3, 301
) as rawdata
</code>```

The row_number function requires SQL 2005 or greater.

A workaround for SQL 2000 would be something like

```<code>drop table #RawData
go
drop table #RawDataFirstRows
GO
create table #RawData
(
id int identity(1,1),
GID varchar(10),
UID int,
Cost int
)

insert into #RawData
    select 'a' as GID, 1 as UID, 100 as Cost
    union
    select 'a', 1, 101
    union
    select 'a', 2, 200
    union
    select 'a', 2, 201
    union
    select 'b', 3, 300
    union
    select 'b', 3, 301

create table #RawDataFirstRows
(
id int
)

insert into #RawDataFirstRows
select
rd.id
from #RawData rd
where
rd.id = (select top 1 id from #RawData rw where rd.uid = rw.uid and rd.gid = rw.gid order by rw.gid,rw.uid)

select
rd.GID, rd.UID, rd.Cost, case when rw.id is null then 0 else 1 end as firstCostGroup
from
#RawData rd
left join
#RawDataFirstRows rw on rd.id = rw.id
</code>```

Note that the nested query in the where clause is incredibly inffecient as it has to call that query for each row in the #Rawdata table. Gets the job done, but at what cost?

If it does not cause performance issues at production levels of data, you may be okay.

Body:
In our DB, we have: (x means don't care)

GID   UID    COST
================================
A   1    100
A   1    x
A   2    200
A   2    x
B   3    330
B   3    x

And the customer report required to look like:

   UID    COST
================================
[Group - A]
   1    100
   1
   2    200
   2
   ---Subtotal: 300
[Group - B]
   3    330
   3    x
   ---Subtotal: 330
                        ======Total:    630

I've 2 groups in the SSRS report, one is group on GID, and one is group on UID, and I've tried many ways to summarize all the first COST of an UID in a group of GID. But no success.

If doing this in Crystal report, we can use "on group change formula" to achieve it. But in SSRS, I found no way to do it right.

Please kindly help!

Body:
You maybe have to go back to the SQL and create the column you want to sum.

Using your example:

select
    GID,
    UID,
    Cost,
    case when row_number()  over(partition by GID,UID ORDER BY GID,UID,Cost) = 1 then Cost else 0 end as firstCostGroup
from
(
    select 'a' as GID, 1 as UID, 100 as Cost
    union
    select 'a', 1, 101
    union
    select 'a', 2, 200
    union
    select 'a', 2, 201
    union
    select 'b', 3, 300
    union
    select 'b', 3, 301
) as rawdata

The row_number function requires SQL 2005 or greater.

A workaround for SQL 2000 would be something like

drop table #RawData
go
drop table #RawDataFirstRows
GO
create table #RawData
(
id int identity(1,1),
GID varchar(10),
UID int,
Cost int
)

insert into #RawData
    select 'a' as GID, 1 as UID, 100 as Cost
    union
    select 'a', 1, 101
    union
    select 'a', 2, 200
    union
    select 'a', 2, 201
    union
    select 'b', 3, 300
    union
    select 'b', 3, 301

create table #RawDataFirstRows
(
id int
)

insert into #RawDataFirstRows
select
rd.id
from #RawData rd
where
rd.id = (select top 1 id from #RawData rw where rd.uid = rw.uid and rd.gid = rw.gid order by rw.gid,rw.uid)

select
rd.GID, rd.UID, rd.Cost, case when rw.id is null then 0 else 1 end as firstCostGroup
from
#RawData rd
left join
#RawDataFirstRows rw on rd.id = rw.id

Note that the nested query in the where clause is incredibly inffecient as it has to call that query for each row in the #Rawdata table. Gets the job done, but at what cost?

If it does not cause performance issues at production levels of data, you may be okay.


问:
VBA fit all shapes in a column to the corresponding cell?
I have a workbook like so:

```<code>     Column L

L5 = Image
L6 = Image
L7 = Image
L8 = Image
</code>```

Column L has images copied and pasted into each cell. The images are all looking a bit mismatched if i'm honest.

I'd like to fit each image to the cell exactly. Is there a way of doing this for all images in the column without having to define the name of each image?

Here's what i've tried:

```<code>Sub FitImageToCell()
    With Sheet1.Shapes
        .Left = .TopLeftCell.Left
        .Top = .TopLeftCell.Top
        .Height = .TopLeftCell.Height
        .Width = .TopLeftCell.Width
    End With
End Sub
</code>```

But i get a object doesn't support this property or method error.

Please can someone show me how to do this?

答:
You're nearly there.

You're just missing telling it what shape in the shapes collection you're working with and telling it to go through each shape on the sheet.

This code will use a For Each....Next to cycle through the shapes collection and reference each shape using the shp variable.

```<code>Sub FitImageToCell()

    Dim shp As Shape

    For Each shp In Sheet1.Shapes
        With shp
            .Left = .TopLeftCell.Left
            .Top = .TopLeftCell.Top
            .Height = .TopLeftCell.Height
            .Width = .TopLeftCell.Width
        End With
    Next shp

End Sub
</code>```

If you want to move just one shape then you can use:

```<code>Sub FitImageToCell1()

    With Sheet1.Shapes("Rectangle 1")
        .Left = .TopLeftCell.Left
        .Top = .TopLeftCell.Top
        .Height = .TopLeftCell.Height
        .Width = .TopLeftCell.Width
    End With

End Sub
</code>```

Finally, if you want to move specific types of shape you can use:

```<code>Sub FitImageToCell()

    Dim shp As Shape

    For Each shp In Sheet1.Shapes
        With shp
            If .Type = msoAutoShape Then
                If .AutoShapeType = msoShapeRectangle Then
                    .Left = .TopLeftCell.Left
                    .Top = .TopLeftCell.Top
                    .Height = .TopLeftCell.Height
                    .Width = .TopLeftCell.Width
                End If
            End If
        End With
    Next shp

End Sub
</code>```

There's a list of shape types here:  https://msdn.microsoft.com/en-us/library/aa432678(v=office.12).aspx

And a list of autoshape types here:  https://msdn.microsoft.com/en-us/library/aa432469(v=office.12).aspx

Body:
I have a workbook like so:

     Column L

L5 = Image
L6 = Image
L7 = Image
L8 = Image

Column L has images copied and pasted into each cell. The images are all looking a bit mismatched if i'm honest.

I'd like to fit each image to the cell exactly. Is there a way of doing this for all images in the column without having to define the name of each image?

Here's what i've tried:

Sub FitImageToCell()
    With Sheet1.Shapes
        .Left = .TopLeftCell.Left
        .Top = .TopLeftCell.Top
        .Height = .TopLeftCell.Height
        .Width = .TopLeftCell.Width
    End With
End Sub

But i get a object doesn't support this property or method error.

Please can someone show me how to do this?

Body:
You're nearly there.

You're just missing telling it what shape in the shapes collection you're working with and telling it to go through each shape on the sheet.

This code will use a For Each....Next to cycle through the shapes collection and reference each shape using the shp variable.

Sub FitImageToCell()

    Dim shp As Shape

    For Each shp In Sheet1.Shapes
        With shp
            .Left = .TopLeftCell.Left
            .Top = .TopLeftCell.Top
            .Height = .TopLeftCell.Height
            .Width = .TopLeftCell.Width
        End With
    Next shp

End Sub

If you want to move just one shape then you can use:

Sub FitImageToCell1()

    With Sheet1.Shapes("Rectangle 1")
        .Left = .TopLeftCell.Left
        .Top = .TopLeftCell.Top
        .Height = .TopLeftCell.Height
        .Width = .TopLeftCell.Width
    End With

End Sub

Finally, if you want to move specific types of shape you can use:

Sub FitImageToCell()

    Dim shp As Shape

    For Each shp In Sheet1.Shapes
        With shp
            If .Type = msoAutoShape Then
                If .AutoShapeType = msoShapeRectangle Then
                    .Left = .TopLeftCell.Left
                    .Top = .TopLeftCell.Top
                    .Height = .TopLeftCell.Height
                    .Width = .TopLeftCell.Width
                End If
            End If
        End With
    Next shp

End Sub

There's a list of shape types here:  https://msdn.microsoft.com/en-us/library/aa432678(v=office.12).aspx

And a list of autoshape types here:  https://msdn.microsoft.com/en-us/library/aa432469(v=office.12).aspx


Title: How to draw SVG icon using html and css?

Body:
is this possible to draw such kind of icons, i have tried so far but i am unable to make such kind of icon using html and css.

I am trying following code

<svg height="1000" width="1000">
<path d="M16 32c8.837 0 16-7.160 16-16s-7.163-16-16-16-16 7.163-16 16 7.163 16 16 16zM16 3c7.18 0 13 5.82 13 13s-5.82 13-13 13-13-5.82-13-13 5.82-13 13-13zM8 10c0-1.105 0.895-2 2-2s2 0.895 2 2c0 1.105-0.895 2-2 2s-2-0.895-2-2zM20 10c0-1.105 0.895-2 2-2s2 0.895 2 2c0 1.105-0.895 2-2 2s-2-0.895-2-2zM22.003 19.602l2.573 1.544c-1.749 2.908-4.935 4.855-8.576 4.855s-6.827-1.946-8.576-4.855l2.573-1.544c1.224 2.036 3.454 3.398 6.003 3.398s4.779-1.362 6.003-3.398z"></path>
</svg>

Body:
You can edit the existing paths into separate ones...the delimiter in the path code is the M

<path class="left-eye"
 d="M8 10c0-1.105 0.895-2 2-2s2 0.895 2 2c0 1.105-0.895 2-2 2s-2-0.895-2-2zM20 10c0-1.105
 0.895-2 2-2s2 0.895 2 2c0 1.105-0.895 2-2 2s-2-0.895-2-2zM22.003 19.602l2.573 1.544c-1.749 2.908-4.935
 4.855-8.576 4.855s-6.827-1.946-8.576-4.855l2.573-1.544c1.224 2.036 3.454
 3.398 6.003 3.398s4.779-1.362 6.003-3.398z"></path>

See these examples:

svg {
  width: 200px;
  display: inline-block;
}

.green {
  fill: green;
}

.red {
  fill: red;
}

.left-eye {
  fill: blue;
}

.right-eye {
  fill: pink;
}

.smile {
  fill: orange;
}

.features {
  fill: rebeccapurple;
}

<svg viewbox=" 0 0 32 32">
  <path class="green "d="M16 32c8.837 0 16-7.160 16-16s-7.163-16-16-16-16 7.163-16 16 7.163 16 16 16z"></path>
  <path class="red "d="M16 3c7.18 0 13 5.82 13 13s-5.82 13-13 13-13-5.82-13-13 5.82-13 13-13zM8 10c0-1.105 0.895-2 2-2s2 0.895 2 2c0 1.105-0.895 2-2 2s-2-0.895-2-2zM20 10c0-1.105 0.895-2 2-2s2 0.895 2 2c0 1.105-0.895 2-2 2s-2-0.895-2-2zM22.003 19.602l2.573 1.544c-1.749 2.908-4.935 4.855-8.576 4.855s-6.827-1.946-8.576-4.855l2.573-1.544c1.224 2.036 3.454 3.398 6.003 3.398s4.779-1.362 6.003-3.398z"></path>
    <path class="left-eye" d="M8 10c0-1.105 0.895-2 2-2s2 0.895 2 2c0 1.105-0.895 2-2 2s-2-0.895-2-2zM20 10c0-1.105 0.895-2 2-2s2 0.895 2 2c0 1.105-0.895 2-2 2s-2-0.895-2-2zM22.003 19.602l2.573 1.544c-1.749 2.908-4.935 4.855-8.576 4.855s-6.827-1.946-8.576-4.855l2.573-1.544c1.224 2.036 3.454 3.398 6.003 3.398s4.779-1.362 6.003-3.398z"></path>
      <path class="right-eye" d="M20 10c0-1.105 0.895-2 2-2s2 0.895 2 2c0 1.105-0.895 2-2 2s-2-0.895-2-2zM22.003 19.602l2.573 1.544c-1.749 2.908-4.935 4.855-8.576 4.855s-6.827-1.946-8.576-4.855l2.573-1.544c1.224 2.036 3.454 3.398 6.003 3.398s4.779-1.362 6.003-3.398z"></path>
        <path class="smile" d="M22.003 19.602l2.573 1.544c-1.749 2.908-4.935 4.855-8.576 4.855s-6.827-1.946-8.576-4.855l2.573-1.544c1.224 2.036 3.454 3.398 6.003 3.398s4.779-1.362 6.003-3.398z"></path>
</svg>

<svg viewbox=" 0 0 32 32">
  <path class="green "d="M16 32c8.837 0 16-7.160 16-16s-7.163-16-16-16-16 7.163-16 16 7.163 16 16 16z"></path>
  <path class="red "d="M16 3c7.18 0 13 5.82 13 13s-5.82 13-13 13-13-5.82-13-13 5.82-13 13-13zM8 10c0-1.105 0.895-2 2-2s2 0.895 2 2c0 1.105-0.895 2-2 2s-2-0.895-2-2zM20 10c0-1.105 0.895-2 2-2s2 0.895 2 2c0 1.105-0.895 2-2 2s-2-0.895-2-2zM22.003 19.602l2.573 1.544c-1.749 2.908-4.935 4.855-8.576 4.855s-6.827-1.946-8.576-4.855l2.573-1.544c1.224 2.036 3.454 3.398 6.003 3.398s4.779-1.362 6.003-3.398z"></path>
    <path class="features" d="M8 10c0-1.105 0.895-2 2-2s2 0.895 2 2c0 1.105-0.895 2-2 2s-2-0.895-2-2zM20 10c0-1.105 0.895-2 2-2s2 0.895 2 2c0 1.105-0.895 2-2 2s-2-0.895-2-2zM22.003 19.602l2.573 1.544c-1.749 2.908-4.935 4.855-8.576 4.855s-6.827-1.946-8.576-4.855l2.573-1.544c1.224 2.036 3.454 3.398 6.003 3.398s4.779-1.362 6.003-3.398z

                              M20 10c0-1.105 0.895-2 2-2s2 0.895 2 2c0 1.105-0.895 2-2 2s-2-0.895-2-2zM22.003 19.602l2.573 1.544c-1.749 2.908-4.935 4.855-8.576 4.855s-6.827-1.946-8.576-4.855l2.573-1.544c1.224 2.036 3.454 3.398 6.003 3.398s4.779-1.362 6.003-3.398z

                                 M22.003 19.602l2.573 1.544c-1.749 2.908-4.935 4.855-8.576 4.855s-6.827-1.946-8.576-4.855l2.573-1.544c1.224 2.036 3.454 3.398 6.003 3.398s4.779-1.362 6.003-3.398z"></path>
</svg>

The "features" (eyes/smile) can be separate paths or just one (I've provided) examples of both.

The trick here is to add the correct viewbox so that the SVG fills the whole SVG canvas. Then the SVG can be sized with CSS not HTML.


问:
Laravel Ajax cannot update database when click on a link
I have an audio file on public folder like this-

```<code>@foreach ($songs as $song)
     <a href="{{asset('/audio/' . $song->song)}}" download="" >
        <button type="button" class="download" style="margin-bottom: 15px;">
           <i class="glyphicon glyphicon-download">Download</i>
        </button>
     </a>
 @endforeach
</code>```

So, when i click that button it downloads the song. In my database, in "song" table there is column for song and another one for download_count which is set to default(0). I try to update download_count when i click on the link by ajax. My ajax:

```<code>$(function() {
  $('.download').click(function(){
 $.ajax({
   url: "/update_download_count",
   type:"POST",
   data: {
     song_id:$(this).attr('data-id')
   }
  });
});
    });
</code>```

My Route:

```<code>Route::post('/update_download_count', 'PagesController@updateDownloadCount');
</code>```

Controller:

```<code>public function updateDownloadCount(){
         $song_id = $_POST['song_id'];
         $song->download += 1;
         $song->save();
}
</code>```

But, i cannot update my database however i click on the link. it still set to 0 in download_count column. Plz help, what's the wrong?

答:
Instead of

```<code>$song->download += 1;
</code>```

Try:

```<code>Song::find($request->input("song_id"))->increment('download');
</code>```

I think that should work

Body:
I have an audio file on public folder like this-

@foreach ($songs as $song)
     song)}}" download="" >
        <button type="button" class="download" style="margin-bottom: 15px;">
           Download
        </button>

 @endforeach

So, when i click that button it downloads the song. In my database, in "song" table there is column for song and another one for download_count which is set to default(0). I try to update download_count when i click on the link by ajax. My ajax:

$(function() {
  $('.download').click(function(){
 $.ajax({
   url: "/update_download_count",
   type:"POST",
   data: {
     song_id:$(this).attr('data-id')
   }
  });
});
    });

My Route:

Route::post('/update_download_count', 'PagesController@updateDownloadCount');

Controller:

public function updateDownloadCount(){
         $song_id = $_POST['song_id'];
         $song->download += 1;
         $song->save();
}

But, i cannot update my database however i click on the link. it still set to 0 in download_count column. Plz help, what's the wrong?

Body:
Instead of

$song->download += 1;

Try:

Song::find($request->input("song_id"))->increment('download');

I think that should work


问:
Unit Test Adapter Threw exception
I am facing exception as shown below when running a coded ui test method.

It terminates before entering in test method body and return exception

```<code>Message: Unit Test Adapter threw exception: Could not load type 'Microsoft.VisualStudio.QualityTools.UnitTestFrmework...
</code>```

As shown below in image libraries are already added.

I am using following version in entire project

```<code>Microsoft.VisualStudio.QualityTools.CodedUITestFramework //version 14.0.0.0
Microsoft.VisualStudio.QualityTools.UnitTestFramework //Version 10.1.0.0
Microsoft.VisualStudio.TestTools.UITest.Common //Version 14.0.0.0
Microsoft.VisualStudio.TestTools.UITest.Extension //Version 14.0.0.0
Microsoft.VisualStudio.TestTools.UITesting //Version 14.0.0.0
</code>```

Thanks.

答:
I just checked my app.config and found following lines were added there.

```<code> <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.VisualStudio.QualityTools.UnitTestFramework" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-10.1.0.0" newVersion="10.1.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</code>```

I do not know how it happen but when i removed this, everything started working fine.

Title: Unit Test Adapter Threw exception

Body:
I am facing exception as shown below when running a coded ui test method.

It terminates before entering in test method body and return exception

Message: Unit Test Adapter threw exception: Could not load type 'Microsoft.VisualStudio.QualityTools.UnitTestFrmework...

As shown below in image libraries are already added.

I am using following version in entire project

Microsoft.VisualStudio.QualityTools.CodedUITestFramework //version 14.0.0.0
Microsoft.VisualStudio.QualityTools.UnitTestFramework //Version 10.1.0.0
Microsoft.VisualStudio.TestTools.UITest.Common //Version 14.0.0.0
Microsoft.VisualStudio.TestTools.UITest.Extension //Version 14.0.0.0
Microsoft.VisualStudio.TestTools.UITesting //Version 14.0.0.0

Thanks.

Body:
I just checked my app.config and found following lines were added there.

 <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.VisualStudio.QualityTools.UnitTestFramework" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-10.1.0.0" newVersion="10.1.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>

I do not know how it happen but when i removed this, everything started working fine.


问:
opencv rtsp stream protocol
I want to process and display a network rtsp stream that is created from a raspberry camera.
I have this code:

```<code>#include <iostream>
#include <functional>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

int main(int argc, char** argv) {

    cv::VideoCapture * stream = new cv::VideoCapture("rtsp://192.168.55.151:8554/");
    if (!stream->isOpened()) return -1;

    cv::namedWindow("rtsp_stream", CV_WINDOW_AUTOSIZE);
    cv::Mat frame;

    while (true) {

        if (!stream->read(frame)) return -1;

        cv::imshow("rtsp_stream", frame);
        cv::waitKey(15);
    }

    return 1;
}
</code>```

When the stream is not live, the execution of this results in:

```<code>[tcp @ 0xa12480] Connection to tcp://192.168.55.151:8554?timeout=0 failed: Connection refused
</code>```

Which means that the stream tries to connect with tcp. When the stream is live, the execution results in:

```<code> [rtsp @ 0xb07960] method SETUP failed: 461 Client error
</code>```

From internet research i found that the problem may be that the stream uses udp. If i change the URL to:

```<code>"udp://192.168.55.151:8554/"
</code>```

Then the execution freezes in the cv::VideoCapture("udp://192.168.55.151:8554/");

VLC is able to open the rtsp stream. As i am given to understand, ffmpeg is used to decode the stream with opencv. When i run:

```<code>ffmpeg -rtsp_transport udp -i rtsp://192.168.55.151:8554/ -t 5 test.mp4
</code>```

the stream decoding and saving is successful.
So how can i specify the lower level protocol to be udp in the opencv code? Is there another way to do it with opencv?

EDIT: If i change the ffmpeg command to use tcp, i.e:

```<code>ffmpeg -rtsp_transport tcp -i rtsp://192.168.55.151:8554/ -t 5 test.mp4
</code>```

then i get the same exact error with the c++ code, 461 client error

EDIT: When the code uses the udp:// link, after some 15 seconds of freeze, the execution returns with error

答:
It was answered in the github opencv issues.
The problem is that opencv forces ffmpeg to use a tcp connection, whereas my server uses rtp protocol(udp transport layer).
So in order to resolve the problem i changed the server to an http stream.</p>

Title: opencv rtsp stream protocol

Body:
I want to process and display a network rtsp stream that is created from a raspberry camera.
I have this code:

#include <iostream>
#include <functional>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

int main(int argc, char** argv) {

    cv::VideoCapture * stream = new cv::VideoCapture("rtsp://192.168.55.151:8554/");
    if (!stream->isOpened()) return -1;

    cv::namedWindow("rtsp_stream", CV_WINDOW_AUTOSIZE);
    cv::Mat frame;

    while (true) {

        if (!stream->read(frame)) return -1;

        cv::imshow("rtsp_stream", frame);
        cv::waitKey(15);
    }

    return 1;
}

When the stream is not live, the execution of this results in:

[tcp @ 0xa12480] Connection to tcp://192.168.55.151:8554?timeout=0 failed: Connection refused

Which means that the stream tries to connect with tcp. When the stream is live, the execution results in:

 [rtsp @ 0xb07960] method SETUP failed: 461 Client error

From internet research i found that the problem may be that the stream uses udp. If i change the URL to:

"udp://192.168.55.151:8554/"

Then the execution freezes in the cv::VideoCapture("udp://192.168.55.151:8554/");

VLC is able to open the rtsp stream. As i am given to understand, ffmpeg is used to decode the stream with opencv. When i run:

ffmpeg -rtsp_transport udp -i rtsp://192.168.55.151:8554/ -t 5 test.mp4

the stream decoding and saving is successful.
So how can i specify the lower level protocol to be udp in the opencv code? Is there another way to do it with opencv?

EDIT: If i change the ffmpeg command to use tcp, i.e:

ffmpeg -rtsp_transport tcp -i rtsp://192.168.55.151:8554/ -t 5 test.mp4

then i get the same exact error with the c++ code, 461 client error

EDIT: When the code uses the udp:// link, after some 15 seconds of freeze, the execution returns with error


问:
Matlab imrect in infinite loop
I have a Matlab UI where I want the user to input several areas using imrect as soon as a radiobutton is selected.

It is unknown how many areas will be selected so the selection needs to be in an infinite loop.

As soon as another radiobutton is selected, the imrect input should stop, which I cannot get to work.

Here is a minimal working example:

```<code>function mwe
ax = axes('Position', [0 0 1 1]);
bg = uibuttongroup('Position',[0 0 .15 1], 'SelectionChangedFcn',{@bselection, ax});
r1 = uicontrol(bg, 'Style','radiobutton', 'String','Option 1', 'Position',[10 250 100 30]);
r2 = uicontrol(bg, 'Style','radiobutton', 'String','Option 2', 'Position',[10 225 100 30], 'Value',1);

function bselection(source, event, ax)
  switch event.NewValue.String
    case 'Option 1'
      while true
        h = imrect(ax);
        % do stuff
        delete(h);
      end
    case 'Option 2'
      % do not show imrect and do other stuff
  end
</code>```

I appreciate any help.

答:
You can set the Interruptible property on the button. You can also set BusyAction to cancel. The help says:

The interruption occurs at the next point where MATLAB processes the
  queue, such as when there is a drawnow, uifigure, getframe, waitfor,
  or pause command.

So if you include a 'pause', it may not stop until the next rectangle has been selected. This is because once you've called imrect, it may not know that it has to stop.

However this method may not work if imrect blocks the matlab UI from triggering a callback.

An altogether better way is not to use an endless loop. You need to tell it when to end by checking --

```<code>running = true;
while running
  h=imrect(ax)
  % do stuff
  delete(h)
  if (SOMETHING)
      running = false
  end
end
</code>```

What is SOMETHING? We need to check if the button has been deselected.

You could use

```<code>if r1.Value!=1
  running = false
end
</code>```

Which would check if r1 is not selected, and if so, running becomes false, and the loop stops cycling round.

Title: Matlab imrect in infinite loop

Body:
I have a Matlab UI where I want the user to input several areas using imrect as soon as a radiobutton is selected.

It is unknown how many areas will be selected so the selection needs to be in an infinite loop.

As soon as another radiobutton is selected, the imrect input should stop, which I cannot get to work.

Here is a minimal working example:

function mwe
ax = axes('Position', [0 0 1 1]);
bg = uibuttongroup('Position',[0 0 .15 1], 'SelectionChangedFcn',{@bselection, ax});
r1 = uicontrol(bg, 'Style','radiobutton', 'String','Option 1', 'Position',[10 250 100 30]);
r2 = uicontrol(bg, 'Style','radiobutton', 'String','Option 2', 'Position',[10 225 100 30], 'Value',1);

function bselection(source, event, ax)
  switch event.NewValue.String
    case 'Option 1'
      while true
        h = imrect(ax);
        % do stuff
        delete(h);
      end
    case 'Option 2'
      % do not show imrect and do other stuff
  end

I appreciate any help.

Body:
You can set the Interruptible property on the button. You can also set BusyAction to cancel. The help says:

The interruption occurs at the next point where MATLAB processes the
  queue, such as when there is a drawnow, uifigure, getframe, waitfor,
  or pause command.

So if you include a 'pause', it may not stop until the next rectangle has been selected. This is because once you've called imrect, it may not know that it has to stop.

However this method may not work if imrect blocks the matlab UI from triggering a callback.

An altogether better way is not to use an endless loop. You need to tell it when to end by checking --

running = true;
while running
  h=imrect(ax)
  % do stuff
  delete(h)
  if (SOMETHING)
      running = false
  end
end

What is SOMETHING? We need to check if the button has been deselected.

You could use

if r1.Value!=1
  running = false
end

Which would check if r1 is not selected, and if so, running becomes false, and the loop stops cycling round.


问:
Laravel 5 InvalidArgumentException in FileViewFinder.php line 137: View [.admin] not found
This is student.php and my function for admin:

```<code> public function admin(Request $request){

       if($request->isMethod('get')){
       return \View::make('/admin');
    }
       else
        {

                 $UserData['email'] = Input::get('username');
                 $UserData['password'] = Input::get('password');
                 User::create($UserData);
                 return 'admintest';
                 //return Redirect::to('/view');
         }
   }
</code>```

routes.php

```<code>      Route::match(['get', 'post'], '/admin', 'student@admin');
</code>```

This is admin form:

```<code>     {!! Form::open(array('url' => '/admin')) !!}
  <input type="hidden" name="_token" value="{{ csrf_token() }}">

    User Name:<br />
      <input name="username" type="text" id="username" size="40" />
    <br /><br />
    Password:<br />
   <input name="password" type="password" id="password" size="40" />
   <br />
   <br />
   <br />

     <input type="submit" name="button" id="button" value="Log In" />

  {!! Form::close() !!}
</code>```

Don't know why showing error:

InvalidArgumentException in FileViewFinder.php line 137:
  View [.] not found

答:
If you recently deployed you project to your production server or moved the project to another server, do not forget to clear the app cache by running these commands.

```<code>php artisan cache:clear
php artisan view:clear
php artisan config:cache
</code>```

it should fix it.

Also consider updating your .env file to match new environment variables.

Body:
This is student.php and my function for admin:

 public function admin(Request $request){

       if($request->isMethod('get')){
       return \View::make('/admin');
    }
       else
        {

                 $UserData['email'] = Input::get('username');
                 $UserData['password'] = Input::get('password');
                 User::create($UserData);
                 return 'admintest';
                 //return Redirect::to('/view');
         }
   }

routes.php

      Route::match(['get', 'post'], '/admin', 'student@admin');

This is admin form:

     {!! Form::open(array('url' => '/admin')) !!}
  <input type="hidden" name="_token" value="{{ csrf_token() }}">

    User Name:

      <input name="username" type="text" id="username" size="40" />

    Password:

   <input name="password" type="password" id="password" size="40" />

     <input type="submit" name="button" id="button" value="Log In" />

  {!! Form::close() !!}

Don't know why showing error:

InvalidArgumentException in FileViewFinder.php line 137:
  View [.] not found

Body:
If you recently deployed you project to your production server or moved the project to another server, do not forget to clear the app cache by running these commands.

php artisan cache:clear
php artisan view:clear
php artisan config:cache

it should fix it.

Also consider updating your .env file to match new environment variables.


问:
Is there a java method to convert a string sum to a integer
I have 2 variables an integer (Num1) and a String (Str1)
My problem is that in the string I have stored a Sum eg: "3+3+3"
And i need to convert it to the int (Num1). So my question is, is there a single method in java that i can use to do this

Code.

```<code>public class StringSum {
    public static void main(String[] args) {
        String Str1;
        int Num1 = 0;

        Str1 = "3+3+3";

        Num1 = Str; // Here is where i need the method

        System.out.println("The answer to " + Str1 + " is : " + Num1);
    }
}
</code>```

答:
Yes, you can use:

```<code>import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;

public class Test {
  public static void main(String[] args) throws Exception{
    ScriptEngineManager manager= new ScriptEngineManager();
    ScriptEngine seng= manager.getEngineByName("JavaScript");
    String bar = "3+3+3";
    System.out.println(seng.eval(bar));
    }
}
</code>```

Using JavaScript engine

Body:
I have 2 variables an integer (Num1) and a String (Str1)
My problem is that in the string I have stored a Sum eg: "3+3+3"
And i need to convert it to the int (Num1). So my question is, is there a single method in java that i can use to do this

Code.

public class StringSum {
    public static void main(String[] args) {
        String Str1;
        int Num1 = 0;

        Str1 = "3+3+3";

        Num1 = Str; // Here is where i need the method

        System.out.println("The answer to " + Str1 + " is : " + Num1);
    }
}

Body:
Yes, you can use:

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;

public class Test {
  public static void main(String[] args) throws Exception{
    ScriptEngineManager manager= new ScriptEngineManager();
    ScriptEngine seng= manager.getEngineByName("JavaScript");
    String bar = "3+3+3";
    System.out.println(seng.eval(bar));
    }
}

Using JavaScript engine


问:
Looping through Pandas dataframes by addressing those with a variable
I am trying to do a set of repetitive operations on a set of similar dataframes (in this example, converting strings of timestamps to datetime objects).
My original dataframe:

```<code>     Date_assetA  assetA    Date_assetB  assetB    Date_assetC  assetC  \
0  06/09/16 8:00  4629.0  06/09/16 5:50   208.2  06/09/16 5:50  209.05
1  06/09/16 8:10  4629.5  06/09/16 6:00   208.0  06/09/16 6:00  208.85
2  06/09/16 8:20  4630.0  06/09/16 6:10   208.1  06/09/16 6:10  208.95
3  06/09/16 8:30  4632.5  06/09/16 6:20   208.1  06/09/16 6:20  208.95
4  06/09/16 8:40  4630.5  06/09/16 6:30   208.1  06/09/16 6:30  208.95

   Date_assetD  assetD
0  06/09/16 5:50  209.70
1  06/09/16 6:00  209.50
2  06/09/16 6:10  209.60
3  06/09/16 6:50  209.55
4  06/09/16 7:10  209.65
</code>```

I build four independant DataFrames from the initial one, as i will need to align those after converting the Date_assetX columns to timestamps. I want to loop through those by adressing them using the list of assets. Here is my code, with the missing part. Any attempt as concatenating a name of df_assetX failed so far:

```<code>import pandas as pd

df = pd.read_csv('example.csv')

df_assetA = df[['Date_assetA', 'assetA']]
df_assetB = df[['Date_assetB', 'assetB']]
df_assetC = df[['Date_assetC', 'assetC']]
df_assetD = df[['Date_assetD', 'assetD']]

contract_list = ['assetA', 'assetB', 'assetC', 'assetD']
for contract in contract_list:
    date_column = 'Date_' + str(contract)
    df_contract = # That's the part where i'm stuck...
    df_contract.date_column = pd.to_datetime(df_contract.date_column, dayfirst=True)
</code>```

Is there something obvious i'm missing, or is the whole approach botched  and i should try the dictionary route instead ?

Thanks,

答:
What I usually do is do create a list of dataframes, then concat them all at once. It would look something like this:</p>

```<code>Frames = []
# Start the loop
for contract in contract_list:
    df = ... # Do whatever
    Frames.append(df)
# Concat
All = pd.concat(Frames)
</code>```

Body:
I am trying to do a set of repetitive operations on a set of similar dataframes (in this example, converting strings of timestamps to datetime objects).
My original dataframe:

     Date_assetA  assetA    Date_assetB  assetB    Date_assetC  assetC  \
0  06/09/16 8:00  4629.0  06/09/16 5:50   208.2  06/09/16 5:50  209.05
1  06/09/16 8:10  4629.5  06/09/16 6:00   208.0  06/09/16 6:00  208.85
2  06/09/16 8:20  4630.0  06/09/16 6:10   208.1  06/09/16 6:10  208.95
3  06/09/16 8:30  4632.5  06/09/16 6:20   208.1  06/09/16 6:20  208.95
4  06/09/16 8:40  4630.5  06/09/16 6:30   208.1  06/09/16 6:30  208.95

   Date_assetD  assetD
0  06/09/16 5:50  209.70
1  06/09/16 6:00  209.50
2  06/09/16 6:10  209.60
3  06/09/16 6:50  209.55
4  06/09/16 7:10  209.65

I build four independant DataFrames from the initial one, as i will need to align those after converting the Date_assetX columns to timestamps. I want to loop through those by adressing them using the list of assets. Here is my code, with the missing part. Any attempt as concatenating a name of df_assetX failed so far:

import pandas as pd

df = pd.read_csv('example.csv')

df_assetA = df[['Date_assetA', 'assetA']]
df_assetB = df[['Date_assetB', 'assetB']]
df_assetC = df[['Date_assetC', 'assetC']]
df_assetD = df[['Date_assetD', 'assetD']]

contract_list = ['assetA', 'assetB', 'assetC', 'assetD']
for contract in contract_list:
    date_column = 'Date_' + str(contract)
    df_contract = # That's the part where i'm stuck...
    df_contract.date_column = pd.to_datetime(df_contract.date_column, dayfirst=True)

Is there something obvious i'm missing, or is the whole approach botched  and i should try the dictionary route instead ?

Thanks,

Body:
What I usually do is do create a list of dataframes, then concat them all at once. It would look something like this:

Frames = []
# Start the loop
for contract in contract_list:
    df = ... # Do whatever
    Frames.append(df)
# Concat
All = pd.concat(Frames)


问:
Codeigniter php: bootstrap modal view is sending empty array on submit
I have this bootstrap modal view:

      <form method = "POST" action = "<?php echo base_url('Monitor/myfct') ?>">

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Add missed Tara or Harvest Product

            Select event type

            <select data-placeholder="Select" class="form-control chosen-select" style="width:350px;" tabindex="2">
              <option value="Tara">
                Tara Machine
              </option>
              <option value="Harvest">
                Harvest Product Machine
              </option>
            </select>

            Product list

            <select id ="harvestAjaxData" data-placeholder="Select" class="form-control chosen-select" style="width:350px;" tabindex="2">
            </select>

            Machine list

            <select id ="machineAjaxData" data-placeholder="Select" class="form-control chosen-select" style="width:350px;" tabindex="2">
            </select>

    Impurities
    <input type="text" class="form-control" id="inputimpurities" placeholder="Impurities" style="width:350px;">

    Humidity
    <input type="text" class="form-control" id="inputhumidity" placeholder="Humidity" style="width:350px;">

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-primary">Save changes</button>

      </form>

```
</div>
</div>
</p>

<p>Except first one, fields are completed on ajax call with dynamic data (coming from mysql tables) and 2 user input fields, and the controller function where I send that form is this one Monitor/myfct:</p>

```public function myfct() {
        $data= $this->input->post();
        print_r($data);
        echo '';
    }
```

<p>I use it to test my form submit, I get the javascript alert(so the call was successful), but the print $data comes with a empty Array, also tried to print $_POST, same output. What is wrong in my modal view? Should I put the name="" for the options?</p>

<p>ps. I should add how the options from ajax look like:</p>

```for(var i = 0; i< data.length;i++){

  $('#harvestAjaxData').append('<option value="'+data[i]['name']+'">'+data[i]['name']+'</option>');
}
```

答: Try giving name attributes to selects</p>

Body:
I have this bootstrap modal view:

      <form method = "POST" action = "<?php echo base_url('Monitor/myfct') ?>">

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Add missed Tara or Harvest Product

            Select event type

            <select data-placeholder="Select" class="form-control chosen-select" style="width:350px;" tabindex="2">
              <option value="Tara">
                Tara Machine
              </option>
              <option value="Harvest">
                Harvest Product Machine
              </option>
            </select>

            Product list

            <select id ="harvestAjaxData" data-placeholder="Select" class="form-control chosen-select" style="width:350px;" tabindex="2">
            </select>

            Machine list

            <select id ="machineAjaxData" data-placeholder="Select" class="form-control chosen-select" style="width:350px;" tabindex="2">
            </select>

    Impurities
    <input type="text" class="form-control" id="inputimpurities" placeholder="Impurities" style="width:350px;">

    Humidity
    <input type="text" class="form-control" id="inputhumidity" placeholder="Humidity" style="width:350px;">

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-primary">Save changes</button>

      </form>

Except first one, fields are completed on ajax call with dynamic data (coming from mysql tables) and 2 user input fields, and the controller function where I send that form is this one Monitor/myfct:

public function myfct() {
        $data= $this->input->post();
        print_r($data);
        echo '';
    }

I use it to test my form submit, I get the javascript alert(so the call was successful), but the print $data comes with a empty Array, also tried to print $_POST, same output. What is wrong in my modal view? Should I put the name="" for the options?

ps. I should add how the options from ajax look like:

for(var i = 0; i< data.length;i++){

  $('#harvestAjaxData').append('<option value="'+data[i]['name']+'">'+data[i]['name']+'</option>');
}

Body: Try giving name attributes to selects


问:
Breeze's errorCallback function is never called
If I call a web API method (which throws an exception) using breeze's executeQuery method (Breeze version is 1.6.3), the errorCallback function is never called.

```<code>var eq = new breeze.EntityQuery('TestError');
manager.executeQuery(
    eq,
    function(data) { console.log('success') },
    function(err) { console.log('error') }
);
</code>```

this is the api method

```<code>[HttpGet]
public void TestError() {
    throw new Exception("test exception");
}
</code>```

nor does it work with what is described here (see executeQuery method)

My app uses Aurelia and the aurelia-breeze plugin, and I suppose this problem happens because aurelia-breeze replaces Q with ES6 Promises.
Is it possible to have the errorCallback called anyway? Or am I just doing something wrong?

Here is my original post on the aurelia-breeze github page

答: I have solved it (at least I think so), by adding an extra .catch() in an inner Promise in aurelia-breeze's source files. Details here</p>

Body:
If I call a web API method (which throws an exception) using breeze's executeQuery method (Breeze version is 1.6.3), the errorCallback function is never called.

var eq = new breeze.EntityQuery('TestError');
manager.executeQuery(
    eq,
    function(data) { console.log('success') },
    function(err) { console.log('error') }
);

this is the api method

[HttpGet]
public void TestError() {
    throw new Exception("test exception");
}

nor does it work with what is described here (see executeQuery method)

My app uses Aurelia and the aurelia-breeze plugin, and I suppose this problem happens because aurelia-breeze replaces Q with ES6 Promises.
Is it possible to have the errorCallback called anyway? Or am I just doing something wrong?

Here is my original post on the aurelia-breeze github page


问:
does Tcl TSV support passing dictionaries
I would like to share a dict type variable through TSV, but the TSV documentation doesn't show any support for DICT.  Is there perhaps some alternate way to share a DICT variable through threads?</p>

答:
The TSV sub-package doesn't specifically have support for it; you'd usually use a tsv::array for that sort of thing. However, you can also just bring the value in as a string inside a lock, process as a dictionary, and write the result back.

```<code># assuming that the main thread shared variable is called FOO and we're using the BAR element of it
tsv::lock FOO {
    # Read the dictionary out
    set mycopy [tsv::get FOO BAR]
    # Do some complicated operation
    dict set mycopy "grill" [expr {2**[dict get $mycopy "quux"]}]
    # Write the updated dictionary back
    tsv::set FOO BAR $mycopy
}
</code>```

In many ways, the list-based commands like tsv::lappend are wrappers around the basic get/set pattern rather like that, except the wrappers are written in C for you. (The TSV sub-package is rather old — the API it presents makes me think it has a similar age-of-last-update to Tcl 8.4 — and doesn't provide specific operations for dictionaries.)

Body:
The TSV sub-package doesn't specifically have support for it; you'd usually use a tsv::array for that sort of thing. However, you can also just bring the value in as a string inside a lock, process as a dictionary, and write the result back.

# assuming that the main thread shared variable is called FOO and we're using the BAR element of it
tsv::lock FOO {
    # Read the dictionary out
    set mycopy [tsv::get FOO BAR]
    # Do some complicated operation
    dict set mycopy "grill" [expr {2**[dict get $mycopy "quux"]}]
    # Write the updated dictionary back
    tsv::set FOO BAR $mycopy
}

In many ways, the list-based commands like tsv::lappend are wrappers around the basic get/set pattern rather like that, except the wrappers are written in C for you. (The TSV sub-package is rather old — the API it presents makes me think it has a similar age-of-last-update to Tcl 8.4 — and doesn't provide specific operations for dictionaries.)


问:
How to implement Left or right outer join in QueryDsl
How to implement  Left or right outer join in QueryDsl. A simple example is helpful.

答:
You should use leftJoin method for that sake.
E.g.:

```<code>queryUtil
    .createJpaQuery()
    .from(t1)
    .leftJoin(t1.t2, t2)
    .fetchJoin()
    .where(t2.a.eq(t1.t2.a))
    .fetchAll()
</code>```

Body:
You should use leftJoin method for that sake.
E.g.:

queryUtil
    .createJpaQuery()
    .from(t1)
    .leftJoin(t1.t2, t2)
    .fetchJoin()
    .where(t2.a.eq(t1.t2.a))
    .fetchAll()


答:
event.data its wrong syntax .if you need a value of the textarea use

```<code> console.log(event.target.value);
</code>```

or

```<code> function checkLastCharacter(event,this){
  console.log(this.value);
}
</code>```

function checkLastCharacter(event){
  console.log(event.target.value);
}

$( document ).ready(function() {
    console.log( "ready!" );
    //$( "#update" ).click(updateClick);
    var text=document.getElementById("text");
    text.addEventListener("input", checkLastCharacter);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="text" rows="4" cols="50">
     ASfadfasbncaksjb
 </textarea></code>```

Title: Accessing event.data from handler of input on textarea

Body:
I've been looking arround for a couple of days on this matter.

For some background I will explain the objective:
  I have a textarea and I want that when I type some special character defined by me (like @) it detects it as a part of a dictionary and show an autocomplete floating dive to choose from and if it's not in the dictionary it adds it.

The current status / problem is that I'm trying to capture the changes in the textarea with the input event and it works, it runs the handler code exactly when I want but I'm not able to access the data.

I guess I could capture the paste event and the key up events and take the clipboard from one and the key code from the other but I wonder if there is a way I can do it with the input event.

Here the relevant code:

function checkLastCharacter(event){
  console.log(event);
}

$( document ).ready(function() {
    console.log( "ready!" );
    //$( "#update" ).click(updateClick);
    var text=document.getElementById("text");
    text.addEventListener("input", checkLastCharacter);
});

<textarea id="text" rows="4" cols="50">Sample text</textarea>

Result of execution: No mater what key I press or if I paste or not anything it shows:

"event: undefined"

Thanks in advance!

Body:
event.data its wrong syntax .if you need a value of the textarea use

 console.log(event.target.value);

or

 function checkLastCharacter(event,this){
  console.log(this.value);
}

function checkLastCharacter(event){
  console.log(event.target.value);
}

$( document ).ready(function() {
    console.log( "ready!" );
    //$( "#update" ).click(updateClick);
    var text=document.getElementById("text");
    text.addEventListener("input", checkLastCharacter);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="text" rows="4" cols="50">
     ASfadfasbncaksjb
 </textarea>


问:
How can I inject Location in angular2?
I thought it would be the same way to inject Location just like how I inject Http. However my app breaks - the page does not render, if I uncomment "public location: Location" in the last line. As far as I can see, I have the correct import and providers array:

```<code>import {Component} from 'angular2/core';
import {
    ROUTER_DIRECTIVES,
    ROUTER_PROVIDERS,
    RouteConfig,
    Location,
    LocationStrategy,
    HashLocationStrategy
} from 'angular2/router';

import {TaskForm} from './task_form';
import {TaskList} from './task_list';
import {AboutUs} from './about_us';

@Component({
    selector: 'task-app',
    templateUrl: 'app/task_app.html',
    providers: [ROUTER_PROVIDERS],
    directives: [TaskForm, TaskList, ROUTER_DIRECTIVES]
})
@RouteConfig([
    {path: '/', component: TaskApp, as: 'Home'},
    {path: '/about_us', component: AboutUs, as: 'aboutUs'}
])
export class TaskApp {
    constructor(/*public location: Location*/) {
</code>```

In my index.html, I have the following line:

```<code><script src="https://code.angularjs.org/2.0.0-beta.0/router.dev.js"></script>
</code>```

In my bootstrap code, I have:

```<code>import {bootstrap} from 'angular2/platform/browser';
import {HTTP_PROVIDERS} from 'angular2/http';
import {provide} from 'angular2/core';

import {
    ROUTER_DIRECTIVES,
    ROUTER_PROVIDERS,
    RouteConfig,
    Location,
    LocationStrategy,
    HashLocationStrategy
} from 'angular2/router';

import {TaskApp} from './task_app';
import {MyService} from './my_service'

bootstrap(TaskApp, [HTTP_PROVIDERS, ROUTER_PROVIDERS, MyService, provide(LocationStrategy, {useClass: HashLocationStrategy})]);
</code>```

Not sure whether I missed something or the current build is broken. If it is the first case, what did I miss?

答:
in your NgModule

```<code>  providers: [
     { provide: 'locationObject', useValue: location}
  ]
</code>```

in your component you need to Inject it so

```<code>import { Component, Inject } from '@angular/core';

 constructor(
     @Inject('locationObject') private locationObject: Location
 ) {}
</code>```

Title: How can I inject Location in angular2?

Body:
I thought it would be the same way to inject Location just like how I inject Http. However my app breaks - the page does not render, if I uncomment "public location: Location" in the last line. As far as I can see, I have the correct import and providers array:

import {Component} from 'angular2/core';
import {
    ROUTER_DIRECTIVES,
    ROUTER_PROVIDERS,
    RouteConfig,
    Location,
    LocationStrategy,
    HashLocationStrategy
} from 'angular2/router';

import {TaskForm} from './task_form';
import {TaskList} from './task_list';
import {AboutUs} from './about_us';

@Component({
    selector: 'task-app',
    templateUrl: 'app/task_app.html',
    providers: [ROUTER_PROVIDERS],
    directives: [TaskForm, TaskList, ROUTER_DIRECTIVES]
})
@RouteConfig([
    {path: '/', component: TaskApp, as: 'Home'},
    {path: '/about_us', component: AboutUs, as: 'aboutUs'}
])
export class TaskApp {
    constructor(/*public location: Location*/) {

In my index.html, I have the following line:

In my bootstrap code, I have:

import {bootstrap} from 'angular2/platform/browser';
import {HTTP_PROVIDERS} from 'angular2/http';
import {provide} from 'angular2/core';

import {
    ROUTER_DIRECTIVES,
    ROUTER_PROVIDERS,
    RouteConfig,
    Location,
    LocationStrategy,
    HashLocationStrategy
} from 'angular2/router';

import {TaskApp} from './task_app';
import {MyService} from './my_service'

bootstrap(TaskApp, [HTTP_PROVIDERS, ROUTER_PROVIDERS, MyService, provide(LocationStrategy, {useClass: HashLocationStrategy})]);

Not sure whether I missed something or the current build is broken. If it is the first case, what did I miss?

Body:
in your NgModule

  providers: [
     { provide: 'locationObject', useValue: location}
  ]

in your component you need to Inject it so

import { Component, Inject } from '@angular/core';

 constructor(
     @Inject('locationObject') private locationObject: Location
 ) {}