问:
How to update RecyclerView when another Fragment button Click
i have 2 tab.

A - RecycleFragment ///////
B - DiaryFragment

i want update RecycleFragment when button click in DiaryFragment.

```<code>public class RecycleFragment extends Fragment {

    static  DBHelper dbHelper;
    public List<Contact> items = new ArrayList<Contact>();

    MyAdapter adapter = new MyAdapter(items);

    @Override
    public void onCreate(Bundle savedInstanceState) {
        dbHelper = new DBHelper(getActivity());
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.recyle_fragment, container, false);
        RecyclerView rv = (RecyclerView) rootView.findViewById(R.id.rv_recycler_view);
        LinearLayoutManager llm = new LinearLayoutManager(getActivity());
        // MyAdapter adapter = new MyAdapter(items);

        rv.setLayoutManager(llm);
        rv.setAdapter(adapter);
        adapter.addTestData();
        adapter.notifyDataSetChanged();

        return rv;
    }
}
</code>```

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

```<code>public  class  MyAdapter extends RecyclerView.Adapter<DataManager> {
 static List<Contact> items = new ArrayList<Contact>();

public MyAdapter(List<Contact> items){
    this.items = items;
}

@Override
public DataManager onCreateViewHolder(ViewGroup viewGroup, int i) {
    View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.entries, viewGroup, false);
    return new DataManager(v);
}

@Override
public void onBindViewHolder(DataManager holder, int position) {

    Contact item = items.get(position);
    holder.mTitle.setText(item.get1(Contact.Field.TITLE));
    holder.mDate.setText(item.get1(Contact.Field.DATE));
    holder.mMonth.setText(item.get1(Contact.Field.MONTH));
    holder.mTime.setText(item.get1(Contact.Field.TIME));
    holder.mDay.setText(item.get1(Contact.Field.DAY));
    holder.mContent.setText(item.get1(Contact.Field.CONTENT));
    holder.mMood.setImageResource(item.get2(Contact.Field.MOOD));
    holder.mWeather.setImageResource(item.get2(Contact.Field.WEATHER));

}

@Override
public int getItemCount() {
    return items.size();
}

public void setItem(List<Contact> items){
    this.items = items;
    notifyItemChanged (0, null);
}

public void addTestData(){

    Cursor cursor = RecycleFragment.dbHelper.D_getAllData();
    if(cursor != null) {
        if (cursor.moveToFirst()) {
            do{
                add(new Contact(cursor.getString(0),
                        cursor.getString(1),
                        cursor.getString(2),
                        cursor.getString(3),
                        cursor.getString(5),
                        cursor.getString(5),
                        cursor.getString(6),
                        cursor.getInt(7),
                        cursor.getInt(8)));

            }while (cursor.moveToNext());
        }
    }
}

public void add(Contact data){
    items.add(data);
    setItem(items);
}

}
</code>```

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

DiaryFragment in button click event

```<code>case R.id.IV_diary_save:
            if(EDT_diary_title.getText().toString().trim() != null && EDT_diary_title.getText().toString().trim().length() != 0){

                if( EDT_diary_content.getText().toString().trim() != null && EDT_diary_content.getText().toString().trim().length() != 0){

                    dbHelper.D_insertData(EDT_diary_title.getText().toString(), EDT_diary_content.getText().toString(),
                            TV_diary_month.getText().toString(), TV_diary_date.getText().toString(), TV_diary_day.getText().toString(),
                            TV_diary_time.getText().toString(),
                            diaryInfoHelper.getMoodResourceId(SP_diary_weather.getSelectedItemPosition()),
                            diaryInfoHelper.getWeatherResourceId(SP_diary_mood.getSelectedItemPosition())
                    );

                    myAdapter.add(new Contact
                            (String.valueOf(dbHelper.getRow()),EDT_diary_title.getText().toString(), EDT_diary_content.getText().toString(),
                                    TV_diary_month.getText().toString(), TV_diary_date.getText().toString(), TV_diary_day.getText().toString(),
                                    TV_diary_time.getText().toString(),
                                    diaryInfoHelper.getMoodResourceId(SP_diary_weather.getSelectedItemPosition()),
                                    diaryInfoHelper.getWeatherResourceId(SP_diary_mood.getSelectedItemPosition())
                            ));

                    Toast.makeText(v.getContext(), "Success to Insert", Toast.LENGTH_SHORT).show();

                    ((TabActivity)getActivity()).getViewPager().setCurrentItem(0);

                    EDT_diary_title.setText("");
                    EDT_diary_content.setText("");

                }else {
                    Toast.makeText(v.getContext(), "Content is Empty ", Toast.LENGTH_SHORT).show();
                    EDT_diary_content.setText("");
                }
            }else {
                Toast.makeText(v.getContext(), "Title is Empty ", Toast.LENGTH_SHORT).show();
                EDT_diary_title.setText("");
            }
            break;
</code>```

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

button click in DiaryFragment then

moving tab RecycleFragment and

RecycleFragment content immediately change new item insert data.

but now when button click in DiaryFragment
RecycleFragment not change.

Want changing RecycleFragment. I exit RecycleFragment and restart RecycleFragment.

please help me

thank

答:
Do following Steps:

```<code>1. create and interface in dairy.
2. Write A method in it.
3. create the object of this interface and initialize.
4. create a setter for this object.
5. Now in Recycle Fragment implement this interface.
6. Now finally write you code inside the overridden method of interface
</code>```

Let's  take this example.
for declaring an interface.

```<code>private getBusinessList list;

    public void setList(getBusinessList list) {
        this.list = list;
    }

    public interface getBusinessList {
        void result(boolean b, String msg,JSONArray array);
    }
</code>```

now Inside recycler fragment.

```<code>public class SplashActivity extends AppCompatActivity implements ServerCall.getBusinessList
</code>```

now initialize the interface object.

```<code>serverCall.setBusinessList(this);
</code>```

This is my method for interface implementation.

```<code> @Override
    public void getBuisnessList(boolean b, String msg,JSONArray array) {
        progressDialog.dismiss();
        if(b) {

           //displayBusinessList(array);
        }
        else {
            Log.e("Exception e",""+msg+" "+array.toString());

        }

    }
</code>```

you can write your code inside that method.

Body:
i have 2 tab.

A - RecycleFragment ///////
B - DiaryFragment

i want update RecycleFragment when button click in DiaryFragment.

public class RecycleFragment extends Fragment {

    static  DBHelper dbHelper;
    public List<Contact> items = new ArrayList<Contact>();

    MyAdapter adapter = new MyAdapter(items);

    @Override
    public void onCreate(Bundle savedInstanceState) {
        dbHelper = new DBHelper(getActivity());
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.recyle_fragment, container, false);
        RecyclerView rv = (RecyclerView) rootView.findViewById(R.id.rv_recycler_view);
        LinearLayoutManager llm = new LinearLayoutManager(getActivity());
        // MyAdapter adapter = new MyAdapter(items);

        rv.setLayoutManager(llm);
        rv.setAdapter(adapter);
        adapter.addTestData();
        adapter.notifyDataSetChanged();

        return rv;
    }
}

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

public  class  MyAdapter extends RecyclerView.Adapter<DataManager> {
 static List<Contact> items = new ArrayList<Contact>();

public MyAdapter(List<Contact> items){
    this.items = items;
}

@Override
public DataManager onCreateViewHolder(ViewGroup viewGroup, int i) {
    View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.entries, viewGroup, false);
    return new DataManager(v);
}

@Override
public void onBindViewHolder(DataManager holder, int position) {

    Contact item = items.get(position);
    holder.mTitle.setText(item.get1(Contact.Field.TITLE));
    holder.mDate.setText(item.get1(Contact.Field.DATE));
    holder.mMonth.setText(item.get1(Contact.Field.MONTH));
    holder.mTime.setText(item.get1(Contact.Field.TIME));
    holder.mDay.setText(item.get1(Contact.Field.DAY));
    holder.mContent.setText(item.get1(Contact.Field.CONTENT));
    holder.mMood.setImageResource(item.get2(Contact.Field.MOOD));
    holder.mWeather.setImageResource(item.get2(Contact.Field.WEATHER));

}

@Override
public int getItemCount() {
    return items.size();
}

public void setItem(List<Contact> items){
    this.items = items;
    notifyItemChanged (0, null);
}

public void addTestData(){

    Cursor cursor = RecycleFragment.dbHelper.D_getAllData();
    if(cursor != null) {
        if (cursor.moveToFirst()) {
            do{
                add(new Contact(cursor.getString(0),
                        cursor.getString(1),
                        cursor.getString(2),
                        cursor.getString(3),
                        cursor.getString(5),
                        cursor.getString(5),
                        cursor.getString(6),
                        cursor.getInt(7),
                        cursor.getInt(8)));

            }while (cursor.moveToNext());
        }
    }
}

public void add(Contact data){
    items.add(data);
    setItem(items);
}

}

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

DiaryFragment in button click event

case R.id.IV_diary_save:
            if(EDT_diary_title.getText().toString().trim() != null && EDT_diary_title.getText().toString().trim().length() != 0){

                if( EDT_diary_content.getText().toString().trim() != null && EDT_diary_content.getText().toString().trim().length() != 0){

                    dbHelper.D_insertData(EDT_diary_title.getText().toString(), EDT_diary_content.getText().toString(),
                            TV_diary_month.getText().toString(), TV_diary_date.getText().toString(), TV_diary_day.getText().toString(),
                            TV_diary_time.getText().toString(),
                            diaryInfoHelper.getMoodResourceId(SP_diary_weather.getSelectedItemPosition()),
                            diaryInfoHelper.getWeatherResourceId(SP_diary_mood.getSelectedItemPosition())
                    );

                    myAdapter.add(new Contact
                            (String.valueOf(dbHelper.getRow()),EDT_diary_title.getText().toString(), EDT_diary_content.getText().toString(),
                                    TV_diary_month.getText().toString(), TV_diary_date.getText().toString(), TV_diary_day.getText().toString(),
                                    TV_diary_time.getText().toString(),
                                    diaryInfoHelper.getMoodResourceId(SP_diary_weather.getSelectedItemPosition()),
                                    diaryInfoHelper.getWeatherResourceId(SP_diary_mood.getSelectedItemPosition())
                            ));

                    Toast.makeText(v.getContext(), "Success to Insert", Toast.LENGTH_SHORT).show();

                    ((TabActivity)getActivity()).getViewPager().setCurrentItem(0);

                    EDT_diary_title.setText("");
                    EDT_diary_content.setText("");

                }else {
                    Toast.makeText(v.getContext(), "Content is Empty ", Toast.LENGTH_SHORT).show();
                    EDT_diary_content.setText("");
                }
            }else {
                Toast.makeText(v.getContext(), "Title is Empty ", Toast.LENGTH_SHORT).show();
                EDT_diary_title.setText("");
            }
            break;

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

button click in DiaryFragment then

moving tab RecycleFragment and

RecycleFragment content immediately change new item insert data.

but now when button click in DiaryFragment
RecycleFragment not change.

Want changing RecycleFragment. I exit RecycleFragment and restart RecycleFragment.

please help me

thank

Body:
Do following Steps:

1. create and interface in dairy.
2. Write A method in it.
3. create the object of this interface and initialize.
4. create a setter for this object.
5. Now in Recycle Fragment implement this interface.
6. Now finally write you code inside the overridden method of interface

Let's  take this example.
for declaring an interface.

private getBusinessList list;

    public void setList(getBusinessList list) {
        this.list = list;
    }

    public interface getBusinessList {
        void result(boolean b, String msg,JSONArray array);
    }

now Inside recycler fragment.

public class SplashActivity extends AppCompatActivity implements ServerCall.getBusinessList

now initialize the interface object.

serverCall.setBusinessList(this);

This is my method for interface implementation.

 @Override
    public void getBuisnessList(boolean b, String msg,JSONArray array) {
        progressDialog.dismiss();
        if(b) {

           //displayBusinessList(array);
        }
        else {
            Log.e("Exception e",""+msg+" "+array.toString());

        }

    }

you can write your code inside that method.


来源: stackexchange

问:
Uploadcare not cropping properly
Trying to trigger the uploadcare php function with a jquery ajax call, and I get everything to work fine, except for the user selected crop region. It crops to the right ration, but defaults to top left all the time.

What am I missing to pass on the user selected crop area?

Here is the jQuery code that runs the script

```<code>$(function() {
  $('#avatar-uc').each(function() {
     $("#avatar-uc").find('.uploadcare-widget-button-open').html('<i class="fa fa-camera"></i> Edit Photo');
     $("#avatar-uc").find('.uploadcare-widget-button-remove').html('<i class="fa fa-camera"></i> Edit Photo');
       WidgetResetAvatar(
        uploadcare.SingleWidget($(this).children('input'))
      );
});
});
function WidgetResetAvatar(widget) {
  widget.onChange(function(file) {
    if (file) {
      file.done(function(fileInfo) {
        $.ajax({
            url: '/asset/create/avatar',
            method: 'POST',
            disablePreview: true,
            headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')},
            data: {uuid: fileInfo.uuid},
        })
        .done(function( data ) {
          $('#avatarPhoto').css('background-image', 'url("'+data.avatar_url+'")')
        });
      });
    }
    widget.value(null)
  });
}
</code>```

And the PHP Function

```<code>public function CreateAvatar(Request $request)
{
if (!Auth::check()) {
    return Response::json(array('message' => 'not logged in'));
}

$user = Auth::user();

if ($request->ajax()) {
    if (!empty($request->uuid)) {
        $api = app()->uploadcare;
        $original_file = $api->getFile($request->uuid);
        $cropped_file = $original_file->crop(150,150)->copy();
        $cropped_file->store();
        $cropped_file_url = $cropped_file->data['original_file_url'];
        $upload_url = "https://ucarecdn.com";
        $remove_upload_care_url = "";
        $cropped_file_path = str_replace($upload_url,
$remove_upload_care_url, $cropped_file_url);
    }
    else {
        $cropped_file_path = "";
    }

    $user->avatar = $cropped_file_path;
    $user->save();

    return Response::json(['avatar_url' => $cropped_file_url]);
}
}
</code>```

答:
For some reason,  crop() function does not accept coordinates for the cropping area, just to center it or not (see the code).

Easiest way is to build the URL by hand. Bonus points for sending PR to the library for accepting coordinates.

ContentLicense: CC BY-SA 3.0

Title: Uploadcare not cropping properly

Body:
Trying to trigger the uploadcare php function with a jquery ajax call, and I get everything to work fine, except for the user selected crop region. It crops to the right ration, but defaults to top left all the time.

What am I missing to pass on the user selected crop area?

Here is the jQuery code that runs the script

$(function() {
  $('#avatar-uc').each(function() {
     $("#avatar-uc").find('.uploadcare-widget-button-open').html(' Edit Photo');
     $("#avatar-uc").find('.uploadcare-widget-button-remove').html(' Edit Photo');
       WidgetResetAvatar(
        uploadcare.SingleWidget($(this).children('input'))
      );
});
});
function WidgetResetAvatar(widget) {
  widget.onChange(function(file) {
    if (file) {
      file.done(function(fileInfo) {
        $.ajax({
            url: '/asset/create/avatar',
            method: 'POST',
            disablePreview: true,
            headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')},
            data: {uuid: fileInfo.uuid},
        })
        .done(function( data ) {
          $('#avatarPhoto').css('background-image', 'url("'+data.avatar_url+'")')
        });
      });
    }
    widget.value(null)
  });
}

And the PHP Function

public function CreateAvatar(Request $request)
{
if (!Auth::check()) {
    return Response::json(array('message' => 'not logged in'));
}

$user = Auth::user();

if ($request->ajax()) {
    if (!empty($request->uuid)) {
        $api = app()->uploadcare;
        $original_file = $api->getFile($request->uuid);
        $cropped_file = $original_file->crop(150,150)->copy();
        $cropped_file->store();
        $cropped_file_url = $cropped_file->data['original_file_url'];
        $upload_url = "https://ucarecdn.com";
        $remove_upload_care_url = "";
        $cropped_file_path = str_replace($upload_url,
$remove_upload_care_url, $cropped_file_url);
    }
    else {
        $cropped_file_path = "";
    }

    $user->avatar = $cropped_file_path;
    $user->save();

    return Response::json(['avatar_url' => $cropped_file_url]);
}
}


问:
WCF service operations not updated
I´m creating a new WCF service.  I initially had only three operations.  But after some time I decided to add two more.  This operations doesn't appear in the Microsoft test client, neither in the list of operations when I try to add a service reference from my WPF client.  Also I tried to comment one of the initial operations.  It still apears in the Microsoft test client and can be invoked. I Tried also delete the dlls generated by the service and regenerate again.  No luck.  There are some kind of "cache" where Visual Studio stores the WCF services libraries that I can delete?

UPDATE:  I'm working with the service running in the ASP.NET devolopment server.

答:
SOLUTION HERE :

Make sure your dataContract does NOT contain any enum
(You can use integer instead)

Be sure to reference a project in the solution and not a dll on your disk

Remove your "bin" and "obj" folders

Recompile

In IIS recycle the application pool

In IIS restart your service

In IIS "Browse" your service

=> You got it

Title: WCF service operations not updated


问:
Invalid datetime format: 1292 Incorrect datetime value - Laravel 5.2
I'm getting this error when I insert these value into my database table:

```
SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value:
'24/06/2017' for column 'registration_from' at row 1
(SQL: insert into `campus_registrations` (`campus_major_class_id`,
`registration_from`, `registration_to`, `testing`, `announcement`,
`enrollment_from`, `enrollment_to`, `updated_at`, `created_at`) values (3,
24/06/2017, 27/06/2017, 13/07/2017, 01/08/2017, 05/09/2017, 31/01/2018,
 2017-06-07 09:39:31, 2017-06-07 09:39:31))
```

Do I have to intiate the datetime first or what?

答:
The error is here:

```<code>Incorrect datetime value: '24/06/2017' for column 'registration_from' at row 1
</code>```

the default format for date column in mysql is Y-m-d and for datetime is Y-m-d H:i:s. So change your date to this format and try again.

Body:
I'm getting this error when I insert these value into my database table:

SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value:
'24/06/2017' for column 'registration_from' at row 1
(SQL: insert into `campus_registrations` (`campus_major_class_id`,
`registration_from`, `registration_to`, `testing`, `announcement`,
`enrollment_from`, `enrollment_to`, `updated_at`, `created_at`) values (3,
24/06/2017, 27/06/2017, 13/07/2017, 01/08/2017, 05/09/2017, 31/01/2018,
 2017-06-07 09:39:31, 2017-06-07 09:39:31))

Do I have to intiate the datetime first or what?

Body:
The error is here:

Incorrect datetime value: '24/06/2017' for column 'registration_from' at row 1

the default format for date column in mysql is Y-m-d and for datetime is Y-m-d H:i:s. So change your date to this format and try again.


问:
How to find minimum of nonlinear, multivariate function using Newton's method (code not linear algebra)
I'm trying to do some parameter estimation and want to choose parameter estimates that minimize the square error in a predicted equation over about 30 variables.  If the equation were linear, I would just compute the 30 partial derivatives, set them all to zero, and use a linear-equation solver.  But unfortunately the equation is nonlinear and so are its derivatives.

If the equation were over a single variable, I would just use Newton's method (also known as Newton-Raphson).  The Web is rich in examples and code to implement Newton's method for functions of a single variable.

Given that I have about 30 variables, how can I program a numeric solution to this problem using Newton's method?  I have the equation in closed form and can compute the first and second derivatives, but I don't know quite how to proceed from there.  I have found a large number of treatments on the web, but they quickly get into heavy matrix notation.  I've found something moderately helpful on Wikipedia, but I'm having trouble translating it into code.

Where I'm worried about breaking down is in the matrix algebra and matrix inversions.  I can invert a matrix with a linear-equation solver but I'm worried about getting the right rows and columns, avoiding transposition errors, and so on.

To be quite concrete:

I want to work with tables mapping variables to their values.  I can write a function of such a table that returns the square error given such a table as argument.  I can also create functions that return a partial derivative with respect to any given variable.

I have a reasonable starting estimate for the values in the table, so I'm not worried about convergence.

I'm not sure how to write the loop that uses an estimate (table of value for each variable), the function, and a table of partial-derivative functions to produce a new estimate.

That last is what I'd like help with.  Any direct help or pointers to good sources will be warmly appreciated.

Edit: Since I have the first and second derivatives in closed form, I would like to take advantage of them and avoid more slowly converging methods like simplex searches.

答: My opinion is to use a stochastic optimizer, e.g., a Particle Swarm method.</p>

OwnerDisplayName: Norman Ramsey

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Norman Ramsey

OwnerDisplayName: Paul Nathan


问:
Why there are the same variables of mine with a ':' in Visual Studio auto complete list?
What's the difference between myVar and myVar: in VS auto-complete list while working with functions. Why the second one is added to this list ?

答:
In addition to what the others wrote: The first one is a (local) variable or field, while the last one is the name of the parameter of the called method. In code:</p>

```<code>private void MyFirstMethod(int myVar)
{
    Console.WriteLine(myVar);
}

private void MySecondMethod(int myVar)
{
    MyFirstMethod(myVar); // Call with the value of the parameter myVar
    MyFirstMethod(myVar: myVar); // Same as before, but explicitly naming the parameter

    MyFirstMethod(5); // Call with the value 5
    MyFirstMethod(myVar: 5); // Same as before, but explicitly naming the parameter
}
</code>```

Body:
In addition to what the others wrote: The first one is a (local) variable or field, while the last one is the name of the parameter of the called method. In code:

private void MyFirstMethod(int myVar)
{
    Console.WriteLine(myVar);
}

private void MySecondMethod(int myVar)
{
    MyFirstMethod(myVar); // Call with the value of the parameter myVar
    MyFirstMethod(myVar: myVar); // Same as before, but explicitly naming the parameter

    MyFirstMethod(5); // Call with the value 5
    MyFirstMethod(myVar: 5); // Same as before, but explicitly naming the parameter
}


问:
Both vertically and horizontally center of Bootsrap ui Modal
I'm trying to make a Bootstrap ui Modal that is both vertically and horizontally center align .

I tried this solution , that indeed vertically centered the modal , but when I tried it with my own template (with 800px) it lost its horizontally center:

i.e - http://plnkr.co/edit/vp3IWIcrpGG6ehH8JKVe?p=preview

How could I achieve this modal with vertically and horizontally center with my own template ?

Note - The width and height of the template is dynamic so the solution should be appropriate for any width and and height .

答:
I did just override .modal-dialog with

```<code>.modal .modal-dialog {
 max-width: 800px;
 width: 100%;
}
</code>```

this. Because it has fixed with:600px; which should be max-width:800px;

For smaller screens, I added margin auto so it doesn't go down.

```<code>@media (max-width: 767px){
  .modal .modal-dialog{
    margin:10px auto;
  }
}
</code>```

Plunker demo

Body:
I did just override .modal-dialog with

.modal .modal-dialog {
 max-width: 800px;
 width: 100%;
}

this. Because it has fixed with:600px; which should be max-width:800px;

For smaller screens, I added margin auto so it doesn't go down.

@media (max-width: 767px){
  .modal .modal-dialog{
    margin:10px auto;
  }
}

Plunker demo


问:
Debugging source files using chrome extension
I am trying to control the debugger using Chrome Extension.

I am using devtools-protocol and chrome extension documentation, but I have no idea how to implement them as I have not seen any samples of the methods in use. I used the sample extension from here which shows how to pause and resume the debugger only, but that's absolutely no use to me. I tried to implement some methods in the sample, but nothing happens.

```<code>function onDebuggerEnabled(debuggeeId) {
  chrome.debugger.sendCommand(debuggeeId, "Debugger.setBreakpointByUrl", {
        lineNumber: 45825,
        url: 'full https link to the js file from source tab'
  });
}
</code>```

The problem is that the js file I am trying to debug is loaded from the website inside the sources tab and it's huge, we talking 150k+ lines after its been formatted and it takes some time to load.

Now can anyone tell me how to simply add a break point inside the js file from the sources (USING CHROME EXTENSION) so it could be triggered on action which will then stops the debugger so I could change values etc?

答:
ok, for start you have to sendCommand Debugger.enable .. something like this:

```<code>var tabId = parseInt(window.location.search.substring(1));

window.addEventListener("load", function() {
  chrome.debugger.sendCommand({tabId:tabId}, "Debugger.enable");
  chrome.debugger.attach( tabId, "0.1" );
  chrome.debugger.onEvent.addListener(onEvent);
});
</code>```

then inside you onEvent you can set breaking points

```<code>function onEvent(debuggeeId, message, params) {
  if (tabId != debuggeeId.tabId) return;
  var res = Debugger.setBreakpointByUrl( 2, 'url-of-the-script-file' );
}
</code>```

I would strongly suggest to check the sniffing section on this page: https://chromedevtools.github.io/devtools-protocol/ because I was able to see the json that get returned via WS protocol and that will help you to do pretty much anything you want.. I can't build you full extension, you are on your own man,,

I guess that you need to add somekind of DOM elemnet with list of scripts that you'll parse from Network.getResponseBody and then somekind of UX tool to pick that scripts and let users to debugging,, that process could take you some time :(

hope I have steered you in the right direction, good luck!

Body:
I am trying to control the debugger using Chrome Extension.

I am using devtools-protocol and chrome extension documentation, but I have no idea how to implement them as I have not seen any samples of the methods in use. I used the sample extension from here which shows how to pause and resume the debugger only, but that's absolutely no use to me. I tried to implement some methods in the sample, but nothing happens.

function onDebuggerEnabled(debuggeeId) {
  chrome.debugger.sendCommand(debuggeeId, "Debugger.setBreakpointByUrl", {
        lineNumber: 45825,
        url: 'full https link to the js file from source tab'
  });
}

The problem is that the js file I am trying to debug is loaded from the website inside the sources tab and it's huge, we talking 150k+ lines after its been formatted and it takes some time to load.

Now can anyone tell me how to simply add a break point inside the js file from the sources (USING CHROME EXTENSION) so it could be triggered on action which will then stops the debugger so I could change values etc?

Body:
ok, for start you have to sendCommand Debugger.enable .. something like this:

var tabId = parseInt(window.location.search.substring(1));

window.addEventListener("load", function() {
  chrome.debugger.sendCommand({tabId:tabId}, "Debugger.enable");
  chrome.debugger.attach( tabId, "0.1" );
  chrome.debugger.onEvent.addListener(onEvent);
});

then inside you onEvent you can set breaking points

function onEvent(debuggeeId, message, params) {
  if (tabId != debuggeeId.tabId) return;
  var res = Debugger.setBreakpointByUrl( 2, 'url-of-the-script-file' );
}

I would strongly suggest to check the sniffing section on this page: https://chromedevtools.github.io/devtools-protocol/ because I was able to see the json that get returned via WS protocol and that will help you to do pretty much anything you want.. I can't build you full extension, you are on your own man,,

I guess that you need to add somekind of DOM elemnet with list of scripts that you'll parse from Network.getResponseBody and then somekind of UX tool to pick that scripts and let users to debugging,, that process could take you some time :(

hope I have steered you in the right direction, good luck!


问:
what is the difference between @Transactional and @Transactional(readOnly=true)
Can anyone tell me what is the difference between @Transactional and @Transactional(readOnly=true) in spring/hibernate.

Why we need to use @Transactional/@Transactional(readOnly=true) annotations in Service layer and not in DAO layer?

Please advise

答:
From Spring documentation:

true if the transaction is read-only.  Defaults to false.

This just serves as a hint for the actual transaction subsystem; it
  will not necessarily cause failure of write access attempts. A
  transaction manager which cannot interpret the read-only hint will not
  throw an exception when asked for a read-only transaction but rather
  silently ignore the hint.

Which means that readOnly flag if set to 'true' serves only as a hint for the transaction subsystem that your transaction will not attempt to modify any data.

@Transactional annotation is mostly used in the Service Layer, because your business methods can consist of many DAO methods calls that you might want to process in one transaction.

This question was already asked and you can read more about it here:
Where should "@Transactional" be place Service Layer or DAO


问:
Python create folders structure based on current date
i'm using the following var on my script to send output to one

```<code>output = "/opt/output"
</code>```

i want to adjust it to make the output relative to the date current date of trigger the script it should be structured like this

```<code>output = "/opt/output/year/month/day"
</code>```

i'm not sure if i'm using the correct way here i used the following approach

```<code>output = "/opt/output/" + today.strftime('%Y%m%d')
</code>```

any tips here

答:
today.strftime('%Y%m%d') would print todays date as 20170607. But I guess you want it printed as 2017/06/07. You could explicitly add the slashes and print it something like this?

output = "/opt/output/" + today.year +"/" + today.month + "/" + today.date

Body:
i'm using the following var on my script to send output to one

output = "/opt/output"

i want to adjust it to make the output relative to the date current date of trigger the script it should be structured like this

output = "/opt/output/year/month/day"

i'm not sure if i'm using the correct way here i used the following approach

output = "/opt/output/" + today.strftime('%Y%m%d')

any tips here


问:
How to serve pre-rendered data-bindable templates
There are a lot of data-binding client-side frameworks these days (Ember, Backbone, Knockout and Angular are the popular ones I'm aware of).

The problem with all these frameworks is the initial load. You have to mark your HTML up with placeholders, and depending on how it's done, the client will either see empty page chunks, or random {{ markup }}. Further, most of these templates are parsed client-side, rather than pre-compiled.

Ideally, when the user first comes to the site, they would be served some pre-rendered HTML with all the data filled in, and that would give them something to look at while all the pre-compiled JavaScript templates load and the data-bindings kick-in. From there on out, it would use client-side routing and we would just have JSON on the wire.

I can do half of this already with Jade or a handful of other template languages that can be rendered server or client-side. The thing I can't figure out is how I would get this to play nicely with one of those frameworks.

For example, in Knockout, your view might look like this:

```<code><p>First name: <strong data-bind="text: firstName"></strong></p>
<p>Last name: <strong data-bind="text: lastName"></strong></p>
</code>```

In Jade, I would define the same template like this:

```<code>p First Name
  b= firstName
p Last Name
  b= lastName
</code>```

Which, for the curious, gets compiled to this:

```<code>function anonymous(locals) {
    var buf = [];
    var locals_ = locals || {}, firstName = locals_.firstName, lastName = locals_.lastName;
    buf.push("<p>First Name <b>" + jade.escape(null == (jade.interp = firstName) ? "" : jade.interp) + "</b></p><p>Last Name <b>" + jade.escape(null == (jade.interp = lastName) ? "" : jade.interp) + "</b></p>");
    return buf.join("");
}
</code>```

Which is super quick to render either server- or client-side.

To get the data-binding to work, however, I would have to doubly annotate the source:

```<code>p(data-bind='text: firstName') First Name
  b= firstName
p(data-bind='text: lastName') Last Name
  b= lastName
</code>```

i.e., put each placeholder variable in there twice, in two different formats.

(Fortunately, most of these frameworks take some sort of JSON object for the View Model (I believe), which I could serve directly to Jade or the framework, so that part shouldn't be an issue.)

I would very much like to avoid that but I can't think of how this might be possible without writing my own templating language which has a strong dependency on the frontend framework.

Is there a way to do this without a lot of pain? Using any of the above frontends or any JS-compilable templating language? Perhaps via some plugins/extensions rather than having to redefine it at a core level?

答:
Angular 4+ has now Angular Universal, which allows SPA developed with Angular 2+ to be rendered in client side or in server side (with NodeJs or even Asp.Net Core).
The tricky thing is that ANYTHING that relies on window, sessionStore, localStore, etc. won't be executed in server side, because there is no browser in server side environment. So keep it in mind if you develop a SPA and are planning on rendering at server side to become SEO friendly.

React and VueJs are also frameworks/libraries that can be used for universal applications (to be rendered at server side and serve already rendered content to the browser)

Body:
There are a lot of data-binding client-side frameworks these days (Ember, Backbone, Knockout and Angular are the popular ones I'm aware of).

The problem with all these frameworks is the initial load. You have to mark your HTML up with placeholders, and depending on how it's done, the client will either see empty page chunks, or random {{ markup }}. Further, most of these templates are parsed client-side, rather than pre-compiled.

Ideally, when the user first comes to the site, they would be served some pre-rendered HTML with all the data filled in, and that would give them something to look at while all the pre-compiled JavaScript templates load and the data-bindings kick-in. From there on out, it would use client-side routing and we would just have JSON on the wire.

I can do half of this already with Jade or a handful of other template languages that can be rendered server or client-side. The thing I can't figure out is how I would get this to play nicely with one of those frameworks.

For example, in Knockout, your view might look like this:

First name:

Last name:

In Jade, I would define the same template like this:

p First Name
  b= firstName
p Last Name
  b= lastName

Which, for the curious, gets compiled to this:

function anonymous(locals) {
    var buf = [];
    var locals_ = locals || {}, firstName = locals_.firstName, lastName = locals_.lastName;
    buf.push("
First Name " + jade.escape(null == (jade.interp = firstName) ? "" : jade.interp) + "

Last Name " + jade.escape(null == (jade.interp = lastName) ? "" : jade.interp) + "
");
    return buf.join("");
}

Which is super quick to render either server- or client-side.

To get the data-binding to work, however, I would have to doubly annotate the source:

p(data-bind='text: firstName') First Name
  b= firstName
p(data-bind='text: lastName') Last Name
  b= lastName

i.e., put each placeholder variable in there twice, in two different formats.

(Fortunately, most of these frameworks take some sort of JSON object for the View Model (I believe), which I could serve directly to Jade or the framework, so that part shouldn't be an issue.)

I would very much like to avoid that but I can't think of how this might be possible without writing my own templating language which has a strong dependency on the frontend framework.

Is there a way to do this without a lot of pain? Using any of the above frontends or any JS-compilable templating language? Perhaps via some plugins/extensions rather than having to redefine it at a core level?


问:
Java - Which version was a .jar file built too?
Is there a way to find out the JDK version used to build a .jar file?</p>

答:
Most jars are built using the provided "jar" tool packaged with the jdk.

In SUN's JDK the provided "jar" tool will add a "Created-By" line in the embedded META-INF/MANIFEST.MF file.

That line will specify the version of the JDK that created the JAR (in my case "Created-By: 1.6.0_17 (Sun Microsystems Inc.)")

Other Java vendors tend to do the same.


答:
Since you're not using standard datetime format, define a mutator for each date. For example:</p>

```<code>public function setRegistrationFromAttribute($value)
{
    $this->attributes['registration_from'] =  Carbon::parse($value);
}
</code>```

Title: Invalid datetime format: 1292 Incorrect datetime value - Laravel 5.2

Body:
Since you're not using standard datetime format, define a mutator for each date. For example:

public function setRegistrationFromAttribute($value)
{
    $this->attributes['registration_from'] =  Carbon::parse($value);
}


问:
Excel formula vlookup
I need to fill in the column D using the information from column G (all in the first sheet) and the information from column A in the second sheet.

What needs to be returned to the column is the exact information found in the second sheet with the letter.

I have tried using vlookup with extract and other's but I always get N/A returned and im getting nervous.

Below are two screenshots of each sheet and at the bottom you will find an excel file uploaded with example data.

Excel file with example

答:
You can do this with an array. Remember to enter the formula with Ctrl+shift+enter</p>

```<code>=INDEX(ActiveCoupons!A2:A9,MATCH(G3,RIGHT(ActiveCoupons!A2:A9,LEN(ActiveCoupons!A2:A9)-1)*1,0))
</code>```

Title: Excel formula vlookup

Body:
You can do this with an array. Remember to enter the formula with Ctrl+shift+enter

=INDEX(ActiveCoupons!A2:A9,MATCH(G3,RIGHT(ActiveCoupons!A2:A9,LEN(ActiveCoupons!A2:A9)-1)*1,0))


问:
Random Non-White Colors That Look Okay As Background for Black Text
I'd like to generate random, non-white colors using hue, saturation and brightness that can be used as a background for black text. I've created a generator for random colors, but when I scan the numbers, I can't see any clear pattern in the colors that look too dark.

How can I generate random non-white background colors for black text? Feel free to answer with code or pseudo-code, but it's definitely not necessary.

答: I don't know color theory, but you can try randomly generating the 3 components in RGB (xxx,xxx,xxx) in a way that the sum of the components is greater than X (X depends of the contrast you want), and the convert to HSB.</p>


问:
React + Redux : reducer won't reload component
I wrote a generic Table component, instancied twice with two differents datasets. I use a Redux store to hydrate props and I try to delete a row when I click on it.

Components are well displayed and onClick function is fired and reducer is called. The new returned state returns the previous state without the element clicked.

My problem is that the components are not re-rendered.
According to the troubleshouting page (http://redux.js.org/docs/Troubleshooting.html), it seems that I don't mutate the previous state (maybe I just don't understand how to do), I'm calling the dispatch() function and my mapStateToProps seems to be right as datas are well displayed on the page load.

I tried to define initial state in reducer.js > table function instead of doing it with createStore function, I tried to split 'tables' reducer into 'domains' and 'hosts' reducers (duplicate code), I tried to not use combineReducers() as I have only one (but I will have more in the future), and I tried so many things so I can't remember.

I bet it's not a big deal but I just not able to figure out what's going on. Can you help me please ? Thank you very much.

reducer.js

```<code>import { combineReducers } from 'redux'
import { DELETE_DOMAIN, DELETE_HOST } from './actions'

function deleteItem(state, index) {
    let newState = Object.assign({}, state)

    newState.items.splice(index, 1)

    return newState
}

function tables(state = {}, action) {
    switch (action.type) {
        case DELETE_HOST:
            return Object.assign({}, state, {
                hosts: deleteItem(state.hosts, action.host)
            })

        case DELETE_DOMAIN:
            return Object.assign({}, state, {
                domains: deleteItem(state.domains, action.domain)
            })

        default:
            return state
    }
}

const reducers = combineReducers({
    tables,
})

export default reducers
</code>```

actions.js

```<code>export const DELETE_DOMAIN = 'DELETE_DOMAIN'
export const DELETE_HOST = 'DELETE_HOST'

export function deleteDomain(domain) {
    return { type: DELETE_DOMAIN, domain }
}

export function deleteHost(host) {
    return { type: DELETE_HOST, host }
}
</code>```

index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import App from './app';
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import reducers from './reducers'

const initialState = {
    tables: {
        domains: {
            headers: {
                id: 'Id',
                domain: 'Domain',
                host: 'Hoster',
            },
            items: [
                {
                    id: 1,
                    domain: 'dev.example.com',
                    host: 'dev',
                },
                {
                    id: 2,
                    domain: 'prod.example.com',
                    host: 'prod',
                }
            ]
        },
        hosts: {
            headers: {
                id: 'Id',
                label: 'Label',
                type: 'Type',
                hoster: 'Corporation',
            },
            items: [
                {
                    id: 1,
                    label: 'Server 1',
                    type: 'Server type',
                    hoster: 'Gandi',
                },
                {
                    id: 2,
                    label: 'Server 2',
                    type: 'Server type',
                    hoster: 'OVH',
                }
            ]
        }
    }
}

let store = createStore(reducers, initialState)

ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>,
    document.getElementById('root')
);
</code>```

app.js

```<code>import React from 'react';
import Domains from './modules/domains.js';
import Hosts from './modules/hosts.js';
import Nav from './modules/nav.js';
import {
  BrowserRouter as Router,
  Route,
} from 'react-router-dom'

export default class App extends React.Component {
    render() {
        return (
            <Router>
                <div className="container-fluid col-md-6">
                    <Nav />
                    <Route path="/domains" component={Domains}/>
                    <Route path="/hosts" component={Hosts}/>
                </div>
            </Router>
        );
    }
}
</code>```

domain.js

```<code>import React from 'react';
import Table from './../components/table.js';
import { connect } from 'react-redux'
import { deleteDomain } from './../actions'

const mapStateToProps = (state) => {
    return state.tables.domains
}

const mapDispatchToProps = (dispatch) => {
    return {
            onRowClick: (id) => {
                dispatch(deleteDomain(id))
            }
        }
}

class DomainsView extends React.Component {
    render() {
        return (
            <Table headers={this.props.headers} items={this.props.items} onRowClick={this.props.onRowClick} />
        )
    }
}

const Domains = connect(
    mapStateToProps,
    mapDispatchToProps,
)(DomainsView)

export default Domains
</code>```

hosts.js
Same as domains.js with differents const / class names and props

答:
Thanks a lot guys.
Using Lodash was the solution. However, I flattened my state as a good practice

Here are the result :

index.js

```<code>...
const initialState = {
    tables: {
        domains_headers: {
            id: 'Id',
            domain: 'Domain',
            host: 'Host',
        },
        domains_items: [
            {
                id: 1,
                domain: 'domain_1',
                host: 'host_domain_1',
            },
            {
                id: 2,
                domain: 'domain_2',
                host: 'host_domain_2',
            }
        ],
        hosts_headers: {
            id: 'Id',
            label: 'Label',
            type: 'Type',
            hoster: 'Corporation',
        },
        hosts_items: [
            {
                id: 1,
                label: 'label_host_1',
                type: 'type_host_1',
                hoster: 'hoster_host_1',
            },
            {
                id: 2,
                label: 'label_host_2',
                type: 'type_host_2',
                hoster: 'hoster_host_2',
            }
        ]
    }
}
...
</code>```

reducer.js

```<code>import { combineReducers } from 'redux'
import { DELETE_DOMAIN, DELETE_HOST } from './actions'
import { merge } from 'lodash'

function deleteItem(items, index) {
    items.splice(index, 1)

    return items
}

function tables(state = {}, action) {
    let newState = merge({}, state)

    switch (action.type) {
        case DELETE_HOST:
            newState.hosts_items = deleteItem(newState.hosts_items, action.host)
            return newState

        case DELETE_DOMAIN:
            newState.domains_items = deleteItem(newState.domains_items, action.domain)
            return newState

        default:
            return state
    }
}

const reducers = combineReducers({
    tables,
})

export default reducers
</code>```

domains.js

```<code>...
const mapStateToProps = (state) => {
    return {
        headers: state.tables.domains_headers,
        items: state.tables.domains_items
    }
}
...
</code>```

hosts.js

```<code>...
const mapStateToProps = (state) => {
    return {
        headers: state.tables.hosts_headers,
        items: state.tables.hosts_items
    }
}
...
</code>```

Body:
I wrote a generic Table component, instancied twice with two differents datasets. I use a Redux store to hydrate props and I try to delete a row when I click on it.

Components are well displayed and onClick function is fired and reducer is called. The new returned state returns the previous state without the element clicked.

My problem is that the components are not re-rendered.
According to the troubleshouting page (http://redux.js.org/docs/Troubleshooting.html), it seems that I don't mutate the previous state (maybe I just don't understand how to do), I'm calling the dispatch() function and my mapStateToProps seems to be right as datas are well displayed on the page load.

I tried to define initial state in reducer.js > table function instead of doing it with createStore function, I tried to split 'tables' reducer into 'domains' and 'hosts' reducers (duplicate code), I tried to not use combineReducers() as I have only one (but I will have more in the future), and I tried so many things so I can't remember.

I bet it's not a big deal but I just not able to figure out what's going on. Can you help me please ? Thank you very much.

reducer.js

import { combineReducers } from 'redux'
import { DELETE_DOMAIN, DELETE_HOST } from './actions'

function deleteItem(state, index) {
    let newState = Object.assign({}, state)

    newState.items.splice(index, 1)

    return newState
}

function tables(state = {}, action) {
    switch (action.type) {
        case DELETE_HOST:
            return Object.assign({}, state, {
                hosts: deleteItem(state.hosts, action.host)
            })

        case DELETE_DOMAIN:
            return Object.assign({}, state, {
                domains: deleteItem(state.domains, action.domain)
            })

        default:
            return state
    }
}

const reducers = combineReducers({
    tables,
})

export default reducers

actions.js

export const DELETE_DOMAIN = 'DELETE_DOMAIN'
export const DELETE_HOST = 'DELETE_HOST'

export function deleteDomain(domain) {
    return { type: DELETE_DOMAIN, domain }
}

export function deleteHost(host) {
    return { type: DELETE_HOST, host }
}

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './app';
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import reducers from './reducers'

const initialState = {
    tables: {
        domains: {
            headers: {
                id: 'Id',
                domain: 'Domain',
                host: 'Hoster',
            },
            items: [
                {
                    id: 1,
                    domain: 'dev.example.com',
                    host: 'dev',
                },
                {
                    id: 2,
                    domain: 'prod.example.com',
                    host: 'prod',
                }
            ]
        },
        hosts: {
            headers: {
                id: 'Id',
                label: 'Label',
                type: 'Type',
                hoster: 'Corporation',
            },
            items: [
                {
                    id: 1,
                    label: 'Server 1',
                    type: 'Server type',
                    hoster: 'Gandi',
                },
                {
                    id: 2,
                    label: 'Server 2',
                    type: 'Server type',
                    hoster: 'OVH',
                }
            ]
        }
    }
}

let store = createStore(reducers, initialState)

ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>,
    document.getElementById('root')
);

app.js

import React from 'react';
import Domains from './modules/domains.js';
import Hosts from './modules/hosts.js';
import Nav from './modules/nav.js';
import {
  BrowserRouter as Router,
  Route,
} from 'react-router-dom'

export default class App extends React.Component {
    render() {
        return (
            <Router>

                    <Route path="/domains" component={Domains}/>
                    <Route path="/hosts" component={Hosts}/>

            </Router>
        );
    }
}

domain.js

import React from 'react';
import Table from './../components/table.js';
import { connect } from 'react-redux'
import { deleteDomain } from './../actions'

const mapStateToProps = (state) => {
    return state.tables.domains
}

const mapDispatchToProps = (dispatch) => {
    return {
            onRowClick: (id) => {
                dispatch(deleteDomain(id))
            }
        }
}

class DomainsView extends React.Component {
    render() {
        return (

        )
    }
}

const Domains = connect(
    mapStateToProps,
    mapDispatchToProps,
)(DomainsView)

export default Domains

hosts.js
Same as domains.js with differents const / class names and props

Body:
Thanks a lot guys.
Using Lodash was the solution. However, I flattened my state as a good practice

Here are the result :

index.js

...
const initialState = {
    tables: {
        domains_headers: {
            id: 'Id',
            domain: 'Domain',
            host: 'Host',
        },
        domains_items: [
            {
                id: 1,
                domain: 'domain_1',
                host: 'host_domain_1',
            },
            {
                id: 2,
                domain: 'domain_2',
                host: 'host_domain_2',
            }
        ],
        hosts_headers: {
            id: 'Id',
            label: 'Label',
            type: 'Type',
            hoster: 'Corporation',
        },
        hosts_items: [
            {
                id: 1,
                label: 'label_host_1',
                type: 'type_host_1',
                hoster: 'hoster_host_1',
            },
            {
                id: 2,
                label: 'label_host_2',
                type: 'type_host_2',
                hoster: 'hoster_host_2',
            }
        ]
    }
}
...

reducer.js

import { combineReducers } from 'redux'
import { DELETE_DOMAIN, DELETE_HOST } from './actions'
import { merge } from 'lodash'

function deleteItem(items, index) {
    items.splice(index, 1)

    return items
}

function tables(state = {}, action) {
    let newState = merge({}, state)

    switch (action.type) {
        case DELETE_HOST:
            newState.hosts_items = deleteItem(newState.hosts_items, action.host)
            return newState

        case DELETE_DOMAIN:
            newState.domains_items = deleteItem(newState.domains_items, action.domain)
            return newState

        default:
            return state
    }
}

const reducers = combineReducers({
    tables,
})

export default reducers

domains.js

...
const mapStateToProps = (state) => {
    return {
        headers: state.tables.domains_headers,
        items: state.tables.domains_items
    }
}
...

hosts.js

...
const mapStateToProps = (state) => {
    return {
        headers: state.tables.hosts_headers,
        items: state.tables.hosts_items
    }
}
...


问:
Understand normalized squared euclidean distance?
I'm trying to understand the normalized squared euclidean distance formula from the Wolfram documentation:

```<code>1/2*Norm[(u-Mean[u])-(v-Mean[v])]^2/(Norm[u-Mean[u]]^2+Norm[v-Mean[v]]^2)
</code>```

I searched around for this formula on the web but couldn't find it. Can someone explain how this formula is derived?

答:
Further to Luca's comment, here is an example showing the "distance between two vectors where their lengths have been scaled to have unit norm".  It doesn't equal the normalised square Euclidean distance. The former is coloured blue in the graphic below.  The standard Euclidean distance is coloured red.

```<code>(* Leave this unevaluated to see symbolic expressions *)
{{a, b, c}, {d, e, f}} = {{1, 2, 3}, {3, 5, 10}};

N[EuclideanDistance[{a, b, c}, {d, e, f}]]
</code>```

7.87401

```<code>Norm[{a, b, c} - {d, e, f}]

SquaredEuclideanDistance[{a, b, c}, {d, e, f}]

Norm[{a, b, c} - {d, e, f}]^2

N[NormalizedSquaredEuclideanDistance[{a, b, c}, {d, e, f}]]
</code>```

0.25

```<code>(1/2 Norm[({a, b, c} - Mean[{a, b, c}]) - ({d, e, f} - Mean[{d, e, f}])]^2)/
 (Norm[{a, b, c} - Mean[{a, b, c}]]^2 + Norm[{d, e, f} - Mean[{d, e, f}]]^2)

1/2 Variance[{a, b, c} - {d, e, f}]/(Variance[{a, b, c}] + Variance[{d, e, f}])

{a2, b2, c2} = Normalize[{a, b, c}];
{d2, e2, f2} = Normalize[{d, e, f}];

N[EuclideanDistance[{a2, b2, c2}, {d2, e2, f2}]]
</code>```

0.120185

```<code>Graphics3D[{Line[{{0, 0, 0}, {1, 2, 3}}],
  Line[{{0, 0, 0}, {3, 5, 10}}],
  Red, Thick, Line[{{1, 2, 3}, {3, 5, 10}}],
  Blue, Line[{{a2, b2, c2}, {d2, e2, f2}}]},
 Axes -> True, AspectRatio -> 1,
 PlotRange -> {{0, 10}, {0, 10}, {0, 10}},
 AxesLabel -> Map[Style[#, Bold, 16] &, {"x", "y", "z"}],
 AxesEdge -> {{-1, -1}, {-1, -1}, {-1, -1}},
 ViewPoint -> {1.275, -2.433, -1.975},
 ViewVertical -> {0.551, -0.778, 0.302}]
</code>```

Body:
I'm trying to understand the normalized squared euclidean distance formula from the Wolfram documentation:

1/2*Norm[(u-Mean[u])-(v-Mean[v])]^2/(Norm[u-Mean[u]]^2+Norm[v-Mean[v]]^2)

I searched around for this formula on the web but couldn't find it. Can someone explain how this formula is derived?

Body:
Further to Luca's comment, here is an example showing the "distance between two vectors where their lengths have been scaled to have unit norm".  It doesn't equal the normalised square Euclidean distance. The former is coloured blue in the graphic below.  The standard Euclidean distance is coloured red.

(* Leave this unevaluated to see symbolic expressions *)
{{a, b, c}, {d, e, f}} = {{1, 2, 3}, {3, 5, 10}};

N[EuclideanDistance[{a, b, c}, {d, e, f}]]

7.87401

Norm[{a, b, c} - {d, e, f}]

SquaredEuclideanDistance[{a, b, c}, {d, e, f}]

Norm[{a, b, c} - {d, e, f}]^2

N[NormalizedSquaredEuclideanDistance[{a, b, c}, {d, e, f}]]

0.25

(1/2 Norm[({a, b, c} - Mean[{a, b, c}]) - ({d, e, f} - Mean[{d, e, f}])]^2)/
 (Norm[{a, b, c} - Mean[{a, b, c}]]^2 + Norm[{d, e, f} - Mean[{d, e, f}]]^2)

1/2 Variance[{a, b, c} - {d, e, f}]/(Variance[{a, b, c}] + Variance[{d, e, f}])

{a2, b2, c2} = Normalize[{a, b, c}];
{d2, e2, f2} = Normalize[{d, e, f}];

N[EuclideanDistance[{a2, b2, c2}, {d2, e2, f2}]]

0.120185

Graphics3D[{Line[{{0, 0, 0}, {1, 2, 3}}],
  Line[{{0, 0, 0}, {3, 5, 10}}],
  Red, Thick, Line[{{1, 2, 3}, {3, 5, 10}}],
  Blue, Line[{{a2, b2, c2}, {d2, e2, f2}}]},
 Axes -> True, AspectRatio -> 1,
 PlotRange -> {{0, 10}, {0, 10}, {0, 10}},
 AxesLabel -> Map[Style[#, Bold, 16] &, {"x", "y", "z"}],
 AxesEdge -> {{-1, -1}, {-1, -1}, {-1, -1}},
 ViewPoint -> {1.275, -2.433, -1.975},
 ViewVertical -> {0.551, -0.778, 0.302}]


问:
Create a historical sequence in talend big data jobs
I have a requirement to create sequence in talend.
Basically records are coming from a source file.
for each source row i want to create a unique number.
here is where it gets complicated.
when a new file comes next day , the talend should pick the last generated number and then increment it with 1.
for EX:
today the last generated sequence number is 100.
tomorrow the talend should generate sequence number from 100 . i.e. 101,102,103,104.....
This means talend should keep the history of previously generated last sequence number.

Thanks

答:
So, in such a case you have to persist this last sequence value somewhere, in the target database (if any) or in a dedicated file.
If the records are stored in a database, you can also get the max value from the corresponding field using the appropriate Select.

When you got the desired value, you need to store it in a global variable, then reuse this variable to initialize the sequence with something like:

Numeric.sequence("yourSequence", (Integer)globalMap.get("yourGlobal"), 1)

Hope this helps.


问:
How can I call a console command in web application in Yii 2.0
I have a console command to generate user report. I want to call the same from my web application. I am using Yii 2.0.0 beta version.I tried to follow answers given in this post  How to call a console command in web application action in Yii?

Since Yii 2.0 structure is very different from Yii 1.1 ,I get errors if I try to include command/userReportController.php .Can someone guide me on this?

答:
I think this is the simplest solution:</p>

```<code>$controller = new YourConsoleController(Yii::$app->controller->id, Yii::$app);
$controller->actionYourConsoleAction();
</code>```

Body:
I think this is the simplest solution:

$controller = new YourConsoleController(Yii::$app->controller->id, Yii::$app);
$controller->actionYourConsoleAction();


答:
I recommend you use the full timestamp instead of just using the date:

```<code>import os

mydir = os.path.join(output, datetime.datetime.now().strftime('%Y/%m/%d_%H-%M-%S'))
</code>```

It's recommended do it this way because what'd happen if your script runs more than once a day ? You should at least add a counter or something (if you don't want the full timestamp) which will increment some variable if the folder already exist.

You can read more about os.path.join here

As per creating a folder, you can do it like this:

```<code>if not os.path.exists(directory):
    os.makedirs(mydir)
</code>```

Title: Python create folders structure based on current date

Body:
I recommend you use the full timestamp instead of just using the date:

import os

mydir = os.path.join(output, datetime.datetime.now().strftime('%Y/%m/%d_%H-%M-%S'))

It's recommended do it this way because what'd happen if your script runs more than once a day ? You should at least add a counter or something (if you don't want the full timestamp) which will increment some variable if the folder already exist.

You can read more about os.path.join here

As per creating a folder, you can do it like this:

if not os.path.exists(directory):
    os.makedirs(mydir)


问:
Azure B2C SignIn Policy Custom Page URI is not called from OWIN
I have set sign-in policy custom page URI in blob storage, but it always go to Microsoft login page. I am using owin and code as follow :

```<code> public void ConfigureAuth(IAppBuilder app)
 {                 app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

 app.UseCookieAuthentication(new CookieAuthenticationOptions());

        app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                ClientId = clientId,
                Authority = authority,
                PostLogoutRedirectUri = postLogoutRedirectUri,
                RedirectUri = postLogoutRedirectUri,
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = context =>
                    {
                        context.HandleResponse();
                        context.Response.Redirect("/Error?message=" + context.Exception.Message);
                        return Task.FromResult(0);
                    }
                }
            });
    }
</code>```

Page is configured and it is working.

Following URL I am using

```<code> <add key="ida:AADInstance" value="https://login.microsoftonline.com/te/{0}/{1}/v2.0/.well-known/openid-configuration" />
</code>```

I using following sample :
     https://github.com/Azure-Samples/active-directory-b2c-dotnet-webapp-and-webapi

Getting following error:

```<code> Response status code does not indicate success: 404 (Not Found).

 Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

 Exception Details: System.Net.Http.HttpRequestException: Response status code does not indicate success: 404 (Not Found).
</code>```

Following is the Microsoft default login screen :

答:
If you're still getting the 404 error, you might consider checking the following:

Check your B2C policie's metadata endpoint and base your AADInstance url on that. Example in my policy I have the following:

So I would have an AADInstance url = "https://login.microsoftonline.com/{0}/v2.0/.well-known/openid-configuration?p={1}"

In your OpenIdConnectAuthenticationOptions, use the Metadata property instead of Authority and use the AADInstance above from your metadata endpoint.

new OpenIdConnectAuthenticationOptions
            {
                ClientId = clientId,
                MetadataAddress = String.Format(<AadInstance>, <Tenant>,<SignInPolicyId>),
                PostLogoutRedirectUri = postLogoutRedirectUri,
                RedirectUri = postLogoutRedirectUri,
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = context =>
                    {
                        context.HandleResponse();
                        context.Response.Redirect("/Error?message=" + context.Exception.Message);
                        return Task.FromResult(0);
                    }
                }
            });

Additional note, you mentioned in your question that you

have set sign-in policy custom page URI in blob storage, but it always go to Microsoft login page

Note that your custom HTML will only be used to change how the page looks, but the page will still have the login.microsoftonline.com domain. And also, as stated in the documentation, "currently, local account sign-in pages, its accompanying password reset pages and verification emails can be customized only by using the company branding feature" .

Body:
I have set sign-in policy custom page URI in blob storage, but it always go to Microsoft login page. I am using owin and code as follow :

 public void ConfigureAuth(IAppBuilder app)
 {                 app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

 app.UseCookieAuthentication(new CookieAuthenticationOptions());

        app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                ClientId = clientId,
                Authority = authority,
                PostLogoutRedirectUri = postLogoutRedirectUri,
                RedirectUri = postLogoutRedirectUri,
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = context =>
                    {
                        context.HandleResponse();
                        context.Response.Redirect("/Error?message=" + context.Exception.Message);
                        return Task.FromResult(0);
                    }
                }
            });
    }

Page is configured and it is working.

Following URL I am using

 <add key="ida:AADInstance" value="https://login.microsoftonline.com/te/{0}/{1}/v2.0/.well-known/openid-configuration" />

I using following sample :
     https://github.com/Azure-Samples/active-directory-b2c-dotnet-webapp-and-webapi

Getting following error:

 Response status code does not indicate success: 404 (Not Found).

 Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

 Exception Details: System.Net.Http.HttpRequestException: Response status code does not indicate success: 404 (Not Found).

Following is the Microsoft default login screen :


问:
the url not working in Laravel 5.4 route
Newbie to Laravel. In my project, my base url is 'http://localhost/laravel'. In my webpages I got a welcome page.
When I run

```<code>Route::get('/','UserController@index');
</code>```

It works.
Also

```<code>Route::get('/',function(){echo 'Succeed.';});
</code>```

I can see the Succeed.
When I change it into "foo" inside, everything fails.
neither

```<code>Route::get('/foo','UserController@index');
</code>```

nor

```<code>Route::get('/foo',function(){echo 'Succeed.';});
</code>```

It returns the NotFoundHttpException

My controller:

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

use Illuminate\Http\Request;
class UserController extends Controller
{
    // controller version, combined with route
    public function index(){
        return view('welcome');
    }
}
</code>```

Also I got welcome.blade.php inside the views.
Any suggestions for this problem?

答:
If you have moved your index.php and .htaccess from public folder to root folder, then you have to make changes in index.php file like

From:

require __DIR__.'../bootstrap/autoload.php';
$app = require_once __DIR__.'../bootstrap/app.php';```
</div>
</div>
</p>

<p><strong>to:</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>require __DIR__.'/bootstrap/autoload.php';
$app = require_once __DIR__.'/bootstrap/app.php';</code>```

For your Js and CSS files, You have to add "public" before file path. Like asset("public/js/app.js"), asset("public/css/app.css")
Now your route /foo will work.

Body:
Newbie to Laravel. In my project, my base url is 'http://localhost/laravel'. In my webpages I got a welcome page.
When I run

Route::get('/','UserController@index');

It works.
Also

Route::get('/',function(){echo 'Succeed.';});

I can see the Succeed.
When I change it into "foo" inside, everything fails.
neither

Route::get('/foo','UserController@index');

nor

Route::get('/foo',function(){echo 'Succeed.';});

It returns the NotFoundHttpException

My controller:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
class UserController extends Controller
{
    // controller version, combined with route
    public function index(){
        return view('welcome');
    }
}

Also I got welcome.blade.php inside the views.
Any suggestions for this problem?

Body:
If you have moved your index.php and .htaccess from public folder to root folder, then you have to make changes in index.php file like

From:

require __DIR__.'../bootstrap/autoload.php';
$app = require_once __DIR__.'../bootstrap/app.php';

to:

require __DIR__.'/bootstrap/autoload.php';
$app = require_once __DIR__.'/bootstrap/app.php';

For your Js and CSS files, You have to add "public" before file path. Like asset("public/js/app.js"), asset("public/css/app.css")
Now your route /foo will work.


问:
How to get the difference of weekdays?
I have this information:

```<code>Days  Dec'15  Jan'16
---------------------
Sun    27
Mon    28
Tue    29
Wed    30
Thu    31
Fri             1
Sat             2
</code>```

I have 1st Jan'16. So I have to get Fri and then the difference of days from the Sun. So, in this case, the difference should be 5. Because, before Friday there are 5 other days. So if I want to know it for 2nd Jan'16 it should be 6. And likewise.

How do I get it easy with date functions?

答:
The following code may help you

```<code>extension Date {

    func weekdayDiffence() -> Int {
        return Calendar.current.dateComponents([Calendar.Component.weekday], from: self).weekday ?? 0

    }
}
</code>```

Example

```<code>let d = Date().weekdayDiffence()
print(d)
</code>```

Title: How to get the difference of weekdays?

Body:
I have this information:

Days  Dec'15  Jan'16
---------------------
Sun    27
Mon    28
Tue    29
Wed    30
Thu    31
Fri             1
Sat             2

I have 1st Jan'16. So I have to get Fri and then the difference of days from the Sun. So, in this case, the difference should be 5. Because, before Friday there are 5 other days. So if I want to know it for 2nd Jan'16 it should be 6. And likewise.

How do I get it easy with date functions?

Body:
The following code may help you

extension Date {

    func weekdayDiffence() -> Int {
        return Calendar.current.dateComponents([Calendar.Component.weekday], from: self).weekday ?? 0

    }
}

Example

let d = Date().weekdayDiffence()
print(d)


问:
Convert jquery function to angular?
HTML:

```<code><div class="day-row" ng-repeat="(a, b) in $ctrl.myModel">
     <div class="col-lg">
         <a href="#" class="my-btn" aria-hidden="true" ng-click="$ctrl.toggleTimepickerPopup($event)"></a>
         <div class="the-container">
</code>```

LESS:

```<code>         &.set-time {
            .timepicker-container {
              display: block;
            }
          }
</code>```

JavaScript:

```<code>jquery(".my-btn").each(function () {
        if (jquery(this).is(jquery(event.target))) {
            jquery(this).parent().toggleClass('set-time');
        } else {
            jquery(this).parent().removeClass('set-time');
        }
    });
    event.preventDefault();
</code>```

This jquery function toggles the class for the link that
was clicked on, and removes the class for all other links in the ng-repeat.

I'd like to convert this to angular if possible. I had a similar question Toggle class of parent element using ng-click? where the selected answer worked, but now I need to extend it to not only toggle the class of the parent element, but to remove the class from the parents of all the sibling elements.

答:
Assuming b is your object, you can do something like this:

```<code><div class="day-row"
     ng-repeat="(a, b) in $ctrl.myModel">
     <div class="col-lg"
          ng-class="{ 'set-time': $ctrl.selected === b }">
         <a href="#" class="my-btn" aria-hidden="true"
            ng-click="$ctrl.selected = b"></a>
</code>```

This will toggle the class set-time on your div when the anchor is clicked and removes the class on all other elements.

Title: Convert jquery function to angular?

Body:
HTML:

LESS:

         &.set-time {
            .timepicker-container {
              display: block;
            }
          }

JavaScript:

jquery(".my-btn").each(function () {
        if (jquery(this).is(jquery(event.target))) {
            jquery(this).parent().toggleClass('set-time');
        } else {
            jquery(this).parent().removeClass('set-time');
        }
    });
    event.preventDefault();

This jquery function toggles the class for the link that
was clicked on, and removes the class for all other links in the ng-repeat.

I'd like to convert this to angular if possible. I had a similar question Toggle class of parent element using ng-click? where the selected answer worked, but now I need to extend it to not only toggle the class of the parent element, but to remove the class from the parents of all the sibling elements.

Body:
Assuming b is your object, you can do something like this:

<div class="day-row"
     ng-repeat="(a, b) in $ctrl.myModel">
     <div class="col-lg"
          ng-class="{ 'set-time': $ctrl.selected === b }">
         <a href="#" class="my-btn" aria-hidden="true"
            ng-click="$ctrl.selected = b"></a>

This will toggle the class set-time on your div when the anchor is clicked and removes the class on all other elements.


答: In the Jars MANIFEST.MF there may be a Build-Jdk property which should be what you're looking for.</p>

Title: Java - Which version was a .jar file built too?

Body: Is there a way to find out the JDK version used to build a .jar file?


问:
Jetty, force webapp to use different javax.mail from that one included in server lib/jndi
I'm quite newbie in Jetty, I've used Tomcat for many years, I would like to know the best practice to force my webapp to use javax.mail 1.5.5 since it is using javax.mail.glassfish-1.4.1.v201005082020.jar found on /srv/jetty/lib/jndi of jetty 9.3.10.

I don't believe it is safe replace that version with that one wanted by my webapplication, is it true?

At last if the best practice was to update the jar leaving it where it is, then should I remove that dependency from my webapp, in a way that in WEB-INF/lib it shouldn't be present?

Really thanks in advance

答:
I've received help from jetty-users, where contributor Jan Bartel said me:

I'd probably make a fresh jndi.mod, called eg my-jndi.mod that is
  copied from $JETTY_HOME/modules/jndi.mod and put it into
  $JETTY_BASE/modules. Then I'd change the last line of it to refer to a
  different lib, eg lib/my-jndi. So the module would look like this:

[name] myjndi

[depend] server

[lib] lib/jetty-jndi-${jetty.version}.jar lib/my-jndi/*.jar Put the
  javax.mail jars and any others you need into $JETTY_BASE/lib/my-jndi.
  Then all you need to do is to activate it with a java -jar
  ../start.jar --add-to-start=my-jndi and you're done. The good thing
  about this approach is that it is portable across any updates to
  different versions of jetty.

It was furthermore opened an issue


问:
how to add padding top in CSS pseudo element class::after
I want to add padding top to ::after and want to make it centered.

But it's not happening, this is what I get :

After using this css :

```<code>.list-unstyled li::after {
content: url(images/heartborder.png)
text-align:center;
padding-top: 30px;
}
</code>```

and this is my HTML CODE :

View / Edit Profile

You can view or edit your profile from here. Phone no., address, other information etc. etc.

```

答:
Your :after is set by default to display: inline so padding has no effect on it. Change it to inline-block or block and then it will.

To center it (as requested in comments), use flex on the div as below:

div {
  width: 50px;
  height: 50px;
  background: green;
  display: flex;
  justify-content: center;
}

div:after {
  content: "";
  width: 20px;
  height: 20px;
  background: blue;
  display: inline-block;
  padding-top: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div></div></code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to add padding top to ::after and want to make it centered.

But it's not happening, this is what I get :

After using this css :

.list-unstyled li::after {
content: url(images/heartborder.png)
text-align:center;
padding-top: 30px;
}

and this is my HTML CODE :

View / Edit Profile

You can view or edit your profile from here. Phone no., address, other information etc. etc.

Body:
Your :after is set by default to display: inline so padding has no effect on it. Change it to inline-block or block and then it will.

To center it (as requested in comments), use flex on the div as below:

div {
  width: 50px;
  height: 50px;
  background: green;
  display: flex;
  justify-content: center;
}

div:after {
  content: "";
  width: 20px;
  height: 20px;
  background: blue;
  display: inline-block;
  padding-top: 5px;
}

<div></div>


问:
Changing permanently html values using javascript?
Is it possible to change a html value permanently via javascript? I'm accessing a local file.

These are my codes:

```<code>function switchPic(){
  top.topPage.activeDef = top.topPage.document.getElementById('h1');
  top.topPage.activeDef.href = "pic2.html";

}
</code>```

答: If by "permanently" you mean changing the HTML file (on the server), the answer is no, you cannot do that with client-side JavaScript.</p>

Body:
Is it possible to change a html value permanently via javascript? I'm accessing a local file.

These are my codes:

function switchPic(){
  top.topPage.activeDef = top.topPage.document.getElementById('h1');
  top.topPage.activeDef.href = "pic2.html";

}


问:
Javascript: How to read data from remote js file?
I have a javascript file from remote server and it contains a variable which has data which I want to access.

Js file:

```<code>http://static.www.xxx.com/mydata/uXKojYEd9WXFpAasite/v4_3/3/d/itemjs
</code>```

Js file contain code like below

```<code>var MyItemData={"counts":{"q":1,"a":1,"r":2,"ar":4,"rr":0,"dq":1,"da":1,"c":0,"sdsd":0},"active":true};
</code>```

I've used below code but it's giving error for cross-origin request block.

```<code>var target = 'http://static.www.xxx.com/mydata/uXKojYEd9WXFpAasite/v4_3/3/d/itemjs';
jQuery.get(target, function(data) {
                                        alert(data);
                                    });
</code>```

Any other way to get the data ?

答:
If the remote file is javascript and contains variable declaration as in your example, it will be available for other scripts on web page including your script. You only need to load this file as javascript and listen for its load event. When it fires you'll have access to that variable.

So the code might look like this:

```<code>var script = document.createElement('script');
script.src = target;
script.addEventListener('load', function() {
    // at this moment MyItemData variable is accessible as MyItemData or window.MyItemData
});
</code>```

Body:
I have a javascript file from remote server and it contains a variable which has data which I want to access.

Js file:

http://static.www.xxx.com/mydata/uXKojYEd9WXFpAasite/v4_3/3/d/itemjs

Js file contain code like below

var MyItemData={"counts":{"q":1,"a":1,"r":2,"ar":4,"rr":0,"dq":1,"da":1,"c":0,"sdsd":0},"active":true};

I've used below code but it's giving error for cross-origin request block.

var target = 'http://static.www.xxx.com/mydata/uXKojYEd9WXFpAasite/v4_3/3/d/itemjs';
jQuery.get(target, function(data) {
                                        alert(data);
                                    });

Any other way to get the data ?

Body:
If the remote file is javascript and contains variable declaration as in your example, it will be available for other scripts on web page including your script. You only need to load this file as javascript and listen for its load event. When it fires you'll have access to that variable.

So the code might look like this:

var script = document.createElement('script');
script.src = target;
script.addEventListener('load', function() {
    // at this moment MyItemData variable is accessible as MyItemData or window.MyItemData
});


问:
Dynamic Persistent Volumes with Kuberenetes Heketi not working
I deployed heketi/gluster on Kubernetes 1.6 cluster. Then I followed the guide to create a StorageClass for dynamic persistent volumes, but no pv are created if I create pvc.

heketi and glusterfs pods running and working as expected if I use heketi-cli manually and create pv manually. The pv are also claimed by pvc.

I feels like that I'm missing a step, but I don't know which one. I followed the guides and I assumed that dynamic persistent volumes should "just work".

install heketi-cli and glusterfs-client

use ./gk-deploy -g

create StorageClass

create PVC
Did I missed a step?

StorageClass

```<code>$ kubectl get storageclasses
NAME      TYPE
slow      kubernetes.io/glusterfs

apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  creationTimestamp: 2017-06-07T06:54:35Z
  name: slow
  resourceVersion: "82741"
  selfLink: /apis/storage.k8s.io/v1/storageclassesslow
  uid: 2aab0a5c-4b4e-11e7-9ee4-001a4a3f1eb3
parameters:
  restauthenabled: "false"
  resturl: http://10.2.35.3:8080/
  restuser: ""
  restuserkey: ""
provisioner: kubernetes.io/glusterfs
</code>```

PVC

```<code>$ kubectl -nkube-system get pvc
NAME                          STATUS    VOLUME               CAPACITY   ACCESSMODES   STORAGECLASS   AGE
gluster1                      Bound     glusterfs-b427d1f1   1Gi        RWO                          15m
influxdb-persistent-storage   Pending                                                 slow           14h

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: |
      {"apiVersion":"v1","kind":"PersistentVolumeClaim","metadata":{"annotations":{"volume.beta.kubernetes.io/storage-class":"slow"},"labels":{"k8s-app":"influxGrafana"},"name":"influxdb-persistent-storage","namespace":"kube-system"},"spec":{"accessModes":["ReadWriteOnce"],"resources":{"requests":{"storage":"1Gi"}}}}
    volume.beta.kubernetes.io/storage-class: slow
    volume.beta.kubernetes.io/storage-provisioner: kubernetes.io/glusterfs
  creationTimestamp: 2017-06-06T16:48:46Z
  labels:
    k8s-app: influxGrafana
  name: influxdb-persistent-storage
  namespace: kube-system
  resourceVersion: "87638"
  selfLink: /api/v1/namespaces/kube-system/persistentvolumeclaims/influxdb-persistent-storage
  uid: 021b69c4-4ad8-11e7-9ee4-001a4a3f1eb3
spec:
  accessModes:
  - ReadWriteOnce
  resources:
    requests:
      storage: 1Gi
status:
  phase: Pending
</code>```

Sources:

https://github.com/gluster/gluster-kubernetes

http://blog.lwolf.org/post/how-i-deployed-glusterfs-cluster-to-kubernetes/

Environment:

```<code>$ kubectl cluster-info
Kubernetes master is running at https://andrea-master-0.muellerpublic.de:443
KubeDNS is running at https://andrea-master-0.muellerpublic.de:443/api/v1/proxy/namespaces/kube-system/services/kube-dns
kubernetes-dashboard is running at https://andrea-master-0.muellerpublic.de:443/api/v1/proxy/namespaces/kube-system/services/kubernetes-dashboard

$ heketi-cli cluster list
Clusters:
24dca142f655fb698e523970b33238a9

$ kubectl version
Client Version: version.Info{Major:"1", Minor:"6", GitVersion:"v1.6.4", GitCommit:"d6f433224538d4f9ca2f7ae19b252e6fcb66a3ae", GitTreeState:"clean", BuildDate:"2017-05-19T18:44:27Z", GoVersion:"go1.7.5", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"6", GitVersion:"v1.6.4+coreos.0", GitCommit:"8996efde382d88f0baef1f015ae801488fcad8c4", GitTreeState:"clean", BuildDate:"2017-05-19T21:11:20Z", GoVersion:"go1.7.5", Compiler:"gc", Platform:"linux/amd64"}
</code>```

答:
The problem was the slash in the StorageClass resturl.

resturl: http://10.2.35.3:8080/ must be resturl: http://10.2.35.3:8080

PS: o.O ....

Body:
I deployed heketi/gluster on Kubernetes 1.6 cluster. Then I followed the guide to create a StorageClass for dynamic persistent volumes, but no pv are created if I create pvc.

heketi and glusterfs pods running and working as expected if I use heketi-cli manually and create pv manually. The pv are also claimed by pvc.

I feels like that I'm missing a step, but I don't know which one. I followed the guides and I assumed that dynamic persistent volumes should "just work".

install heketi-cli and glusterfs-client

use ./gk-deploy -g

create StorageClass

create PVC
Did I missed a step?

StorageClass

$ kubectl get storageclasses
NAME      TYPE
slow      kubernetes.io/glusterfs

apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  creationTimestamp: 2017-06-07T06:54:35Z
  name: slow
  resourceVersion: "82741"
  selfLink: /apis/storage.k8s.io/v1/storageclassesslow
  uid: 2aab0a5c-4b4e-11e7-9ee4-001a4a3f1eb3
parameters:
  restauthenabled: "false"
  resturl: http://10.2.35.3:8080/
  restuser: ""
  restuserkey: ""
provisioner: kubernetes.io/glusterfs

PVC

$ kubectl -nkube-system get pvc
NAME                          STATUS    VOLUME               CAPACITY   ACCESSMODES   STORAGECLASS   AGE
gluster1                      Bound     glusterfs-b427d1f1   1Gi        RWO                          15m
influxdb-persistent-storage   Pending                                                 slow           14h

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: |
      {"apiVersion":"v1","kind":"PersistentVolumeClaim","metadata":{"annotations":{"volume.beta.kubernetes.io/storage-class":"slow"},"labels":{"k8s-app":"influxGrafana"},"name":"influxdb-persistent-storage","namespace":"kube-system"},"spec":{"accessModes":["ReadWriteOnce"],"resources":{"requests":{"storage":"1Gi"}}}}
    volume.beta.kubernetes.io/storage-class: slow
    volume.beta.kubernetes.io/storage-provisioner: kubernetes.io/glusterfs
  creationTimestamp: 2017-06-06T16:48:46Z
  labels:
    k8s-app: influxGrafana
  name: influxdb-persistent-storage
  namespace: kube-system
  resourceVersion: "87638"
  selfLink: /api/v1/namespaces/kube-system/persistentvolumeclaims/influxdb-persistent-storage
  uid: 021b69c4-4ad8-11e7-9ee4-001a4a3f1eb3
spec:
  accessModes:
  - ReadWriteOnce
  resources:
    requests:
      storage: 1Gi
status:
  phase: Pending

Sources:

https://github.com/gluster/gluster-kubernetes

http://blog.lwolf.org/post/how-i-deployed-glusterfs-cluster-to-kubernetes/

Environment:

$ kubectl cluster-info
Kubernetes master is running at https://andrea-master-0.muellerpublic.de:443
KubeDNS is running at https://andrea-master-0.muellerpublic.de:443/api/v1/proxy/namespaces/kube-system/services/kube-dns
kubernetes-dashboard is running at https://andrea-master-0.muellerpublic.de:443/api/v1/proxy/namespaces/kube-system/services/kubernetes-dashboard

$ heketi-cli cluster list
Clusters:
24dca142f655fb698e523970b33238a9

$ kubectl version
Client Version: version.Info{Major:"1", Minor:"6", GitVersion:"v1.6.4", GitCommit:"d6f433224538d4f9ca2f7ae19b252e6fcb66a3ae", GitTreeState:"clean", BuildDate:"2017-05-19T18:44:27Z", GoVersion:"go1.7.5", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"6", GitVersion:"v1.6.4+coreos.0", GitCommit:"8996efde382d88f0baef1f015ae801488fcad8c4", GitTreeState:"clean", BuildDate:"2017-05-19T21:11:20Z", GoVersion:"go1.7.5", Compiler:"gc", Platform:"linux/amd64"}


Title: convert csv to dictionary

Body:
I have the following csv file(total 20000 lines)

ozone,paricullate_matter,carbon_monoxide,sulfure_dioxide,nitrogen_dioxide,longitude,latitude,timestamp,avg_measured_time,avg_speed,median_measured_time,timestamp:1,vehicle_count,lat1,long1,lat2,long2,distance_between_2_points,duration_of_measurement,ndt_in_kmh
99,99,98,116,118,10.09351660921,56.1671665604395,1407575099.99998,0,0,0,1407575099.99998,0,56.1089513576227,10.1823955595246,56.1048021343541,10.1988040846558,1124,65,62
99,99,98,116,118,10.09351660921,56.1671665604395,1407575099.99998,0,0,0,1407575099.99998,0,56.10986429895,10.1627288048935,56.1089513576227,10.1823955595246,1254,71,64
99,99,98,116,118,10.09351660921,56.1671665604395,1407575099.99998,0,0,0,1407575099.99998,0,56.1425188527673,10.1868802625656,56.1417522836526,10.1927236478157,521,62,30
99,99,98,116,118,10.09351660921,56.1671665604395,1407575099.99998,18,84,18,1407575099.99998,1,56.1395320665735,10.1772034087371,56.1384485157567,10.1791506011887,422,50,30

I want to convert this into a dictionary like

{'ozone': [99,99,99,99], 'paricullate_matter': [99,99,99,99],'carbon_monoxide': [98,98,98,98],etc....}

What i have tried

import csv

reader = csv.DictReader(open('resulttable.csv'))

output = open("finalprojdata.py","w")

result = {}
for row in reader:
    for column, value in row.iteritems():
        result.setdefault(column, []).append(float(value))
output.write(str(result))

The output am getting is consisting of only few dictionaries. Like from

{'vehicle_count': [0,0,0,1], 'lat1': etc}

The whole csv file is not getting converted to dictionary.

Body:
from collections import defaultdict
import csv

columns = defaultdict(list)
with open('test.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        for (k,v) in row.items():
             columns[k].append(v)

    print columns

#Output

defaultdict(<type 'list'>, {'vehicle_count': ['0', '0', '0', '1'], 'lat1': ['56.1089513576227', '56.10986429895', '56.1425188527673', '56.1395320665735'], 'lat2': ['56.1048021343541', '56.1089513576227', '56.1417522836526', '56.1384485157567'], 'paricullate_matter': ['99', '99', '99', '99'], 'timestamp': ['1407575099.99998', '1407575099.99998', '1407575099.99998', '1407575099.99998'], 'long1': ['10.1823955595246', '10.1627288048935', '10.1868802625656', '10.1772034087371'], 'longitude': ['10.09351660921', '10.09351660921', '10.09351660921', '10.09351660921'], 'nitrogen_dioxide': ['118', '118', '118', '118'], 'ozone': ['99', '99', '99', '99'], 'latitude': ['56.1671665604395', '56.1671665604395', '56.1671665604395', '56.1671665604395'], 'timestamp:1': ['1407575099.99998', '1407575099.99998', '1407575099.99998', '1407575099.99998'], 'distance_between_2_points': ['1124', '1254', '521', '422'], 'long2': ['10.1988040846558', '10.1823955595246', '10.1927236478157', '10.1791506011887'], 'avg_measured_time': ['0', '0', '0', '18'], 'carbon_monoxide': ['98', '98', '98', '98'], 'ndt_in_kmh': ['62', '64', '30', '30'], 'avg_speed': ['0', '0', '0', '84'], 'sulfure_dioxide': ['116', '116', '116', '116'], 'duration_of_measurement': ['65', '71', '62', '50'], 'median_measured_time': ['0', '0', '0', '18']})


问:
Generic list and for-each loop
I am using a  generic class TestThrows< T > with a containing function that returns a generic list . My problem is i am unable to compile this program and it is throwing following error :

Type mismatch: cannot convert from element type Object to Throwable

```<code>public class Test
{
    public static void main( String[] args )
    {
        TestThrows testThrows = new TestThrows();

        // compile error on the next line
        for ( Throwable t : testThrows.getExceptions() )
        {
            t.toString();
        }
    }

    static class TestThrows< T >
    {
        public List< Throwable > getExceptions()
        {
            List< Throwable > exceptions = new ArrayList< Throwable >();
            return exceptions;
        }
    }
}
</code>```

I am not sure why is this error as i am using generic list ?

答:
You declared a generic type parameter T for TestThrows, which you never use.

That makes the type of TestThrows testThrows = new TestThrows() a raw type,
which causes the return type of getExceptions() to also be a raw List instead of List<Throwable>, so iterating overtestThrows.getExceptions()returnsObjectreferences instead ofThrowable` references, and your loop doesn't pass compilation.

Just change

```<code>static class TestThrows< T >
{
    public List< Throwable > getExceptions()
    {
        List< Throwable > exceptions = new ArrayList< Throwable >();
        return exceptions;
    }
}
</code>```

to

```<code>static class TestThrows
{
    public List< Throwable > getExceptions()
    {
        List< Throwable > exceptions = new ArrayList< Throwable >();
        return exceptions;
    }
}
</code>```

since you are not using T anyway.

If you do need T, you should change

```<code>TestThrows testThrows = new TestThrows();
</code>```

to

```<code>TestThrows<SomeType> testThrows = new TestThrows<>();
</code>```

Title: Generic list and for-each loop

Body:
I am using a  generic class TestThrows< T > with a containing function that returns a generic list . My problem is i am unable to compile this program and it is throwing following error :

Type mismatch: cannot convert from element type Object to Throwable

public class Test
{
    public static void main( String[] args )
    {
        TestThrows testThrows = new TestThrows();

        // compile error on the next line
        for ( Throwable t : testThrows.getExceptions() )
        {
            t.toString();
        }
    }

    static class TestThrows< T >
    {
        public List< Throwable > getExceptions()
        {
            List< Throwable > exceptions = new ArrayList< Throwable >();
            return exceptions;
        }
    }
}

I am not sure why is this error as i am using generic list ?

Body:
You declared a generic type parameter T for TestThrows, which you never use.

That makes the type of TestThrows testThrows = new TestThrows() a raw type,
which causes the return type of getExceptions() to also be a raw List instead of List<Throwable>, so iterating overtestThrows.getExceptions()returnsObjectreferences instead ofThrowable` references, and your loop doesn't pass compilation.

Just change

static class TestThrows< T >
{
    public List< Throwable > getExceptions()
    {
        List< Throwable > exceptions = new ArrayList< Throwable >();
        return exceptions;
    }
}

to

static class TestThrows
{
    public List< Throwable > getExceptions()
    {
        List< Throwable > exceptions = new ArrayList< Throwable >();
        return exceptions;
    }
}

since you are not using T anyway.

If you do need T, you should change

TestThrows testThrows = new TestThrows();

to

TestThrows<SomeType> testThrows = new TestThrows<>();