问:
The angular2-mdl tooltip is appearing obfuscated
I'm using angular2-mdl and applying the tooltip to header items.

But the tooltip is looking obfuscated.

Nothing was added on purpose for this to happen.

See the index.html:

```<code><!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>App Title</title>
  <base href="/">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <!-- Page styles -->
  <link rel="stylesheet" href="https://code.getmdl.io/1.1.3/material.indigo-red.min.css" />
  <!-- Fonts -->
  <link href='https://fonts.googleapis.com/css?family=Roboto:regular,bold,italic,thin,light,bolditalic,black,medium&lang=en' rel='stylesheet' type='text/css'>
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body>
  <app-root>Loading...</app-root>

  <!-- IE Compatibility shims -->
    <!--[if lt IE 9]>
      <script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.2/html5shiv.min.js""></script>
    <![endif]-->
    <!--[if IE]>
      <script src="//cdnjs.cloudflare.com/ajax/libs/es5-shim/4.1.7/es5-shim.min.js"></script>
      <script src="//cdnjs.cloudflare.com/ajax/libs/classlist/2014.01.31/classList.min.js"></script>
      <script src="//cdnjs.cloudflare.com/ajax/libs/selectivizr/1.0.2/selectivizr-min.js"></script>
      <script src="//cdnjs.cloudflare.com/ajax/libs/flexie/1.0.3/flexie.min.js"></script>
      <link href="./assets/ie.css" rel="stylesheet">
    <![endif]-->
  <!-- end shims -->
</body>
</html>
</code>```

And another part´s of app:

styles.css:

```<code>/* You can add global styles to this file, and also import other style files */
mdl-layout mdl-layout-header nav button.mdl-button--icon {
  margin-left: 10px;
  margin-right: 10px;
}
</code>```

The app.module.ts:

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { MdlModule } from '@angular-mdl/core';

import { routing } from './app.routing';

import { AppComponent } from './app.component';
import { MainComponent } from './layout/main/main.component';

@NgModule({
  declarations: [
    AppComponent,
    MainComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    MdlModule,
    routing
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

app.routing.ts:

```<code>import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { MainComponent } from "app/layout/main/main.component";

const APP_ROUTES: Routes = [

  { path: '', component: MainComponent },

];
</code>```

```<code>export const routing: ModuleWithProviders = RouterModule.forRoot(APP_ROUTES);
</code>```

and main.component.ts:

```<code><mdl-layout mdl-layout-fixed-header mdl-layout-fixed-drawer>
  <mdl-layout-header>
    <mdl-layout-header-row>
      <mdl-layout-title>App Title</mdl-layout-title>
      <mdl-layout-spacer></mdl-layout-spacer>
      <nav class="mdl-navigation">
        <button mdl-button mdl-button-type="icon" mdl-tooltip-large="Notificações"><mdl-icon>notifications</mdl-icon></button>
        <button mdl-button mdl-button-type="icon" mdl-tooltip-large="Usuário"><mdl-icon>account_circle</mdl-icon></button>

        <button mdl-button #btnSettings="mdlButton" (click)="menuSettings.toggle($event, btnSettings)" mdl-button-type="icon" mdl-ripple mdl-tooltip-large="Opções"><mdl-icon>more_vert</mdl-icon></button>
        <mdl-menu #menuSettings="mdlMenu" mdl-menu-position="bottom-left">
          <mdl-menu-item>Some Action</mdl-menu-item>
          <mdl-menu-item mdl-menu-item-full-bleed-divider>Another Action</mdl-menu-item>
          <mdl-menu-item disabled>Disabled Action</mdl-menu-item>
          <mdl-menu-item>Yet Another Action</mdl-menu-item>
        </mdl-menu>

        <button mdl-button mdl-button-type="icon" mdl-tooltip-large="Logout"><mdl-icon>power_settings_new</mdl-icon></button>
      </nav>
    </mdl-layout-header-row>
  </mdl-layout-header>
  <mdl-layout-drawer>
    <mdl-layout-title>App Title</mdl-layout-title>
    <nav class="mdl-navigation">
      <a class="mdl-navigation__link">Link</a>
      <a class="mdl-navigation__link">Link</a>
      <a class="mdl-navigation__link">Link</a>
    </nav>
  </mdl-layout-drawer>
  <mdl-layout-content>
    <!-- Your content goes here -->
  </mdl-layout-content>
</mdl-layout>
</code>```

The app.component.ts has only the route-outlet.

What was rendered, part 1:

Part 2:

What is wrong?

答:
Solved with:

```<code>.mdl-tooltip {
    will-change: unset;
}

.mdl-snackbar {
  will-change: unset;
}
</code>```

As in https://github.com/mseemann/angular2-mdl/issues/1004

Body:
I'm using angular2-mdl and applying the tooltip to header items.

But the tooltip is looking obfuscated.

Nothing was added on purpose for this to happen.

See the index.html:

<!doctype html>

  <meta charset="utf-8">
  <title>App Title</title>
  <base href="/">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

  <link rel="stylesheet" href="https://code.getmdl.io/1.1.3/material.indigo-red.min.css" />

  <link href='https://fonts.googleapis.com/css?family=Roboto:regular,bold,italic,thin,light,bolditalic,black,medium&lang=en' rel='stylesheet' type='text/css'>
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

  <app-root>Loading...</app-root>

And another part´s of app:

styles.css:

/* You can add global styles to this file, and also import other style files */
mdl-layout mdl-layout-header nav button.mdl-button--icon {
  margin-left: 10px;
  margin-right: 10px;
}

The app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { MdlModule } from '@angular-mdl/core';

import { routing } from './app.routing';

import { AppComponent } from './app.component';
import { MainComponent } from './layout/main/main.component';

@NgModule({
  declarations: [
    AppComponent,
    MainComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    MdlModule,
    routing
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.routing.ts:

import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { MainComponent } from "app/layout/main/main.component";

const APP_ROUTES: Routes = [

  { path: '', component: MainComponent },

];

export const routing: ModuleWithProviders = RouterModule.forRoot(APP_ROUTES);

and main.component.ts:

<mdl-layout mdl-layout-fixed-header mdl-layout-fixed-drawer>
  <mdl-layout-header>
    <mdl-layout-header-row>
      <mdl-layout-title>App Title</mdl-layout-title>
      <mdl-layout-spacer></mdl-layout-spacer>

        <button mdl-button mdl-button-type="icon" mdl-tooltip-large="Notificações"><mdl-icon>notifications</mdl-icon></button>
        <button mdl-button mdl-button-type="icon" mdl-tooltip-large="Usuário"><mdl-icon>account_circle</mdl-icon></button>

        <button mdl-button #btnSettings="mdlButton" (click)="menuSettings.toggle($event, btnSettings)" mdl-button-type="icon" mdl-ripple mdl-tooltip-large="Opções"><mdl-icon>more_vert</mdl-icon></button>
        <mdl-menu #menuSettings="mdlMenu" mdl-menu-position="bottom-left">
          <mdl-menu-item>Some Action</mdl-menu-item>
          <mdl-menu-item mdl-menu-item-full-bleed-divider>Another Action</mdl-menu-item>
          <mdl-menu-item disabled>Disabled Action</mdl-menu-item>
          <mdl-menu-item>Yet Another Action</mdl-menu-item>
        </mdl-menu>

        <button mdl-button mdl-button-type="icon" mdl-tooltip-large="Logout"><mdl-icon>power_settings_new</mdl-icon></button>

    </mdl-layout-header-row>
  </mdl-layout-header>
  <mdl-layout-drawer>
    <mdl-layout-title>App Title</mdl-layout-title>

      Link
      Link
      Link

  </mdl-layout-drawer>
  <mdl-layout-content>

  </mdl-layout-content>
</mdl-layout>

The app.component.ts has only the route-outlet.

What was rendered, part 1:

Part 2:

What is wrong?

Body:
Solved with:

.mdl-tooltip {
    will-change: unset;
}

.mdl-snackbar {
  will-change: unset;
}

As in https://github.com/mseemann/angular2-mdl/issues/1004


来源: stackexchange

问:
Where are jQuery UI colors and widget styles set?
When you download jQuery UI from the jQuery web site, you get a file of javascript code and a file of css code.

I understand that CSS code has to do with various elements of the style and appearance of various web page elements.

I would like to know if there is anything having to do with the style of the jQuery elements that is part of the jQuery UI javascript code.  Can I rip and replace the css file to change the style of the jQuery elements on my web site, or are there some parts of the style hard-coded into the javascript code?

答:
None of it is hard coded in the javascript files.  If you were to remove the CSS, your widgets will lose all styling, including positioning.

jQuery UI uses a css framework.  You can freely edit these files to change the look and feel of the theme-rolled elements, but good luck!  A lot of the classes are interdependent.  On the other hand, jQuery UI adds all needed classes to the elements when the widgets are activated, so as long as you dive in and learn what's going on, you should be able to figure things out.

I would recommend using the themeroller to get the styles as close as possible to what you want, and then tweaking the css from there.

ContentLicense: CC BY-SA 2.5


问:
SAS - Custom Date Format - YYYYMMDDhhmmss
I need to add a current date to the output I am exporting from SAS in the following format: filename_YYYYMMDDhhmmss.csv

I am creating a macro variable the following way:

```<code>%let date_human = %sysfunc(today(), YYYYMMDDn8.);
</code>```

Does anybody know how to create a custom format for the date I have got? datetime20. gives an incorrect one.

Thank you.

答:
Use the B8601 formats.</p>

```<code>%let now=%sysfunc(datetime());
%let date_human=%sysfunc(putn(&now,B8601DN8))%sysfunc(timepart(&now),B8601TM6);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need to add a current date to the output I am exporting from SAS in the following format: filename_YYYYMMDDhhmmss.csv

I am creating a macro variable the following way:

%let date_human = %sysfunc(today(), YYYYMMDDn8.);

Does anybody know how to create a custom format for the date I have got? datetime20. gives an incorrect one.

Thank you.

Body:
Use the B8601 formats.

%let now=%sysfunc(datetime());
%let date_human=%sysfunc(putn(&now,B8601DN8))%sysfunc(timepart(&now),B8601TM6);


问:
Rails - Saving external API call to DB
I'm making a GET call to an external source (a Spree Commerce store) for getting the list of orders... the call is working fine but I need to save the order list to my rails app's db. I have no idea how to do this.

My Controller:

```<code>def index
  # GRAB THE URL
  url = 'https://cuytest1.herokuapp.com/api/v1/orders.json?token=982fe19b763ee46bf1ea6ca6ddf70c61f2b6571c7434c22c'
  response = HTTParty.get(url)

  # PARSE THE RESPONSE
  @orders = response.parsed_response["orders"]
end
</code>```

My model:

```<code>class Order < ApplicationRecord
  include HTTParty
end
</code>```

My view:

```<code><p id="notice"><%= notice %></p>

<h1>Orders</h1>

<table>
  <thead>
    <tr>
      <th>Number</th>
      <th>Total</th>
      <th>State</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @orders.each do |order| %>
      <tr>
        <td><%= order["number"] %></td>
        <td><%= order["total"] %></td>
        <td><%= order["shipment_state"] %></td>

      </tr>
    <% end %>
  </tbody>
</table>
</code>```

If anyone can point me into the right direction will be appreciated. Thanks a lot!

答:
```<code># Create a new Orders table w/ a `details` column of JSON type
class CreateOrders < ActiveRecord::Migration
  def change
    create_table :orders do |t|
     t.json :details
    end
  end
end

# And a corresponding model
class Order < ApplicationRecord
end

# Then when you're fetching those orders:
Order.new(details: fetched_order_record)

# That might look something like this in practice:
client = Spree::Client.new(...)
orders = client.orders.parsed_response
orders.each do |order_hash|
  Order.create! details: order_hash
end

# Later when you load from the database
order = Order.first
order.details['total']
</code>```

Title: Rails - Saving external API call to DB

Body:
I'm making a GET call to an external source (a Spree Commerce store) for getting the list of orders... the call is working fine but I need to save the order list to my rails app's db. I have no idea how to do this.

My Controller:

def index
  # GRAB THE URL
  url = 'https://cuytest1.herokuapp.com/api/v1/orders.json?token=982fe19b763ee46bf1ea6ca6ddf70c61f2b6571c7434c22c'
  response = HTTParty.get(url)

  # PARSE THE RESPONSE
  @orders = response.parsed_response["orders"]
end

My model:

class Order < ApplicationRecord
  include HTTParty
end

My view:

<%= notice %>

Orders

      Number
      Total
      State

    <% @orders.each do |order| %>

        <%= order["number"] %>
        <%= order["total"] %>
        <%= order["shipment_state"] %>

    <% end %>

If anyone can point me into the right direction will be appreciated. Thanks a lot!


问:
Numpy slogdet computation error
There appears to be a major difference between numpy's slogdet and the exact result when computing the log determinant of Vanermonde matrix.

I compare against the exact log determinant, see eg here for proof.

The minimal code to see this is:

```<code>A = np.power.outer(np.linspace(0,1,50),range(50))

print np.linalg.slogdet(A)[1]

s = 0
for v1 in np.linspace(0,1,50):
    for v2 in np.linspace(0,1,50):
        if v1>v2:
            s+= np.log(v1-v2)

print s
</code>```

Which yeilds:

```<code>-1191.88408998
-1706.99560647
</code>```

I was wondering if there was a more accurate log determinant implementation which I could use in this situation but also in non-Vandermonde matrix situation.

答:
You can use sympy and mpmath like this:

```<code>import numpy as np
import sympy as smp
import mpmath as mp

mp.mp.dps = 50

linspace1 = list(map(smp.mpmath.mpf,np.linspace(0,1,50)))
A = np.power.outer(list(map(float,linspace1)),range(50))

first_print = smp.mpmath.mpf(np.linalg.slogdet(A)[1])
print(first_print)

s = 0
linspace2 = list(map(smp.mpmath.mpf,np.linspace(0,1,50)))
linspace3 = list(map(smp.mpmath.mpf,np.linspace(0,1,50)))
for v1 in linspace1:
    for v2 in linspace2:
        if v1>v2:
            s+= mp.log(v1-v2)

print(s)
</code>```

RESULTS

```<code>first_print = -1178.272517342130186079884879291057586669921875

s = -1706.9956064674289001970168329846189154212781094939
</code>```

Title: Numpy slogdet computation error

Body:
There appears to be a major difference between numpy's slogdet and the exact result when computing the log determinant of Vanermonde matrix.

I compare against the exact log determinant, see eg here for proof.

The minimal code to see this is:

A = np.power.outer(np.linspace(0,1,50),range(50))

print np.linalg.slogdet(A)[1]

s = 0
for v1 in np.linspace(0,1,50):
    for v2 in np.linspace(0,1,50):
        if v1>v2:
            s+= np.log(v1-v2)

print s

Which yeilds:

-1191.88408998
-1706.99560647

I was wondering if there was a more accurate log determinant implementation which I could use in this situation but also in non-Vandermonde matrix situation.

Body:
You can use sympy and mpmath like this:

import numpy as np
import sympy as smp
import mpmath as mp

mp.mp.dps = 50

linspace1 = list(map(smp.mpmath.mpf,np.linspace(0,1,50)))
A = np.power.outer(list(map(float,linspace1)),range(50))

first_print = smp.mpmath.mpf(np.linalg.slogdet(A)[1])
print(first_print)

s = 0
linspace2 = list(map(smp.mpmath.mpf,np.linspace(0,1,50)))
linspace3 = list(map(smp.mpmath.mpf,np.linspace(0,1,50)))
for v1 in linspace1:
    for v2 in linspace2:
        if v1>v2:
            s+= mp.log(v1-v2)

print(s)

RESULTS

first_print = -1178.272517342130186079884879291057586669921875

s = -1706.9956064674289001970168329846189154212781094939


问:
how to find totally duplicate object in array?
Here is an example js array:

```<code>var arr = [
  {
    name: 'test1',
    price: 20,
    otherKey: 123,
    yetAnotherKey: 'val'
  },
  {
    name: 'test2',
    price: 10,
    otherKey: 11,
    yetAnotherKey: 'erewrwert'
  },
  {
    name: 'test1',
    price: 20,
    otherKey: 123,
    yetAnotherKey: 'val'
  }
]
</code>```

Is there a way to find duplicate object (by all key/value pairs)?
If so - how to do that?
Thanks in advance.

答:
There are many subjects on the matter, from deep mapping to external libraries (underscore is recommendable), but most often a JSON string is used. Not optimal, but easiest in use. Combined with an ES6 Set, the unique objects can be obtained with:

```<code>arr = [...new Set(arr.map(JSON.stringify))].map(JSON.parse);
</code>```

var arr = [
  {
    name: 'test1',
    price: 20,
    otherKey: 123,
    yetAnotherKey: 'val'
  },
  {
    name: 'test2',
    price: 10,
    otherKey: 11,
    yetAnotherKey: 'erewrwert'
  },
  {
    name: 'test1',
    price: 20,
    otherKey: 123,
    yetAnotherKey: 'val'
  }
];

arr = [...new Set(arr.map(JSON.stringify))].map(JSON.parse);

console.log(arr);```

Body:
Here is an example js array:

var arr = [
  {
    name: 'test1',
    price: 20,
    otherKey: 123,
    yetAnotherKey: 'val'
  },
  {
    name: 'test2',
    price: 10,
    otherKey: 11,
    yetAnotherKey: 'erewrwert'
  },
  {
    name: 'test1',
    price: 20,
    otherKey: 123,
    yetAnotherKey: 'val'
  }
]

Is there a way to find duplicate object (by all key/value pairs)?
If so - how to do that?
Thanks in advance.

Body:
There are many subjects on the matter, from deep mapping to external libraries (underscore is recommendable), but most often a JSON string is used. Not optimal, but easiest in use. Combined with an ES6 Set, the unique objects can be obtained with:

arr = [...new Set(arr.map(JSON.stringify))].map(JSON.parse);

var arr = [
  {
    name: 'test1',
    price: 20,
    otherKey: 123,
    yetAnotherKey: 'val'
  },
  {
    name: 'test2',
    price: 10,
    otherKey: 11,
    yetAnotherKey: 'erewrwert'
  },
  {
    name: 'test1',
    price: 20,
    otherKey: 123,
    yetAnotherKey: 'val'
  }
];

arr = [...new Set(arr.map(JSON.stringify))].map(JSON.parse);

console.log(arr);


问:
Subtract current rows second element from the next rows first element in numpy
I have 6x2 numpy array. I want to subtract current rows second element from the next rows first element and get the new column.
Currently i'm using for loop to do that.
Ex:

```<code>from numpy import array
a = array([[1,3],
           [2,5],
           [6,7],
           [8,9],
           [5,6],
           [6,9]])
k = []
for i in range(a.shape[0]-1):
    k.append(a[i][1]-a[i+1][0])
array(k)
</code>```

Output : [1, -1, -1, 4, 0]

How can I get the same output using numpy?

答:
Slice and subtract -

```<code>a[1:,0] - a[:-1,1]
</code>```

Sample run -

```<code>In [303]: a
Out[303]:
array([[1, 3],
       [2, 5],
       [6, 7],
       [8, 9],
       [5, 6],
       [6, 9]])

In [304]: a[1:,0] - a[:-1,1]
Out[304]: array([-1,  1,  1, -4,  0])
</code>```

Since, we have two columns only, another way/trick would be to use differentiaton on flattened version and then step into every other element starting from the second element -

```<code>In [308]: np.diff(a.ravel())[1::2]
Out[308]: array([-1,  1,  1, -4,  0])
</code>```

Body:
I have 6x2 numpy array. I want to subtract current rows second element from the next rows first element and get the new column.
Currently i'm using for loop to do that.
Ex:

from numpy import array
a = array([[1,3],
           [2,5],
           [6,7],
           [8,9],
           [5,6],
           [6,9]])
k = []
for i in range(a.shape[0]-1):
    k.append(a[i][1]-a[i+1][0])
array(k)

Output : [1, -1, -1, 4, 0]

How can I get the same output using numpy?

Body:
Slice and subtract -

a[1:,0] - a[:-1,1]

Sample run -

In [303]: a
Out[303]:
array([[1, 3],
       [2, 5],
       [6, 7],
       [8, 9],
       [5, 6],
       [6, 9]])

In [304]: a[1:,0] - a[:-1,1]
Out[304]: array([-1,  1,  1, -4,  0])

Since, we have two columns only, another way/trick would be to use differentiaton on flattened version and then step into every other element starting from the second element -

In [308]: np.diff(a.ravel())[1::2]
Out[308]: array([-1,  1,  1, -4,  0])


问:
Lookup between two ranges
Afternoon all, I'm working with two columns of data - one of these has an author name and the second has a publish date-time value. I'm looking to build up a UDF to take these two ranges, search the author column for a particular string and if found to return the value from the publish column.

Data looks similar to this;

Once it has found the author I'm looking for i want it to look at the publish time and find the minimum value for this.

For example, if i was looking for the author Ben in the above then the value returned should be 08/06/2014 17:15.

If the data i was working with was always in the same format then i would build up an array formula to create a MINIF but the columns these ranges show in are always different and the easiest option will be a UDF that the end user can just put the two ranges into.

Thanks in advance for any help.

Cheers

答:
Your UDF might be like this, no office 365 features needed:

```<code>Function MinDateByAuthor(author As String, rngNames As Range, rngDates As Range) As Date
  MinDateByAuthor = Application.Evaluate("Aggregate(15, 6," & _
    rngDates.Address(External:=True) & "/(" & _
    rngNames.Address(External:=True) & "=""" & author & """),1)")
End Function
</code>```

You can use it like =MinDateByAuthor("Ben", A2:A100, B2:B100)

You can also place some cell address instead of the hardcoded "Ben".

TBH, all your UDF has done is facilitate a little bit typing the initial formula.
And you might want to make it even easier, by allowing full column references (A:A, B:B) without sensitive slowness. In the above UDF you can do that, but as suggested by @ScottCraner, we can make it work faster:

```<code>Function MinDateByAuthor2(author As String, ByVal rngNames As Range, ByVal rngDates As Range) As Date
  Set rngNames = Intersect(rngNames, rngNames.Parent.UsedRange)
  Set rngDates = Intersect(rngDates, rngDates.Parent.UsedRange)

  ' The rest is the same ...
  MinDateByAuthor2 = Application.Evaluate("Aggregate(15, 6," & _
    rngDates.Address(External:=True) & "/(" & _
    rngNames.Address(External:=True) & "=""" & author & """),1)")
End Function
</code>```

Here you will notice that =MinDateByAuthor2(A3,A:A,B:B) calculates faster than =MinDateByAuthor(A3,A:A,B:B).

Title: Lookup between two ranges

Body:
Your UDF might be like this, no office 365 features needed:

Function MinDateByAuthor(author As String, rngNames As Range, rngDates As Range) As Date
  MinDateByAuthor = Application.Evaluate("Aggregate(15, 6," & _
    rngDates.Address(External:=True) & "/(" & _
    rngNames.Address(External:=True) & "=""" & author & """),1)")
End Function

You can use it like =MinDateByAuthor("Ben", A2:A100, B2:B100)

You can also place some cell address instead of the hardcoded "Ben".

TBH, all your UDF has done is facilitate a little bit typing the initial formula.
And you might want to make it even easier, by allowing full column references (A:A, B:B) without sensitive slowness. In the above UDF you can do that, but as suggested by @ScottCraner, we can make it work faster:

Function MinDateByAuthor2(author As String, ByVal rngNames As Range, ByVal rngDates As Range) As Date
  Set rngNames = Intersect(rngNames, rngNames.Parent.UsedRange)
  Set rngDates = Intersect(rngDates, rngDates.Parent.UsedRange)

  ' The rest is the same ...
  MinDateByAuthor2 = Application.Evaluate("Aggregate(15, 6," & _
    rngDates.Address(External:=True) & "/(" & _
    rngNames.Address(External:=True) & "=""" & author & """),1)")
End Function

Here you will notice that =MinDateByAuthor2(A3,A:A,B:B) calculates faster than =MinDateByAuthor(A3,A:A,B:B).


问:
Difference between public and private variables
```<code>namespace hi
{
    class hithere
    {
         public int numberOne = 12;
         private int numberTwo = 12;

         static void yo()
         {
         }
    }
}
</code>```

Can someone tell me the difference between the variables numberOne and numberTwo in this code excerpt?

答:
It means that if you have another class like this:

```<code>namespace hi
{
    class hithere2
    {
         static void yo2()
         {
             hithere h = new hithere();
             h.numberOne = 2;
             h.numberTwo = 3;
         }
    }
}
</code>```

The second one errors, but the first is OK.

Body:
namespace hi
{
    class hithere
    {
         public int numberOne = 12;
         private int numberTwo = 12;

         static void yo()
         {
         }
    }
}

Can someone tell me the difference between the variables numberOne and numberTwo in this code excerpt?

Body:
It means that if you have another class like this:

namespace hi
{
    class hithere2
    {
         static void yo2()
         {
             hithere h = new hithere();
             h.numberOne = 2;
             h.numberTwo = 3;
         }
    }
}

The second one errors, but the first is OK.


问:
Numbers bigger than 8 bytes in C
I am writing some code to deal with numbers in C which are bigger than 8 bytes in size (don't fit into unsigned long). In this example I will use 16 bytes (128 bits) as the width. The numbers are unsigned and integers (no decimal places). They are stored as an array of unsigned chars eg:

```<code>unsigned char n[16];
</code>```

I have managed to get addition to work (it works like an unsigned number in C so if you had a number which was 0xffffffffffffffffffffffffffffffff (2**128) and you were to add 1 you would get 0. I have managed to get addition to work, but I cannot get subtraction to work. I would assume it would be similar code to addition, but I don't seem to be able to get it to work.

Addition code:

```<code>//a and b are numbers
unsigned char *add(unsigned char *a, unsigned char *b){
    unsigned char *c = malloc(NUM_SIZE);
    //d is the carry and c is the output number
    unsigned short d = 0;

    if(!c){
        return NULL;
    }
    for(int i = 0; i < NUM_SIZE; i++){
        c[i] = 0;
    }
    for(int i = NUM_SIZE * 2 - 1; i >= 0; i--){
        d += a[i % NUM_SIZE] + b[i % NUM_SIZE];
        c[i % NUM_SIZE] = d % 256;
        d >>= 8;
    }
    return c;
}
</code>```

NUM_SIZE is defined as 16 (the width of the number in bytes)

What I have tried:

```<code>//changing the signs to minuses
d -= a[i % NUM_SIZE] - b[i % NUM_SIZE];

//changing the some signs to minuses
d -= a[i % NUM_SIZE] + b[i % NUM_SIZE];
//or
d += a[i % NUM_SIZE] - b[i % NUM_SIZE];

//looping through the number backwards
for(int i = 0; i < NUM_SIZE * 2; i++)
</code>```

答:
Just an idea (not compiled):</p>

```<code>void not( unsigned char* a, unsigned int n )
{
  for ( unsigned int i = 0; i < n; ++i )
    a[i] = ~a[i];
}

void inc( unsigned char* a, unsigned int n )
{
  for ( unsigned int i = 0; i < n; ++i )
    if ( ++a[i] )
      return;
}

void add( unsigned char* c, unsigned char* a, unsigned char* b, unsigned int n )
{
  for ( unsigned int i = 0, r = 0; i < n; ++i )
    c[i] = r = a[i] + b[i] + ( r >> 8 );
}

void sub( unsigned char* c, unsigned char* a, unsigned char* b, unsigned int n )
{
  not( b, n );
  add( c, a, b, n );
  not( b, n ); // revert
  inc( c, n );
}
</code>```

Title: Numbers bigger than 8 bytes in C

Body:
I am writing some code to deal with numbers in C which are bigger than 8 bytes in size (don't fit into unsigned long). In this example I will use 16 bytes (128 bits) as the width. The numbers are unsigned and integers (no decimal places). They are stored as an array of unsigned chars eg:

unsigned char n[16];

I have managed to get addition to work (it works like an unsigned number in C so if you had a number which was 0xffffffffffffffffffffffffffffffff (2**128) and you were to add 1 you would get 0. I have managed to get addition to work, but I cannot get subtraction to work. I would assume it would be similar code to addition, but I don't seem to be able to get it to work.

Addition code:

//a and b are numbers
unsigned char *add(unsigned char *a, unsigned char *b){
    unsigned char *c = malloc(NUM_SIZE);
    //d is the carry and c is the output number
    unsigned short d = 0;

    if(!c){
        return NULL;
    }
    for(int i = 0; i < NUM_SIZE; i++){
        c[i] = 0;
    }
    for(int i = NUM_SIZE * 2 - 1; i >= 0; i--){
        d += a[i % NUM_SIZE] + b[i % NUM_SIZE];
        c[i % NUM_SIZE] = d % 256;
        d >>= 8;
    }
    return c;
}

NUM_SIZE is defined as 16 (the width of the number in bytes)

What I have tried:

//changing the signs to minuses
d -= a[i % NUM_SIZE] - b[i % NUM_SIZE];

//changing the some signs to minuses
d -= a[i % NUM_SIZE] + b[i % NUM_SIZE];
//or
d += a[i % NUM_SIZE] - b[i % NUM_SIZE];

//looping through the number backwards
for(int i = 0; i < NUM_SIZE * 2; i++)

Body:
Just an idea (not compiled):

void not( unsigned char* a, unsigned int n )
{
  for ( unsigned int i = 0; i < n; ++i )
    a[i] = ~a[i];
}

void inc( unsigned char* a, unsigned int n )
{
  for ( unsigned int i = 0; i < n; ++i )
    if ( ++a[i] )
      return;
}

void add( unsigned char* c, unsigned char* a, unsigned char* b, unsigned int n )
{
  for ( unsigned int i = 0, r = 0; i < n; ++i )
    c[i] = r = a[i] + b[i] + ( r >> 8 );
}

void sub( unsigned char* c, unsigned char* a, unsigned char* b, unsigned int n )
{
  not( b, n );
  add( c, a, b, n );
  not( b, n ); // revert
  inc( c, n );
}


问:
django - Can't login after creating user
I can't login after create user. Here's my code:

```<code>class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'

    def create(self, validated_data):
        username = validated_data.pop('username')
        password = validated_data.pop('password')
        return User.objects.create_user(username, password, **validated_data)
</code>```

My api:

```<code>from django.contrib.auth.models import User
class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
</code>```

any help is appreciated.
Updated: Here's my test case

```<code>class UserAPITestCase(APITestCase):

def setUp(self):
    self.client = APIClient()

    self.user = User.objects.create_user(
        username='anhnguyen',
        password=PASSWORD,
    )
    self.user.save()

def test_create_user(self):
    data = {
        'username': 'khoavo',
        'password': PASSWORD,
    }

    user = self.client.post(URL, data, format='json')
    self.assertEqual(user.status_code, status.HTTP_201_CREATED)

    url = reverse(URL1, args=[2])
    response = self.client.get(url)
    self.assertEqual(response.status_code, status.HTTP_200_OK)

    login = self.client.login(username='khoavo', password=PASSWORD)
    self.assertTrue(login)
</code>```

The test case failed at login statement after creating a user

答:
self.client.login() is used for testing APIs that use session authentication. Make sure that you are using session authentication.

If you are using token based authentication instead, you should do like this:

```<code>client = APIClient()
client.credentials(HTTP_AUTHORIZATION='Token ' + token)
</code>```

Hope it helps.

Body:
I can't login after create user. Here's my code:

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'

    def create(self, validated_data):
        username = validated_data.pop('username')
        password = validated_data.pop('password')
        return User.objects.create_user(username, password, **validated_data)

My api:

from django.contrib.auth.models import User
class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

any help is appreciated.
Updated: Here's my test case

class UserAPITestCase(APITestCase):

def setUp(self):
    self.client = APIClient()

    self.user = User.objects.create_user(
        username='anhnguyen',
        password=PASSWORD,
    )
    self.user.save()

def test_create_user(self):
    data = {
        'username': 'khoavo',
        'password': PASSWORD,
    }

    user = self.client.post(URL, data, format='json')
    self.assertEqual(user.status_code, status.HTTP_201_CREATED)

    url = reverse(URL1, args=[2])
    response = self.client.get(url)
    self.assertEqual(response.status_code, status.HTTP_200_OK)

    login = self.client.login(username='khoavo', password=PASSWORD)
    self.assertTrue(login)

The test case failed at login statement after creating a user

Body:
self.client.login() is used for testing APIs that use session authentication. Make sure that you are using session authentication.

If you are using token based authentication instead, you should do like this:

client = APIClient()
client.credentials(HTTP_AUTHORIZATION='Token ' + token)

Hope it helps.


问:
How to use a view inside ASP.NET Core custom Tag Helper?
I have been following this Microsoft article on writing custom Tag Helpers here.

Every where i see code where the element markup is hard coded in C#

Example (taken from the above link)

```<code>public override void Process(TagHelperContext context, TagHelperOutput output)
{
     output.TagName = "section";
     output.Content.SetHtmlContent(
        $@"<ul><li><strong>Version:</strong> {Info.Version}</li>
        <li><strong>Copyright Year:</strong> {Info.CopyrightYear}</li>
        <li><strong>Approved:</strong> {Info.Approved}</li>
        <li><strong>Number of tags to show:</strong> {Info.TagsToShow}</li></ul>");
     output.TagMode = TagMode.StartTagAndEndTag;
}
</code>```

Instead of doing this, is there a way i can load the markup template from a cshtml file? (something similar to loading Partial Views)

My intention is to have individual cshtml files (one for each element type), so that i can style them easily. Also my C# would look clean!

Thanks,

James

答:
I've implemented something like this, but it takes a round about approach by creating a custom ViewRendering service with dependency injection and using that to render the view into a string.  I like this approach because it allows my app to use views for many things including email templates, taghelpers, and any other cases where I'd need to render a view into a string for use in code while also allowing me to pass a model to the view for more dynamic elements.

Interface defining the service:

public interface IViewRenderService
{
    string RenderView(string viewName);

    string RenderView<TModel>(string viewName, TModel model);

}
```

<p>Implementation of the service (the important part):</p>

<pre class="lang-cs prettyprint-override"><code>using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Routing;
using System;
using System.IO;

public class ViewRenderService : IViewRenderService
{
    private readonly IRazorViewEngine _viewEngine;
    private readonly ITempDataProvider _tempDataProvider;
    private readonly IServiceProvider _serviceProvider;

    public ViewRenderService(IRazorViewEngine viewEngine, ITempDataProvider tempDataProvider, IServiceProvider serviceProvider)
    {
        _viewEngine = viewEngine;
        _tempDataProvider = tempDataProvider;
        _serviceProvider = serviceProvider;
    }

    public string RenderView(string viewName)
    {
        var actionContext = GetActionContext();

        var viewEngineResult = _viewEngine.FindView(actionContext, viewName, false);

        if (!viewEngineResult.Success)
        {
            throw new InvalidOperationException(string.Format("Couldn't find view '{0}'", viewName));
        }

        var view = viewEngineResult.View;

        using (var output = new StringWriter())
        {
            var viewContext = new ViewContext(
                actionContext,
                view,
                new ViewDataDictionary(
                    metadataProvider: new EmptyModelMetadataProvider(),
                    modelState: new ModelStateDictionary()),
                new TempDataDictionary(
                    actionContext.HttpContext,
                    _tempDataProvider),
                output,
                new HtmlHelperOptions());

            view.RenderAsync(viewContext).GetAwaiter().GetResult();

            return output.ToString();
        }
    }

    public string RenderView<TModel>(string viewName, TModel model)
    {
        var actionContext = GetActionContext();

        var viewEngineResult = _viewEngine.FindView(actionContext, viewName, false);

        if (!viewEngineResult.Success)
        {
            throw new InvalidOperationException(string.Format("Couldn't find view '{0}'", viewName));
        }

        var view = viewEngineResult.View;

        using (var output = new StringWriter())
        {
            var viewContext = new ViewContext(
                actionContext,
                view,
                new ViewDataDictionary<TModel>(
                    metadataProvider: new EmptyModelMetadataProvider(),
                    modelState: new ModelStateDictionary())
                {
                    Model = model
                },
                new TempDataDictionary(
                    actionContext.HttpContext,
                    _tempDataProvider),
                output,
                new HtmlHelperOptions());

            view.RenderAsync(viewContext).GetAwaiter().GetResult();

            return output.ToString();
        }
    }

    private ActionContext GetActionContext()
    {
        var httpContext = new DefaultHttpContext();
        httpContext.RequestServices = _serviceProvider;
        return new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
    }
}
</code>```

Then in your Startup.cs

    public void ConfigureServices(IServiceCollection services)
    {
        ...

        services.AddTransient<IViewRenderService, ViewRenderService>();

        ...
    }
```

<p>Finally, you would use this in code like this (in this example a controller):</p>

<pre class="lang-cs prettyprint-override"><code>public class TestController : Controller
{
    private IViewRenderService viewRenderService;

    public TestController(IViewRenderService _viewRenderService)
    {
        viewRenderService = _viewRenderService;
    }

    public async Task<IActionResult> Index()
    {
        // code

        var stringOfView = viewRenderService.RenderView("EmailTemplate/EmailConfirmation");

        // code that does something with the view as a string

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

You can put your Views in the Views folder under their own folder (in the example above the view path is thus:  /Views/EmailTemplate/EmailConfirmation.cshtml)

If your view requires a model you would pass it in like so:

var stringOfView = viewRenderService.RenderView("folder/view", model);
```

Hope this helps!

Body:
I have been following this Microsoft article on writing custom Tag Helpers here.

Every where i see code where the element markup is hard coded in C#

Example (taken from the above link)

public override void Process(TagHelperContext context, TagHelperOutput output)
{
     output.TagName = "section";
     output.Content.SetHtmlContent(
        $@"

Version: {Info.Version}

Copyright Year: {Info.CopyrightYear}

Approved: {Info.Approved}

Number of tags to show: {Info.TagsToShow}

");
     output.TagMode = TagMode.StartTagAndEndTag;
}

Instead of doing this, is there a way i can load the markup template from a cshtml file? (something similar to loading Partial Views)

My intention is to have individual cshtml files (one for each element type), so that i can style them easily. Also my C# would look clean!

Thanks,

James

Body:
I've implemented something like this, but it takes a round about approach by creating a custom ViewRendering service with dependency injection and using that to render the view into a string.  I like this approach because it allows my app to use views for many things including email templates, taghelpers, and any other cases where I'd need to render a view into a string for use in code while also allowing me to pass a model to the view for more dynamic elements.

Interface defining the service:

public interface IViewRenderService
{
    string RenderView(string viewName);

    string RenderView<TModel>(string viewName, TModel model);

}

Implementation of the service (the important part):

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Routing;
using System;
using System.IO;

public class ViewRenderService : IViewRenderService
{
    private readonly IRazorViewEngine _viewEngine;
    private readonly ITempDataProvider _tempDataProvider;
    private readonly IServiceProvider _serviceProvider;

    public ViewRenderService(IRazorViewEngine viewEngine, ITempDataProvider tempDataProvider, IServiceProvider serviceProvider)
    {
        _viewEngine = viewEngine;
        _tempDataProvider = tempDataProvider;
        _serviceProvider = serviceProvider;
    }

    public string RenderView(string viewName)
    {
        var actionContext = GetActionContext();

        var viewEngineResult = _viewEngine.FindView(actionContext, viewName, false);

        if (!viewEngineResult.Success)
        {
            throw new InvalidOperationException(string.Format("Couldn't find view '{0}'", viewName));
        }

        var view = viewEngineResult.View;

        using (var output = new StringWriter())
        {
            var viewContext = new ViewContext(
                actionContext,
                view,
                new ViewDataDictionary(
                    metadataProvider: new EmptyModelMetadataProvider(),
                    modelState: new ModelStateDictionary()),
                new TempDataDictionary(
                    actionContext.HttpContext,
                    _tempDataProvider),
                output,
                new HtmlHelperOptions());

            view.RenderAsync(viewContext).GetAwaiter().GetResult();

            return output.ToString();
        }
    }

    public string RenderView<TModel>(string viewName, TModel model)
    {
        var actionContext = GetActionContext();

        var viewEngineResult = _viewEngine.FindView(actionContext, viewName, false);

        if (!viewEngineResult.Success)
        {
            throw new InvalidOperationException(string.Format("Couldn't find view '{0}'", viewName));
        }

        var view = viewEngineResult.View;

        using (var output = new StringWriter())
        {
            var viewContext = new ViewContext(
                actionContext,
                view,
                new ViewDataDictionary<TModel>(
                    metadataProvider: new EmptyModelMetadataProvider(),
                    modelState: new ModelStateDictionary())
                {
                    Model = model
                },
                new TempDataDictionary(
                    actionContext.HttpContext,
                    _tempDataProvider),
                output,
                new HtmlHelperOptions());

            view.RenderAsync(viewContext).GetAwaiter().GetResult();

            return output.ToString();
        }
    }

    private ActionContext GetActionContext()
    {
        var httpContext = new DefaultHttpContext();
        httpContext.RequestServices = _serviceProvider;
        return new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
    }
}

Then in your Startup.cs

    public void ConfigureServices(IServiceCollection services)
    {
        ...

        services.AddTransient<IViewRenderService, ViewRenderService>();

        ...
    }

Finally, you would use this in code like this (in this example a controller):

public class TestController : Controller
{
    private IViewRenderService viewRenderService;

    public TestController(IViewRenderService _viewRenderService)
    {
        viewRenderService = _viewRenderService;
    }

    public async Task<IActionResult> Index()
    {
        // code

        var stringOfView = viewRenderService.RenderView("EmailTemplate/EmailConfirmation");

        // code that does something with the view as a string

        return View();
    }
}

You can put your Views in the Views folder under their own folder (in the example above the view path is thus:  /Views/EmailTemplate/EmailConfirmation.cshtml)

If your view requires a model you would pass it in like so:

var stringOfView = viewRenderService.RenderView("folder/view", model);

Hope this helps!


答:
Some how I could to that using below trick:</p>

```<code>T1 <- rbind(as.data.frame.array(T1,T1))

Final Table$Value <- T1$Value[match(Final Table$Month,T1$Month)]
</code>```

Title: Matching values for reaped Key value in R

Body:
I have to two tables,T1 and T2 containing data, with unique key "Month".
Final Table is the required output.
I am getting output in T2 while using below code, is there any way to get same output.

Final Table$Value <- T1$Value[match(Final Table$Month, T1$Month)]

T1   T2   Final Table
Month Value  Month Value  Month Value
Dec-15 110.655  Dec-15 86.915  Dec-15 110.655
Dec-15 78.255  Dec-15 86.915  Dec-15 78.255
Dec-15 86.915  Dec-15 86.915  Dec-15 86.915
Jan-16 83.141  Dec-15 86.915  Dec-15 110.655
Jan-16 66.341  Dec-15 86.915  Dec-15 78.255
Jan-16 71.399  Dec-15 86.915  Dec-15 86.915
Feb-16 66.599  Jan-16 71.399  Jan-16 83.141
Feb-16 80.741  Jan-16 71.399  Jan-16 66.341
Feb-16 71.312  Jan-16 71.399  Jan-16 71.399
   Jan-16 71.399  Jan-16 83.141
   Jan-16 71.399  Jan-16 66.341
   Jan-16 71.399  Jan-16 71.399
   Feb-16 71.312  Feb-16 66.599
   Feb-16 71.312  Feb-16 80.741
   Feb-16 71.312  Feb-16 71.312
   Feb-16 71.312  Feb-16 66.599
   Feb-16 71.312  Feb-16 80.741
   Feb-16 71.312  Feb-16 71.312

Body:
Some how I could to that using below trick:

T1 <- rbind(as.data.frame.array(T1,T1))

Final Table$Value <- T1$Value[match(Final Table$Month,T1$Month)]


问:
"Unknown Error" when launching Visual Studio 2017 Community after installation
I am getting an "Unknown Error" (shown below) alert when I try to launch Visual Studio 2017 Community after successful installation.

UPDATE: After Force uninstall & reinstallation

答: I only needed to delete or rename ApplicationPrivateSettings.lock within C:\users{your username}\AppData\Local\Microsoft\VisualStudio\15.0_c31ecfb9 folder.


问:
Apache Pig Distinct and Count
I'm trying to figure out the following question.

How many female users provided at least one rating of 4.  I think my join and filters are correct but I cant figure out the distinct count part  Have tried numerous versions of the below.

```<code>a = load '/user/pig/movie' AS (userid:int, movieid:int, rating:int, timestamp:chararray);
b = load '/user/pig/reviewer' using PigStorage('|') AS (userid:int, age:int, gender:chararray, occupation:chararray, zip:chararray);
a1 = filter a by rating == 4;
b1 = filter b by gender == 'F';
c = join a1 by userid, b1 by userid;
d = FOREACH c GENERATE COUNT(DISTINCT(userid));
dump d;
</code>```

答:
You have to GROUP before COUNT.Ref:COUNT requires a preceding GROUP ALL statement for global counts and a GROUP BY statement for group counts.</p>

```<code>d = GROUP c BY userid;
e = FOREACH d GENERATE COUNT(DISTINCT(b1.userid));
dump e;
</code>```

Title: Apache Pig Distinct and Count

Body:
I'm trying to figure out the following question.

How many female users provided at least one rating of 4.  I think my join and filters are correct but I cant figure out the distinct count part  Have tried numerous versions of the below.

a = load '/user/pig/movie' AS (userid:int, movieid:int, rating:int, timestamp:chararray);
b = load '/user/pig/reviewer' using PigStorage('|') AS (userid:int, age:int, gender:chararray, occupation:chararray, zip:chararray);
a1 = filter a by rating == 4;
b1 = filter b by gender == 'F';
c = join a1 by userid, b1 by userid;
d = FOREACH c GENERATE COUNT(DISTINCT(userid));
dump d;

Body:
You have to GROUP before COUNT.Ref:COUNT requires a preceding GROUP ALL statement for global counts and a GROUP BY statement for group counts.

d = GROUP c BY userid;
e = FOREACH d GENERATE COUNT(DISTINCT(b1.userid));
dump e;


问:
Trouble getting working directory
This is how I am trying to get the current working directory:

```<code>    char* ch;
    if( (ch = _getcwd( NULL, 0 )) == NULL )
    {
        cout << "Could not get working directory!" << endl;
    }
    // skonvertujme char* na string, s tym sa nizsie bude lahsie pracovat
    stringstream ss;
    string workingDirectory;
    ss << ch;
    ss >> workingDirectory;

    cout << workingDirectory << endl;
    cin.get();
    cin.get();
</code>```

Which prints out:

```<code>C:\Users\Richard\Documents\Visual
</code>```

Instead of the actual working directory:

```<code>C:\Users\Richard\Documents\Visual Studio 2010\Projects\Client\Debug
</code>```

It seems like ti cuts everything after a space.

How can I get the working directory correctly even if there are spaces in the path?

答:
The >> operator stops at the first space. Instead of the stringstream manipulation try

```<code>string workingDirectory(ch);
</code>```

Title: Trouble getting working directory

Body:
This is how I am trying to get the current working directory:

    char* ch;
    if( (ch = _getcwd( NULL, 0 )) == NULL )
    {
        cout << "Could not get working directory!" << endl;
    }
    // skonvertujme char* na string, s tym sa nizsie bude lahsie pracovat
    stringstream ss;
    string workingDirectory;
    ss << ch;
    ss >> workingDirectory;

    cout << workingDirectory << endl;
    cin.get();
    cin.get();

Which prints out:

C:\Users\Richard\Documents\Visual

Instead of the actual working directory:

C:\Users\Richard\Documents\Visual Studio 2010\Projects\Client\Debug

It seems like ti cuts everything after a space.

How can I get the working directory correctly even if there are spaces in the path?

Body:
The >> operator stops at the first space. Instead of the stringstream manipulation try

string workingDirectory(ch);


问:
How to get instance of InstancePerRequest object inside a Singleton
I am new to Autofac, I really like its lifetime scope features, but I am having an issue.

I need to use an instance of an object created on a InstancePerRequest basis from a singleton in an assembly that doesn't have a refence to .Net MVC Web

I tried what this post suggests but it doesn't work. I get this exception:

No scope with a tag matching 'AutofacWebRequest' is visible from the
  scope in which the instance was requested.

What is the correct way to get/use an InstancePerRequest object in a Singleton?

Update
I would like to clarify, considering Travis answer, we don't want to hold a captive dependency of the InstancePerRequest item in the singleton. We want to request the item each time we use it. We've analyzed and it would be more expensive to make the singleton an InstancePerRequest than request the InstancePerRequest item to the container each time we use it.
Is this considered a bad practice? It is rather common to have certain things you need to access at the Request level and have a Singleton use them.

答:
Thanks everyone for your answers and comments, It turns out the solution was rather simple.
This is the structure of files I wind up having:

No-Web assembly

```<code>public IPerRequestDependencyResolver
{
    T Get<T>() where T : class;
}

public interface IPerRequestObject
{
    void DoSomething();
}

public class PerRequestObject: IPerRequestObject
{
    public void DoSomething()
    {}
}

public interface IMySingletonPerRequestWrapper
{
    DoSomethingOnPerRequestBasis();
}

public class MySingletonPerRequestWrapper: IMySingletonPerRequestWrapper
{
    private IPerRequestDependencyResolver perRequestDependencyResolver;
    public PerRequestWrapper(IPerRequestDependencyResolver perRequestDependencyResolver)
    {
        this.perRequestDependencyResolver = perRequestDependencyResolver;
    }

    public void DoSomethingOnPerRequestBasis()
    {
        this.perRequestDependencyResolver.Get<IPerRequestObject>().DoSomething();
    }
}

public interface IMySingletonBussinesObject
{
    void DoSomething();
}

public class MySingletonBussinessObject: IMySingletonBussinesObject
{
    private IMySingletonPerRequestWrapper mysingletonPerRequestWrapper;
    public MySingletonBussinessObject(IMySingletonPerRequestWrapper mysingletonPerRequestWrapper)
    {
        this.mysingletonPerRequestWrapper = mysingletonPerRequestWrapper;
    }

    public void DoSomething()
    {
        this.mysingletonPerRequestWrapper.DoSomethingOnPerRequestBasis();
    }
}
</code>```

MVC Web assembly

```<code>public class PerRequestDependencyResolver : IPerRequestDependencyResolver
{
    public T Get<T>() where T : class
    {
        return DependencyResolver.Current.GetService<T>();
    }
}
</code>```

MySingletonPerRequestWrapper, MySingletonBussinessObject, PerRequestDependencyResolver are configured as .SingleInstance() in Autofac while PerRequestObject is configured with `InstancePerRequest().

I create the MySingletonPerRequestWrapper instead of directly using the PerRequestDependencyResolver inside the MySingletonBussinessObject because I want to make sure that anyone using the PerRequestObject does so properly and no captive instances are kept by mistake.
I rather use Autofac this way to keep all my instances than keeping my instance in the HttpRequest and using it from there (with a wrapper), I feel this is more flexible.

Update Web Api

This is the update to use this technique with WebApi. I didn't myself do the full implementation, we discussed it on my group and a friend implemented it. I will explain the approach he took.

I simplified the logic and classes for clarity, you can change whatever you need.
In our system we configured Autofac so you can inject instances in static classes. You can change that to something that better suits you.

First some helper, Extension methods to simplify.

```<code>public static class Extensions
{
    private const string dependencyScopeKey = "Resolver.Unique.key";
    public static IExecutionContext ExecutionContext {  get; set; }
    public static IDependencyScope Current(this IDependencyResolver dependencyResolver)
    {
        return ExecutionContext.GetObject<IDependencyScope>(dependencyScopeKey);
    }

    public static void SetCurrentDependencyScope(this HttpRequestMessage request)
    {
        ExecutionContext.SetObject(dependencyScopeKey, request.GetDependencyScope());
    }
}

public class WebExecutionContext : IExecutionContext
{

    public T GetObject <T>(string key)
    {
        var result = HttpContext.Current.Items[key];
        return result != null ? (T) result : default(T);
    }

    public void SetObject(string key, object val)
    {
        if (HttpContext.Current.Items.Contains(key))
            HttpContext.Current.Items.Remove(key);
        HttpContext.Current.Items.Add(key, val);
    }
}
</code>```

Then the WebApi implementation of the IPerRequestDependencyResolver, we make use of the GlobalConfiguration.

```<code>public class PerRequestWebAPIDependencyResolver : IPerRequestDependencyResolver
{
    public T Get <T>() where T : class
    {
        var config = GlobalConfiguration.Configuration;
        return (T)config.DependencyResolver.Current().GetService(typeof(T));
    }
}
</code>```

Then an action filter to help us add the DependencyResolver we need:

```<code>public class IoCScopeAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext filterContext)
    {
        //ioc context set
        filterContext.Request.SetCurrentDependencyScope();
    }
}
</code>```

Finally in your controller, or base controller
    [AuthorizationFilter]
    [IoCScope()]
    public class YourController : ApiController
    {

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

I hope this helps!

Body:
Thanks everyone for your answers and comments, It turns out the solution was rather simple.
This is the structure of files I wind up having:

No-Web assembly

public IPerRequestDependencyResolver
{
    T Get<T>() where T : class;
}

public interface IPerRequestObject
{
    void DoSomething();
}

public class PerRequestObject: IPerRequestObject
{
    public void DoSomething()
    {}
}

public interface IMySingletonPerRequestWrapper
{
    DoSomethingOnPerRequestBasis();
}

public class MySingletonPerRequestWrapper: IMySingletonPerRequestWrapper
{
    private IPerRequestDependencyResolver perRequestDependencyResolver;
    public PerRequestWrapper(IPerRequestDependencyResolver perRequestDependencyResolver)
    {
        this.perRequestDependencyResolver = perRequestDependencyResolver;
    }

    public void DoSomethingOnPerRequestBasis()
    {
        this.perRequestDependencyResolver.Get<IPerRequestObject>().DoSomething();
    }
}

public interface IMySingletonBussinesObject
{
    void DoSomething();
}

public class MySingletonBussinessObject: IMySingletonBussinesObject
{
    private IMySingletonPerRequestWrapper mysingletonPerRequestWrapper;
    public MySingletonBussinessObject(IMySingletonPerRequestWrapper mysingletonPerRequestWrapper)
    {
        this.mysingletonPerRequestWrapper = mysingletonPerRequestWrapper;
    }

    public void DoSomething()
    {
        this.mysingletonPerRequestWrapper.DoSomethingOnPerRequestBasis();
    }
}

MVC Web assembly

public class PerRequestDependencyResolver : IPerRequestDependencyResolver
{
    public T Get<T>() where T : class
    {
        return DependencyResolver.Current.GetService<T>();
    }
}

MySingletonPerRequestWrapper, MySingletonBussinessObject, PerRequestDependencyResolver are configured as .SingleInstance() in Autofac while PerRequestObject is configured with `InstancePerRequest().

I create the MySingletonPerRequestWrapper instead of directly using the PerRequestDependencyResolver inside the MySingletonBussinessObject because I want to make sure that anyone using the PerRequestObject does so properly and no captive instances are kept by mistake.
I rather use Autofac this way to keep all my instances than keeping my instance in the HttpRequest and using it from there (with a wrapper), I feel this is more flexible.

Update Web Api

This is the update to use this technique with WebApi. I didn't myself do the full implementation, we discussed it on my group and a friend implemented it. I will explain the approach he took.

I simplified the logic and classes for clarity, you can change whatever you need.
In our system we configured Autofac so you can inject instances in static classes. You can change that to something that better suits you.

First some helper, Extension methods to simplify.

public static class Extensions
{
    private const string dependencyScopeKey = "Resolver.Unique.key";
    public static IExecutionContext ExecutionContext {  get; set; }
    public static IDependencyScope Current(this IDependencyResolver dependencyResolver)
    {
        return ExecutionContext.GetObject<IDependencyScope>(dependencyScopeKey);
    }

    public static void SetCurrentDependencyScope(this HttpRequestMessage request)
    {
        ExecutionContext.SetObject(dependencyScopeKey, request.GetDependencyScope());
    }
}

public class WebExecutionContext : IExecutionContext
{

    public T GetObject <T>(string key)
    {
        var result = HttpContext.Current.Items[key];
        return result != null ? (T) result : default(T);
    }

    public void SetObject(string key, object val)
    {
        if (HttpContext.Current.Items.Contains(key))
            HttpContext.Current.Items.Remove(key);
        HttpContext.Current.Items.Add(key, val);
    }
}

Then the WebApi implementation of the IPerRequestDependencyResolver, we make use of the GlobalConfiguration.

public class PerRequestWebAPIDependencyResolver : IPerRequestDependencyResolver
{
    public T Get <T>() where T : class
    {
        var config = GlobalConfiguration.Configuration;
        return (T)config.DependencyResolver.Current().GetService(typeof(T));
    }
}

Then an action filter to help us add the DependencyResolver we need:

public class IoCScopeAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext filterContext)
    {
        //ioc context set
        filterContext.Request.SetCurrentDependencyScope();
    }
}

Finally in your controller, or base controller
    [AuthorizationFilter]
    [IoCScope()]
    public class YourController : ApiController
    {

}

I hope this helps!

ContentLicense: CC BY-SA 4.0


问:
Adding one element to recyclerview is adding entire arrayList again
I have an recyclerView which is working fine.
Now if I append an element in the recyclerView and call notifyDataSetChanged() method, it is appending the entire recyclerView with it along with 2 extra copies of the last added item.

Main class

```<code>imageList.add(value);
galleryAdapter.addElement(value);
</code>```

Here imageList is an arrayList of strings and value is a string.

AdapterClass for the recyclerView

public void addElement(String list){
        images.add(list);
        notifyDataSetChanged();
    }

I have checked and made sure the data is working fine. If I leave the screen and open it again, it shows properly with the added element at correct position.

答:
try this

Main class

```<code>imageList.add(value);
galleryAdapter.addElement(imageList);
</code>```

Adapter

```<code>public void addElement(yourlist list){
        images.add(list);
       notifyItemRangeChanged(0,list.size()-1);
    }
</code>```

hope it will help you.

Body:
I have an recyclerView which is working fine.
Now if I append an element in the recyclerView and call notifyDataSetChanged() method, it is appending the entire recyclerView with it along with 2 extra copies of the last added item.

Main class

imageList.add(value);
galleryAdapter.addElement(value);

Here imageList is an arrayList of strings and value is a string.

AdapterClass for the recyclerView

public void addElement(String list){
        images.add(list);
        notifyDataSetChanged();
    }

I have checked and made sure the data is working fine. If I leave the screen and open it again, it shows properly with the added element at correct position.

Body:
try this

Main class

imageList.add(value);
galleryAdapter.addElement(imageList);

Adapter

public void addElement(yourlist list){
        images.add(list);
       notifyItemRangeChanged(0,list.size()-1);
    }

hope it will help you.


问:
502 bad gateway with nginx and node inside docker
I'm trying to run node and nginx each inside their own docker containers and proxy from nginx to node. I tried the configuration below without docker at first and it worked. However when using docker it's not working and gives Status Code:502 Bad Gateway when trying to connect to http://localhost/.

node server

```<code>var http = require('http');
http.createServer(function (req, res) {
    res.setHeader('content-type', 'text/html');
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Request-Headers', '*');
    res.setHeader('Access-Control-Request-Method', '*');
    res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET');
    res.setHeader('Access-Control-Allow-Headers', '*');
    res.end('<html>Hey</html>');
}).listen(3001);
</code>```

docker-compose.yml

```<code>version: '3'
services:
  app:
    build: ./servers
  nginx:
    build: ./nginx
    depends_on:
      - app
    links:
      - app
    volumes:
      - ./nginx/conf:/etc/nginx/conf.d:ro
    ports:
      - 80:80
</code>```

nginx conf

```<code>server {
        listen 80;
        listen [::]:80;

        location / {
                proxy_pass http://app;
        }
}
</code>```

app dockerfile

```<code>FROM node:alpine
RUN mkdir /app/
COPY ./server.js /app
EXPOSE 3001
WORKDIR /app
CMD node server
</code>```

nginx dockerfile

```<code>FROM nginx:alpine
RUN rm /etc/nginx/conf.d/*
</code>```

答:
This now looks like a stupid question but I had the misconception that docker linked containers to whatever ports it opened without specifying the port. It turns out all the example I followed used port 80 on the other side. Anyway, enough with justifying myself, all I had to do was make the js server listen on port 80.

```<code>http.createServer(function (req, res) {
   ...
}).listen(80);
</code>```

Alternatively I believe I could have used port 3001 in nginx conf

```<code>    location / {
            proxy_pass http://app:3001;
    }
</code>```

Body:
I'm trying to run node and nginx each inside their own docker containers and proxy from nginx to node. I tried the configuration below without docker at first and it worked. However when using docker it's not working and gives Status Code:502 Bad Gateway when trying to connect to http://localhost/.

node server

var http = require('http');
http.createServer(function (req, res) {
    res.setHeader('content-type', 'text/html');
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Request-Headers', '*');
    res.setHeader('Access-Control-Request-Method', '*');
    res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET');
    res.setHeader('Access-Control-Allow-Headers', '*');
    res.end('Hey');
}).listen(3001);

docker-compose.yml

version: '3'
services:
  app:
    build: ./servers
  nginx:
    build: ./nginx
    depends_on:
      - app
    links:
      - app
    volumes:
      - ./nginx/conf:/etc/nginx/conf.d:ro
    ports:
      - 80:80

nginx conf

server {
        listen 80;
        listen [::]:80;

        location / {
                proxy_pass http://app;
        }
}

app dockerfile

FROM node:alpine
RUN mkdir /app/
COPY ./server.js /app
EXPOSE 3001
WORKDIR /app
CMD node server

nginx dockerfile

FROM nginx:alpine
RUN rm /etc/nginx/conf.d/*

Body:
This now looks like a stupid question but I had the misconception that docker linked containers to whatever ports it opened without specifying the port. It turns out all the example I followed used port 80 on the other side. Anyway, enough with justifying myself, all I had to do was make the js server listen on port 80.

http.createServer(function (req, res) {
   ...
}).listen(80);

Alternatively I believe I could have used port 3001 in nginx conf

    location / {
            proxy_pass http://app:3001;
    }


问:
Symfony2: do not update a form field if not provided
I have a form for my "Team" entity. This entity has an "image" field. This field is required on creation process, but not required on edit process. But right now, during edit process, if I don't provide any image in the file input, the empty input is still persisted, and so my database field is emptied during the process.
How can I do to avoid persistence of this field, if nothing is provided in the form file input? So the entity keeps its old value for this field. Of course, if a file is provided, I want him to erase the old one.

My controller looks like this:

```<code>if ($request->getMethod() == 'POST') {

    $form->bind($request);

    if ($form->isValid()) {

        $em->persist($team);
        $em->flush();
        ...
    }
}
</code>```

and part of my entity, dealing with image (I'm pretty sure I have to do something in here, but don't know what exactly):

```<code>/**
 * @ORM\PrePersist()
 * @ORM\PreUpdate()
 */
public function uploadImage() {
    // the file property can be empty if the field is not required
    if (null === $this->image) {
        return;
    }
    if(!$this->id){
        $this->image->move($this->getTmpUploadRootDir(), $this->image->getClientOriginalName());
    }else{
        $this->image->move($this->getUploadRootDir(), $this->image->getClientOriginalName());
    }
    $this->setImage($this->image->getClientOriginalName());
}
</code>```

EDIT

Ok, I did some changes to this answer's code code, because apparently the event listener asks for a FormEvent instance in his callback, not a FormInterface instance.

```<code>$builder->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) {
// Retrieve submitted data
$form = $event->getForm();
$item = $event->getData();

// Test if upload image is null (maybe adapt it to work with your code)
if (null !== $form->get('image')->getData()) {
    var_dump($form->get('image')->getData());
    die('image provided');
    $item->setImage($form->get('image')->getData());
}
</code>```

});

When I provide an image, the script goes into the test, and die(), as expected. When I do not provide any file, the script doesn't go into the test if(), but my field in the database is still erased with an empty value. Any idea?

And as asked below, here is the Form

```<code>// src/Van/TeamsBundle/Form/TeamEditType.php

namespace Van\TeamsBundle\Form;

use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;

class TeamEditType extends TeamType // Ici, on hÃ©rite de ArticleType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // On fait appel Ã  la mÃ©thode buildForm du parent, qui va ajouter tous les champs Ã  $builder
        parent::buildForm($builder, $options);
        // On supprime celui qu'on ne veut pas dans le formulaire de modification
        $builder->remove('image')
        ->add('image', 'file', array(
            'data_class' => null,
            'required' => false
        ))
        ;

        $builder->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) {
            // Retrieve submitted data
            $form = $event->getForm();
            $item = $event->getData();

            // Test if upload image is null (maybe adapt it to work with your code)
            if (null !== $form->get('image')->getData()) {
                var_dump($form->get('image')->getData());
                die('image provided');
                $item->setImage($form->get('image')->getData());
            }
        });

    }

    // On modifie cette mÃ©thode car les deux formulaires doivent avoir un nom diffÃ©rent
    public function getName()
    {
        return 'van_teamsbundle_teamedittype';
    }
}
</code>```

and the whole Team entity:

```<code><?php

namespace Van\TeamsBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Team
 *
 * @ORM\Table()
 * @ORM\HasLifecycleCallbacks
 * @ORM\Entity
 * @ORM\Entity(repositoryClass="Van\TeamsBundle\Entity\TeamRepository") @ORM\Table(name="van_teams")
 */
class Team
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=100)
     */
    private $name;

    /**
     * @var string
     *
     * @ORM\Column(name="countryCode", type="string", length=2)
     */
    private $countryCode;

    /**
     * @ORM\ManyToOne(targetEntity="Van\TeamsBundle\Entity\Game")
     * @ORM\JoinColumn(nullable=false)
     */
    private $game;

    /**
     * @ORM\ManyToOne(targetEntity="Van\TeamsBundle\Entity\Statut")
     * @ORM\JoinColumn(nullable=false)
     */
    private $statut;

    /**
     * @var string $image
     * @Assert\File( maxSize = "1024k", mimeTypesMessage = "Please upload a valid Image")
     * @ORM\Column(name="image", type="string", length=255)
     */
    private $image;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return Team
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set countryCode
     *
     * @param string $countryCode
     * @return Team
     */
    public function setCountryCode($countryCode)
    {
        $this->countryCode = $countryCode;

        return $this;
    }

    /**
     * Get countryCode
     *
     * @return string
     */
    public function getCountryCode()
    {
        return $this->countryCode;
    }

    /**
     * Set image
     *
     * @param string $image
     * @return Team
     */
    public function setImage($image)
    {
        $this->image = $image;

        return $this;
    }

    /**
     * Get image
     *
     * @return string
     */
    public function getImage()
    {
        return $this->image;
    }

    /**
     * Set game
     *
     * @param \Van\TeamsBundle\Entity\Game $game
     * @return Team
     */
    public function setGame(\Van\TeamsBundle\Entity\Game $game)
    {
        $this->game = $game;

        return $this;
    }

    /**
     * Get game
     *
     * @return \Van\TeamsBundle\Entity\Game
     */
    public function getGame()
    {
        return $this->game;
    }

    /**
     * Set statut
     *
     * @param \Van\TeamsBundle\Entity\Statut $statut
     * @return Team
     */
    public function setStatut(\Van\TeamsBundle\Entity\Statut $statut)
    {
        $this->statut = $statut;

        return $this;
    }

    /**
     * Get statut
     *
     * @return \Van\TeamsBundle\Entity\Statut
     */
    public function getStatut()
    {
        return $this->statut;
    }

    public function getFullImagePath() {
        return null === $this->image ? null : $this->getUploadRootDir(). $this->image;
    }

    protected function getUploadRootDir() {
        // the absolute directory path where uploaded documents should be saved
        // return $this->getTmpUploadRootDir();
        return __DIR__ . '/../../../../web/uploads/';
    }

    protected function getTmpUploadRootDir() {
        // the absolute directory path where uploaded documents should be saved
        return __DIR__ . '/../../../../web/uploads_tmp/';
    }

    /**
     * @ORM\PrePersist()
     * @ORM\PreUpdate()
     */
    public function uploadImage() {
        // the file property can be empty if the field is not required
        if (null === $this->image) {
            return;
        }
        if(!$this->id){
            $this->image->move($this->getTmpUploadRootDir(), $this->image->getClientOriginalName());
        }else{
            $this->image->move($this->getUploadRootDir(), $this->image->getClientOriginalName());
        }
        $this->setImage($this->image->getClientOriginalName());
    }

    /**
     * @ORM\PostPersist()
     */
    public function moveImage()
    {
        if (null === $this->image) {
            return;
        }
        if(!is_dir($this->getUploadRootDir())){
            mkdir($this->getUploadRootDir());
        }
        copy($this->getTmpUploadRootDir().$this->image, $this->getFullImagePath());
        unlink($this->getTmpUploadRootDir().$this->image);
    }

    /**
     * @ORM\PreRemove()
     */
    public function removeImage()
    {
        unlink($this->getFullImagePath());
        rmdir($this->getUploadRootDir());
    }
}
</code>```

EDIT 2

I did that. When I provide an image, it is saved in the image field in the database and redirection to my index page occurs. When I don't provide any image, redirection doesn't occur, and the following message appears above my file input in my form: "The file could not be found." In my TeamEditType class, I did the following, so the image should not be required.

```<code>$builder->remove('image')
->add('image', 'file', array(
    'data_class' => null,
    'required' => false
))
;
</code>```

答:
I'm using symfony 3.3 and faced the same issue, below is the solution how I overcome it.

You need to create a extra property for image uploading in your entity other than image property, something like $file;

Product.php

```<code>/**
 * @var string
 *
 * @ORM\Column(name="image", type="string")
 *
 */
 private $image;

/**
 *
 * @Assert\File(mimeTypes={ "image/jpeg", "image/jpg", "image/png" })
 */
private $file;

public function setFile($file)
{
    $this->file = $file;
    return $this;
}
public function getFile()
{
    return $this->file;
}

// other code i.e image setter getter
...
</code>```

ProductType.php

```<code>   $builder->add('file', FileType::class, array(
            'data_class' => null,
            'required'=>false,
            'label' => 'Upload Image (jpg, jpeg, png file)')
   );
</code>```

Form.html.twig

```<code>  <div class="form-group">
        {{ form_label(form.file) }}
        {{ form_widget(form.file, {'attr': {'class': 'form-control'}}) }}
    </div>
</code>```

Finally ProductController.php

```<code> ...
 if ($form->isSubmitted() && $form->isValid()) {
     $file = $item->getFile();
              if($file instanceof UploadedFile) {
                  $fileName = md5(uniqid()).'.'.$file->guessExtension();
                  $file->move(
                  $this->getParameter('upload_directory'),
                  $fileName
                  );
                  $item->setImage($fileName);
              }
  ...
  }
 ...
</code>```

Little more about upload_directory

app/config/config.html

```<code> parameters:
    upload_directory: '%kernel.project_dir%/web/uploads'
</code>```

Create a uploads directory in web dir.

Body:
I have a form for my "Team" entity. This entity has an "image" field. This field is required on creation process, but not required on edit process. But right now, during edit process, if I don't provide any image in the file input, the empty input is still persisted, and so my database field is emptied during the process.
How can I do to avoid persistence of this field, if nothing is provided in the form file input? So the entity keeps its old value for this field. Of course, if a file is provided, I want him to erase the old one.

My controller looks like this:

if ($request->getMethod() == 'POST') {

    $form->bind($request);

    if ($form->isValid()) {

        $em->persist($team);
        $em->flush();
        ...
    }
}

and part of my entity, dealing with image (I'm pretty sure I have to do something in here, but don't know what exactly):

/**
 * @ORM\PrePersist()
 * @ORM\PreUpdate()
 */
public function uploadImage() {
    // the file property can be empty if the field is not required
    if (null === $this->image) {
        return;
    }
    if(!$this->id){
        $this->image->move($this->getTmpUploadRootDir(), $this->image->getClientOriginalName());
    }else{
        $this->image->move($this->getUploadRootDir(), $this->image->getClientOriginalName());
    }
    $this->setImage($this->image->getClientOriginalName());
}

EDIT

Ok, I did some changes to this answer's code code, because apparently the event listener asks for a FormEvent instance in his callback, not a FormInterface instance.

$builder->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) {
// Retrieve submitted data
$form = $event->getForm();
$item = $event->getData();

// Test if upload image is null (maybe adapt it to work with your code)
if (null !== $form->get('image')->getData()) {
    var_dump($form->get('image')->getData());
    die('image provided');
    $item->setImage($form->get('image')->getData());
}

});

When I provide an image, the script goes into the test, and die(), as expected. When I do not provide any file, the script doesn't go into the test if(), but my field in the database is still erased with an empty value. Any idea?

And as asked below, here is the Form

// src/Van/TeamsBundle/Form/TeamEditType.php

namespace Van\TeamsBundle\Form;

use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;

class TeamEditType extends TeamType // Ici, on hÃ©rite de ArticleType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // On fait appel Ã  la mÃ©thode buildForm du parent, qui va ajouter tous les champs Ã  $builder
        parent::buildForm($builder, $options);
        // On supprime celui qu'on ne veut pas dans le formulaire de modification
        $builder->remove('image')
        ->add('image', 'file', array(
            'data_class' => null,
            'required' => false
        ))
        ;

        $builder->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) {
            // Retrieve submitted data
            $form = $event->getForm();
            $item = $event->getData();

            // Test if upload image is null (maybe adapt it to work with your code)
            if (null !== $form->get('image')->getData()) {
                var_dump($form->get('image')->getData());
                die('image provided');
                $item->setImage($form->get('image')->getData());
            }
        });

    }

    // On modifie cette mÃ©thode car les deux formulaires doivent avoir un nom diffÃ©rent
    public function getName()
    {
        return 'van_teamsbundle_teamedittype';
    }
}

and the whole Team entity:

<?php

namespace Van\TeamsBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Team
 *
 * @ORM\Table()
 * @ORM\HasLifecycleCallbacks
 * @ORM\Entity
 * @ORM\Entity(repositoryClass="Van\TeamsBundle\Entity\TeamRepository") @ORM\Table(name="van_teams")
 */
class Team
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=100)
     */
    private $name;

    /**
     * @var string
     *
     * @ORM\Column(name="countryCode", type="string", length=2)
     */
    private $countryCode;

    /**
     * @ORM\ManyToOne(targetEntity="Van\TeamsBundle\Entity\Game")
     * @ORM\JoinColumn(nullable=false)
     */
    private $game;

    /**
     * @ORM\ManyToOne(targetEntity="Van\TeamsBundle\Entity\Statut")
     * @ORM\JoinColumn(nullable=false)
     */
    private $statut;

    /**
     * @var string $image
     * @Assert\File( maxSize = "1024k", mimeTypesMessage = "Please upload a valid Image")
     * @ORM\Column(name="image", type="string", length=255)
     */
    private $image;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return Team
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set countryCode
     *
     * @param string $countryCode
     * @return Team
     */
    public function setCountryCode($countryCode)
    {
        $this->countryCode = $countryCode;

        return $this;
    }

    /**
     * Get countryCode
     *
     * @return string
     */
    public function getCountryCode()
    {
        return $this->countryCode;
    }

    /**
     * Set image
     *
     * @param string $image
     * @return Team
     */
    public function setImage($image)
    {
        $this->image = $image;

        return $this;
    }

    /**
     * Get image
     *
     * @return string
     */
    public function getImage()
    {
        return $this->image;
    }

    /**
     * Set game
     *
     * @param \Van\TeamsBundle\Entity\Game $game
     * @return Team
     */
    public function setGame(\Van\TeamsBundle\Entity\Game $game)
    {
        $this->game = $game;

        return $this;
    }

    /**
     * Get game
     *
     * @return \Van\TeamsBundle\Entity\Game
     */
    public function getGame()
    {
        return $this->game;
    }

    /**
     * Set statut
     *
     * @param \Van\TeamsBundle\Entity\Statut $statut
     * @return Team
     */
    public function setStatut(\Van\TeamsBundle\Entity\Statut $statut)
    {
        $this->statut = $statut;

        return $this;
    }

    /**
     * Get statut
     *
     * @return \Van\TeamsBundle\Entity\Statut
     */
    public function getStatut()
    {
        return $this->statut;
    }

    public function getFullImagePath() {
        return null === $this->image ? null : $this->getUploadRootDir(). $this->image;
    }

    protected function getUploadRootDir() {
        // the absolute directory path where uploaded documents should be saved
        // return $this->getTmpUploadRootDir();
        return __DIR__ . '/../../../../web/uploads/';
    }

    protected function getTmpUploadRootDir() {
        // the absolute directory path where uploaded documents should be saved
        return __DIR__ . '/../../../../web/uploads_tmp/';
    }

    /**
     * @ORM\PrePersist()
     * @ORM\PreUpdate()
     */
    public function uploadImage() {
        // the file property can be empty if the field is not required
        if (null === $this->image) {
            return;
        }
        if(!$this->id){
            $this->image->move($this->getTmpUploadRootDir(), $this->image->getClientOriginalName());
        }else{
            $this->image->move($this->getUploadRootDir(), $this->image->getClientOriginalName());
        }
        $this->setImage($this->image->getClientOriginalName());
    }

    /**
     * @ORM\PostPersist()
     */
    public function moveImage()
    {
        if (null === $this->image) {
            return;
        }
        if(!is_dir($this->getUploadRootDir())){
            mkdir($this->getUploadRootDir());
        }
        copy($this->getTmpUploadRootDir().$this->image, $this->getFullImagePath());
        unlink($this->getTmpUploadRootDir().$this->image);
    }

    /**
     * @ORM\PreRemove()
     */
    public function removeImage()
    {
        unlink($this->getFullImagePath());
        rmdir($this->getUploadRootDir());
    }
}

EDIT 2

I did that. When I provide an image, it is saved in the image field in the database and redirection to my index page occurs. When I don't provide any image, redirection doesn't occur, and the following message appears above my file input in my form: "The file could not be found." In my TeamEditType class, I did the following, so the image should not be required.

$builder->remove('image')
->add('image', 'file', array(
    'data_class' => null,
    'required' => false
))
;

Body:
I'm using symfony 3.3 and faced the same issue, below is the solution how I overcome it.

You need to create a extra property for image uploading in your entity other than image property, something like $file;

Product.php

/**
 * @var string
 *
 * @ORM\Column(name="image", type="string")
 *
 */
 private $image;

/**
 *
 * @Assert\File(mimeTypes={ "image/jpeg", "image/jpg", "image/png" })
 */
private $file;

public function setFile($file)
{
    $this->file = $file;
    return $this;
}
public function getFile()
{
    return $this->file;
}

// other code i.e image setter getter
...

ProductType.php

   $builder->add('file', FileType::class, array(
            'data_class' => null,
            'required'=>false,
            'label' => 'Upload Image (jpg, jpeg, png file)')
   );

Form.html.twig

  <div class="form-group">
        {{ form_label(form.file) }}
        {{ form_widget(form.file, {'attr': {'class': 'form-control'}}) }}
    </div>

Finally ProductController.php

 ...
 if ($form->isSubmitted() && $form->isValid()) {
     $file = $item->getFile();
              if($file instanceof UploadedFile) {
                  $fileName = md5(uniqid()).'.'.$file->guessExtension();
                  $file->move(
                  $this->getParameter('upload_directory'),
                  $fileName
                  );
                  $item->setImage($fileName);
              }
  ...
  }
 ...

Little more about upload_directory

app/config/config.html

 parameters:
    upload_directory: '%kernel.project_dir%/web/uploads'

Create a uploads directory in web dir.