问:
Android - Recyclerview shared element transition item position
I hope you could help me with this issue. I have two fragments, the first one is a recyclerview with several images, the second fragment is the details view of this images. If user clicks on an image the app does a fragment transaction and the details are displayed.

I have implemented a shared element transition between the fragments successfully, if I click the little image on the 1st fragment it gets bigger and moves to its final position on the details view.

Well then, here's the issue, the initial position of the image is not the expected, it starts moving a few pixels from its original position, when I click the image jumps a little bit to the right and to the bottom.

Why is this happening? its annoying!

The transition xml:

```<code><transitionSet xmlns:android="http://schemas.android.com/apk/res/android">
    <changeTransform />
    <changeBounds />
</transitionSet>
</code>```

If I do the same for a button outside the recyclerview it works perfectly. Is this some kind of bug in the recyclerview?

答:
I solved this problem by following this article Shared Element Transitions - Part 4: RecyclerView, which shows codes snips and give detailed explanation.

make sure the android:transitionName between shared elements must be the same, and also has to be unique in the view hierarchy.

As for RecyclerView to Fragment, If we set the transitionName in XML then all ImageView in the gallery would have the same one, which means when we came back to the gallery the framework would have no idea where to move the image to.

Since the item position is unique, so it's best to use position here to set transitionName in onBindViewHolder.

Body:
I hope you could help me with this issue. I have two fragments, the first one is a recyclerview with several images, the second fragment is the details view of this images. If user clicks on an image the app does a fragment transaction and the details are displayed.

I have implemented a shared element transition between the fragments successfully, if I click the little image on the 1st fragment it gets bigger and moves to its final position on the details view.

Well then, here's the issue, the initial position of the image is not the expected, it starts moving a few pixels from its original position, when I click the image jumps a little bit to the right and to the bottom.

Why is this happening? its annoying!

The transition xml:

<transitionSet xmlns:android="http://schemas.android.com/apk/res/android">
    <changeTransform />
    <changeBounds />
</transitionSet>

If I do the same for a button outside the recyclerview it works perfectly. Is this some kind of bug in the recyclerview?


来源: stackexchange

问:
To convert Excel into CSV efficiently in ruby
I used the spreadsheet gem to do this. It works but it can be very slow at times .I even tried the Roo gem, but that didn't improve the performance. Is there a better way to do this job? The weird thing is that some worksheets in the same excel work faster and some worksheets work very slowly, even taking up to 1 hour.

Can we use open office to open each worksheet(tab) in a single excel and convert them to csv much faster? If yes, how would I do it in ruby?

Or is there an even better solution?

Just adding a small example I tried with Roo gem

```<code>xls = Roo::Excel.new(source_excel_file)
xls.each_with_pagename do |name, sheet|
  # p sheet.to_csv(File.join(dest_csv_dir,name + ".csv"))
  #sheet.parse(:clean => true)#.to_csv(File.join(dest_csv_dir,name + ".csv"))
  puts name
  puts sheet.parse(:clean => true)
end
</code>```

答:
```<code>xls_file = Roo::Excelx.new('test.xlsx')
CSV.open('test.csv') do |csv|
    (2..xls_file.last_row).each do |i| # if you do not need header otherwise (1..xls_file.last_row)
        csv << a.row(i)
    end
end
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I used the spreadsheet gem to do this. It works but it can be very slow at times .I even tried the Roo gem, but that didn't improve the performance. Is there a better way to do this job? The weird thing is that some worksheets in the same excel work faster and some worksheets work very slowly, even taking up to 1 hour.

Can we use open office to open each worksheet(tab) in a single excel and convert them to csv much faster? If yes, how would I do it in ruby?

Or is there an even better solution?

Just adding a small example I tried with Roo gem

xls = Roo::Excel.new(source_excel_file)
xls.each_with_pagename do |name, sheet|
  # p sheet.to_csv(File.join(dest_csv_dir,name + ".csv"))
  #sheet.parse(:clean => true)#.to_csv(File.join(dest_csv_dir,name + ".csv"))
  puts name
  puts sheet.parse(:clean => true)
end


问:
Logging without loss of time
Greetz fellows!

I'm looking for a way to log actions of a CLI script without losing time. I did some benchmarks and I figured out that by echoing someting after each action, the script will be nearly 2x slower and by appending actions to a log file it'll be 17x times slower.

So, anyone has a solution?

答:
If you are using CLI, I guess you can test with this:

```<code>YOUR_SCRIPT.php > /tmp/log.txt &
</code>```

Inside YOUR_SCRIPT.php

```<code><?
  /* some action */
  echo date('r').some_action_1()."\n";   <-- this is bad  # REMARK 1
  echo date('r').some_action_2()."\n";

  echo date('r'), some_action_1(), "\n"; <-- this is nice # REMARK 2
  echo date('r'), some_action_2(), "\n";
?>
</code>```

And monitor using

```<code>tail -f /tmp/log.txt
</code>```

The reason REMARK 1 slow is because function execute first, while REMAKR 2 does not (output first)

ContentLicense: CC BY-SA 2.5

Title: Logging without loss of time

Body:
If you are using CLI, I guess you can test with this:

YOUR_SCRIPT.php > /tmp/log.txt &

Inside YOUR_SCRIPT.php

<?
  /* some action */
  echo date('r').some_action_1()."\n";   <-- this is bad  # REMARK 1
  echo date('r').some_action_2()."\n";

  echo date('r'), some_action_1(), "\n"; <-- this is nice # REMARK 2
  echo date('r'), some_action_2(), "\n";
?>

And monitor using

tail -f /tmp/log.txt

The reason REMARK 1 slow is because function execute first, while REMAKR 2 does not (output first)


问:
ReferenceError: navigator is not defined in angular4 with server side rendering
I am using simpleMDE editor with my angular 4 Server side rendering application and getting the reference of textarea using

```<code>@ViewChild('simpleMDE') textarea : ElementRef;
</code>```

and initializing it in ngAfterViewInit()

```<code>   this.simplemde = new SimpleMDE(
      {
          element: this.textarea.nativeElement.value,
      })
</code>```

in Template in am using textarea like this

```<code><textarea id="simpleMDE" #simpleMDE></textarea>
</code>```

While starting the server its throwing error saying

```<code>projectpath\node_modules\codemirror\lib\codemirror.js:11
        typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
                                                                                ^
ReferenceError: navigator is not defined
    at projectpath\node_modules\codemirror\lib\codemirror.js:18:17
</code>```

Please suggest something, I stuck here.
 GitHub Repo

答:
Here is how I handle this sorta problem.
To me, server render is only for SEO purpose. And stuff like codemirror doesn't really do anything with SEO. Therefore, my approach is "not to render it on the server side".

 ref

The basic structure is like above illustration.

You have 2 boot files, one for server rendering and the other for client rendering.

Therefore, you actually can have different application modules for each boot file.

In the application module for server render, you can use a mock component to replace the component that uses browser objects and use the real component for client side.

This way you don't need to worry about the problematic component on server render.

Another solution is to use webpack to handle those browser objects.

something like this ref

```<code>module: {
  rules: [
    {
      test: /@angular(\\|\/)material/, use: "imports-loader?window=>global,CSS=>null,navigator=>{get userAgent(){return Zone.current.get('req')['headers']['user-agent'];}}"
    }
  ]
}
</code>```

Personally, I prefer the first solution. The second is kinda hacky to me and rendering a component that has nothing to do with SEO on server side doesn't really give us any benefit.

Body:
I am using simpleMDE editor with my angular 4 Server side rendering application and getting the reference of textarea using

@ViewChild('simpleMDE') textarea : ElementRef;

and initializing it in ngAfterViewInit()

   this.simplemde = new SimpleMDE(
      {
          element: this.textarea.nativeElement.value,
      })

in Template in am using textarea like this

<textarea id="simpleMDE" #simpleMDE></textarea>

While starting the server its throwing error saying

projectpath\node_modules\codemirror\lib\codemirror.js:11
        typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
                                                                                ^
ReferenceError: navigator is not defined
    at projectpath\node_modules\codemirror\lib\codemirror.js:18:17

Please suggest something, I stuck here.
 GitHub Repo

Body:
Here is how I handle this sorta problem.
To me, server render is only for SEO purpose. And stuff like codemirror doesn't really do anything with SEO. Therefore, my approach is "not to render it on the server side".

 ref

The basic structure is like above illustration.

You have 2 boot files, one for server rendering and the other for client rendering.

Therefore, you actually can have different application modules for each boot file.

In the application module for server render, you can use a mock component to replace the component that uses browser objects and use the real component for client side.

This way you don't need to worry about the problematic component on server render.

Another solution is to use webpack to handle those browser objects.

something like this ref

module: {
  rules: [
    {
      test: /@angular(\\|\/)material/, use: "imports-loader?window=>global,CSS=>null,navigator=>{get userAgent(){return Zone.current.get('req')['headers']['user-agent'];}}"
    }
  ]
}

Personally, I prefer the first solution. The second is kinda hacky to me and rendering a component that has nothing to do with SEO on server side doesn't really give us any benefit.


问:
How to correctly wrap few TD tags for JSXTransformer?
I have an array with items and I want to make something like this:

```<code><tr>
(until have items in array
<td></td><td></td>)
</tr>
</code>```

But if I do that, I get an JSXTransformer error :

Adjacent XJS elements must be wrapped in an enclosing tag

Working version:

```<code>{rows.map(function (rowElement){
    return (<tr key={trKey++}>
        <td className='info' key={td1stKey++}>{rowElement.row[0].value}</td><td key={td2ndKey++}>{rowElement.row[0].count}</td>
        <td className='info' key={td1stKey++}>{rowElement.row[1].value}</td><td key={td2ndKey++}>{rowElement.row[1].count}</td>
        <td className='info' key={td1stKey++}>{rowElement.row[2].value}</td><td key={td2ndKey++}>{rowElement.row[2].count}</td>
        <td className='info' key={td1stKey++}>{rowElement.row[3].value}</td><td key={td2ndKey++}>{rowElement.row[3].count}</td>
        <td className='info' key={td1stKey++}>{rowElement.row[4].value}</td><td key={td2ndKey++}>{rowElement.row[4].count}</td>
                 .......
        </tr>);
})}
</code>```

I tried this one. But with
 enclosing tag it doesn't work fine.

Answer here:
Uncaught Error: Invariant Violation: findComponentRoot(..., ...$110): Unable to find element. This probably means the DOM was unexpectedly mutated

```<code><tbody>
    {rows.map(function (rowElement){
        return (<tr key={trKey++}>
        {rowElement.row.map(function(ball){
            console.log('trKey:'+trKey+' td1stKey'+td1stKey+' ball.value:'+ball.value+' td2ndKey:'+td2ndKey+' ball.count:'+ball.count);
            return(<div key={divKey++}>
                <td className='info' key={td1stKey++}>{ball.value}</td><td key={td2ndKey++}>{ball.count}</td>
            </div>);
        })}
        </tr>);
    })}
</tbody>
</code>```

Please, advise me how to properly wrap few TD tags!
  I tried use a guide Dynamic Children, but JSXTransformer doesn't allow me do that.

答:
Here is how you will do it</p>

```<code><tbody>
    {this.props.rows.map((row, i) =>
      <tr key={i}>
        {row.map((col, j) =>
          <td key={j}>{col}</td>
        )}
      </tr>
    )}
</tbody>
</code>```

Body:
I have an array with items and I want to make something like this:

(until have items in array
		)

But if I do that, I get an JSXTransformer error :

Adjacent XJS elements must be wrapped in an enclosing tag

Working version:

{rows.map(function (rowElement){
    return (

        {rowElement.row[0].value}	{rowElement.row[0].count}
        {rowElement.row[1].value}	{rowElement.row[1].count}
        {rowElement.row[2].value}	{rowElement.row[2].count}
        {rowElement.row[3].value}	{rowElement.row[3].count}
        {rowElement.row[4].value}	{rowElement.row[4].count}
                 .......

);
})}

I tried this one. But with
 enclosing tag it doesn't work fine.

Answer here:
Uncaught Error: Invariant Violation: findComponentRoot(..., ...$110): Unable to find element. This probably means the DOM was unexpectedly mutated

    {rows.map(function (rowElement){
        return (

        {rowElement.row.map(function(ball){
            console.log('trKey:'+trKey+' td1stKey'+td1stKey+' ball.value:'+ball.value+' td2ndKey:'+td2ndKey+' ball.count:'+ball.count);
            return(

                {ball.value}	{ball.count}

);
        })}

);
    })}

Please, advise me how to properly wrap few TD tags!
  I tried use a guide Dynamic Children, but JSXTransformer doesn't allow me do that.

Body:
Here is how you will do it

<tbody>
    {this.props.rows.map((row, i) =>
      <tr key={i}>
        {row.map((col, j) =>
          <td key={j}>{col}</td>
        )}
      </tr>
    )}
</tbody>


问:
angularjs input fill issue
trying to make a simple calculator, but have some issues.
So i can not fill the input value by keyboard, also i have two errors ([ngModel:nonassign] when i load the page ,and  when i am trying to fill by keyboard the input value -

this.$$ngModelSet is not a function

I hope someone can help me out.

```<code><div class="container" ng-controller="calcCtrl">
    <div class="content">
    <br><br><br>
    <input type="text" ng-model="formula.join('')" ></input>
    <br><br><span class="content_tab tab"></span> <br>
    <button  ng-click='add(7)'>7</button>
    <button  ng-click='add(8)'>8</button>
    <button  ng-click='add(9)'>9</button>
    <button  ng-click='add("/")'>/</button>
    <br>
    <button  ng-click='add(4)'>4</button>
    <button ng-click='add(5)'>5</button>
    <button  ng-click='add(6)'>6</button>
    <button  ng-click='add("*")'>*</button>
    <br>
    <button  ng-click='add(1)'>1</button></td>
    <button  ng-click='add(2)'>2</button></td>
    <button  ng-click='add(3)'>3</button></td>
    <button  ng-click='add("-")'>-</button></td>
    <br>
    <button  ng-click='add(0)'>0</button>
    <button  ng-click='add(".")'>.</button>
    <td rowspan='2'><button  ng-click='add("+")'>+</button>
    <button ng-click="eval()">=</button>
    <br>
    <button  ng-click="remove()">CLEAR</button>
</div>

app.controller('calcCtrl',  function($scope) {
    $scope.formula = ['0'];
    $scope.add = function(item) {
    if ($scope.formula == '0') $scope.formula = [item];
    else $scope.formula.push(item);
};
    $scope.remove = function() {
    $scope.formula.pop();
    if($scope.formula.length == 0) $scope.formula = ['0'];
};
    $scope.eval = function() {
    var result = eval($scope.formula.join(''));
    $scope.formula = [result];
};

    });
</code>```

答:
You get that error because you didn't put a variable assignable in ng-model.
So change ng-model="formula.join('')" to use a variable: eg: ng-model="total"

and in your controller, for each calculation, just assign this variable to formula.join('')

```<code>$scope.add = function(item) {
    if ($scope.formula == '0') $scope.formula = [item];
    else $scope.formula.push(item);
    $scope.total = $scope.formula.join('');
  };
  $scope.remove = function() {
    $scope.formula.pop();
    if ($scope.formula.length == 0) $scope.formula = ['0'];
    $scope.total = $scope.formula.join('');
  };
  $scope.eval = function() {
    var result = eval($scope.formula.join(''));
    $scope.formula = [result];
    $scope.total = $scope.formula.join('');
  };
</code>```

Title: angularjs input fill issue

Body:
trying to make a simple calculator, but have some issues.
So i can not fill the input value by keyboard, also i have two errors ([ngModel:nonassign] when i load the page ,and  when i am trying to fill by keyboard the input value -

this.$$ngModelSet is not a function

I hope someone can help me out.

    <input type="text" ng-model="formula.join('')" ></input>

    <button  ng-click='add(7)'>7</button>
    <button  ng-click='add(8)'>8</button>
    <button  ng-click='add(9)'>9</button>
    <button  ng-click='add("/")'>/</button>

    <button  ng-click='add(4)'>4</button>
    <button ng-click='add(5)'>5</button>
    <button  ng-click='add(6)'>6</button>
    <button  ng-click='add("*")'>*</button>

    <button  ng-click='add(1)'>1</button>
    <button  ng-click='add(2)'>2</button>
    <button  ng-click='add(3)'>3</button>
    <button  ng-click='add("-")'>-</button>

    <button  ng-click='add(0)'>0</button>
    <button  ng-click='add(".")'>.</button>
    <button  ng-click='add("+")'>+</button>
    <button ng-click="eval()">=</button>

    <button  ng-click="remove()">CLEAR</button>

app.controller('calcCtrl',  function($scope) {
    $scope.formula = ['0'];
    $scope.add = function(item) {
    if ($scope.formula == '0') $scope.formula = [item];
    else $scope.formula.push(item);
};
    $scope.remove = function() {
    $scope.formula.pop();
    if($scope.formula.length == 0) $scope.formula = ['0'];
};
    $scope.eval = function() {
    var result = eval($scope.formula.join(''));
    $scope.formula = [result];
};

    });

Body:
You get that error because you didn't put a variable assignable in ng-model.
So change ng-model="formula.join('')" to use a variable: eg: ng-model="total"

and in your controller, for each calculation, just assign this variable to formula.join('')

$scope.add = function(item) {
    if ($scope.formula == '0') $scope.formula = [item];
    else $scope.formula.push(item);
    $scope.total = $scope.formula.join('');
  };
  $scope.remove = function() {
    $scope.formula.pop();
    if ($scope.formula.length == 0) $scope.formula = ['0'];
    $scope.total = $scope.formula.join('');
  };
  $scope.eval = function() {
    var result = eval($scope.formula.join(''));
    $scope.formula = [result];
    $scope.total = $scope.formula.join('');
  };


问:
get object from controller in view MVC
I need to create the body of a email in html format. Inside a HistoryController I define a metod that return an object (Course) which attributes will be used for crate the body as i said. I dont know how to get the object in the View. I've seen a metod using ActionResult but i dont to present the View it just work like an auxiliary for creating the email.

I get this.

HistoryController

```<code>public static CURSO courseSelected = new CURSO();
public static CURSO courseSel()
{
    courseSelected.Name = "Physics";
    return courseSelected;//cursoSelected del tipo CURSO
}
</code>```

View

```<code>@model Project.Models.Course
@{
    var courseSel = Project.Models.HistoryController.courseSel();
}
<fieldset class="fHorizontalCenter">
        <label style="font-size:18px">Welcome to course of </label><label>@courseSel.Name</label>< br />
</fieldset>
</code>```

But i cant use de data of the variable, It always prints this

Welcome to course of @courseSel.Name

答:
Let's say you have a model that looks like this:

```<code>namespace Project.Models
{
    public class Course
    {
        public string CourseName { get; set; }
    }
}
</code>```

and a view named "CourseEmailTemplate.cshtml" in your Views/Shared Folder:

```<code>@model Project.Models.Course
@{
    Layout = null;
}

<fieldset class="fHorizontalCenter">
    <label style="font-size:18px">Welcome to course of </label><label>@Model.CourseName</label>< br />
</fieldset>
</code>```

then the controller could look something like this:

```<code>public class HistoryController : Controller
 {
    public ActionResult Index(/*put whatever parameters in here*/)
    {
       // Fetch your model
       // just example data
       var course = new Course { CourseName = "your coursename" };

       var html = GetEmailText(course);

        // send your email

        return View(); // or redirect to action
    }

    private string GetEmailText(Course course)
    {
        return RenderRazorViewToString("CourseEmailTemplate", course);
    }

    private string RenderRazorViewToString(string viewName, object model)
    {
        ViewData.Model = model;
        using (var sw = new StringWriter())
        {
            var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,
                                                                     viewName);
            var viewContext = new ViewContext(ControllerContext, viewResult.View,
                                         ViewData, TempData, sw);
            viewResult.View.Render(viewContext, sw);
            viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
            return sw.GetStringBuilder().ToString();
        }
    }
}
</code>```

some code stolen from Render a view as a string

Title: get object from controller in view MVC

Body:
I need to create the body of a email in html format. Inside a HistoryController I define a metod that return an object (Course) which attributes will be used for crate the body as i said. I dont know how to get the object in the View. I've seen a metod using ActionResult but i dont to present the View it just work like an auxiliary for creating the email.

I get this.

HistoryController

public static CURSO courseSelected = new CURSO();
public static CURSO courseSel()
{
    courseSelected.Name = "Physics";
    return courseSelected;//cursoSelected del tipo CURSO
}

View

@model Project.Models.Course
@{
    var courseSel = Project.Models.HistoryController.courseSel();
}
<fieldset class="fHorizontalCenter">
        Welcome to course of @courseSel.Name

</fieldset>

But i cant use de data of the variable, It always prints this

Welcome to course of @courseSel.Name

Body:
Let's say you have a model that looks like this:

namespace Project.Models
{
    public class Course
    {
        public string CourseName { get; set; }
    }
}

and a view named "CourseEmailTemplate.cshtml" in your Views/Shared Folder:

@model Project.Models.Course
@{
    Layout = null;
}

<fieldset class="fHorizontalCenter">
    <label style="font-size:18px">Welcome to course of </label><label>@Model.CourseName</label>< br />
</fieldset>

then the controller could look something like this:

public class HistoryController : Controller
 {
    public ActionResult Index(/*put whatever parameters in here*/)
    {
       // Fetch your model
       // just example data
       var course = new Course { CourseName = "your coursename" };

       var html = GetEmailText(course);

        // send your email

        return View(); // or redirect to action
    }

    private string GetEmailText(Course course)
    {
        return RenderRazorViewToString("CourseEmailTemplate", course);
    }

    private string RenderRazorViewToString(string viewName, object model)
    {
        ViewData.Model = model;
        using (var sw = new StringWriter())
        {
            var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,
                                                                     viewName);
            var viewContext = new ViewContext(ControllerContext, viewResult.View,
                                         ViewData, TempData, sw);
            viewResult.View.Render(viewContext, sw);
            viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
            return sw.GetStringBuilder().ToString();
        }
    }
}

some code stolen from Render a view as a string


问:
TrivialDrive vs TrivialDrive V2?
Why are there two versions of TrivialDrive?

https://github.com/googlesamples/android-play-billing

Which version should be the main reference project for learning in-app billing? What's the difference between the versions?

答:
A little searching shows that Trival Drive V2 sample has a shared build.gradle file:

https://github.com/googlesamples/android-play-billing/blob/master/TrivialDrive_v2/shared-module/build.gradle

which has the following line:

```<code>compile 'com.android.billingclient:billing:dp-1'
</code>```

Looking at the documentation here:

https://developer.android.com/google/play/billing/billing_library.html

Shows that Google just released a new version of the Billing Library release dp-1:

Starting with Play Billing Library release dp-1 (June 2017), the minimum
  supported API level is Android 2.2 (API level 8). The minimum supported
  In-app Billing API is version 3.

And specifically calls out changes to the minimum support Android API and In-app Billing API.

Given the Trivial Drive V2 sample app(s) has a Wear 2.0 example - this version has billing support on Wear 2.0 apps.

Title: TrivialDrive vs TrivialDrive V2?

Body:
A little searching shows that Trival Drive V2 sample has a shared build.gradle file:

https://github.com/googlesamples/android-play-billing/blob/master/TrivialDrive_v2/shared-module/build.gradle

which has the following line:

compile 'com.android.billingclient:billing:dp-1'

Looking at the documentation here:

https://developer.android.com/google/play/billing/billing_library.html

Shows that Google just released a new version of the Billing Library release dp-1:

Starting with Play Billing Library release dp-1 (June 2017), the minimum
  supported API level is Android 2.2 (API level 8). The minimum supported
  In-app Billing API is version 3.

And specifically calls out changes to the minimum support Android API and In-app Billing API.

Given the Trivial Drive V2 sample app(s) has a Wear 2.0 example - this version has billing support on Wear 2.0 apps.


问:
How can I hide the modal programatically in vue js
I am trying to create a component in vue js 2. It is a modal component. The function of this is to just alert a user for successful query on the database or errors. So when the user submitted a form successful or not this modal component will be shown. I did successfully shown it but the problem is I want to automatically hide it in few seconds after it is shown. How can I achieve this in vue JS.</p>

答:
Use setTimeout javascript function.</p>

```<code>showModal(){
   var self = this;
   self.modalActive = true;
   setTimeout(function(){
      self.modalActive = false; // Use your variable name
   }, 5 * 1000); // Hide after 5 secs
}
</code>```

Body:
Use setTimeout javascript function.

showModal(){
   var self = this;
   self.modalActive = true;
   setTimeout(function(){
      self.modalActive = false; // Use your variable name
   }, 5 * 1000); // Hide after 5 secs
}


问:
Operation is not valid due to the current state of the object (System.Iinq)
So i'm making a basic 2D platformer in Unity, I want to be able to save the time it takes the player to complete each level and display the fastest time in a UI element. I'm writing the times to a text file (this works fine), and reading all the times line by line into a list, from there I find the lowest value etc.  However, my code does not work, it gives me the following error when I'm calling the function from another script. I'm new to C# so would greatly appreciate any help anyone can give me!

Thanks!

Full Error Message

InvalidOperationException: Operation is not valid due to the current state of the object
System.Linq.Enumerable.Iterate[Single,Single] (IEnumerable1 source, Single initValue, System.Func3 selector)
System.Linq.Enumerable.Min (IEnumerable`1 source)
SaveScores.ReadData (System.String LevelLoaded) (at Assets/Scripts/Highscores/SaveScores.cs:73)
GameManager.Update () (at Assets/Scripts/GameManager.cs:45)

Code

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System;
using System.Linq;

public class SaveScores : MonoBehaviour {

void Start()
{
    //ReadData();
}

public static void WriteData(float time, string LevelLoaded)
{
    try
    {
        //Debug.Log("Saving time");
        StreamWriter sw = new StreamWriter(@"C:\Users\Theo\Documents\Unity Projects\V13\Platformer\Assets\Scripts\Highscores\Scores.txt", true);
        sw.WriteLine(LevelLoaded + " " + time);

        sw.Close();
    }
    catch(Exception e)
    {
        Console.WriteLine("Exception: " + e.Message);
    }
    finally
    {
        Console.WriteLine("Executing final block");
    }
}

public static void ReadData(string LevelLoaded)
{
    List <float> timesLevel1 = new List<float>();
    List <float> timesLevel2 = new List<float>();
    List <float> timesLevel3 = new List<float>();

    try
    {
        var lines = File.ReadAllLines(@"C:\Users\Theo\Documents\Unity Projects\V13\Platformer\Assets\Scripts\Highscores\Scores.txt");

        foreach (var line in lines)
        {
            if (line.Contains("Level1"))
            {
                timesLevel1.Add(Convert.ToSingle(line));
            }
            else if (line.Contains("Level2"))
            {
                timesLevel2.Add(Convert.ToSingle(line));
            }
            else if (line.Contains("Level3"))
            {
                timesLevel3.Add(Convert.ToSingle(line));
            }
        }
    }
    catch (Exception e)
    {
        Console.WriteLine("Exception: " + e.Message);
    }
    finally
    {
        Console.WriteLine("Executing final block");
    }

    switch (LevelLoaded)
    {
        case "Level1":
            UIManager.lowestTime = timesLevel1.Min();
            break;
        case "Level2":
            UIManager.lowestTime = timesLevel2.Min();
            break;
        case "Level3":
           UIManager.lowestTime = timesLevel3.Min();
            break;
    }

}
</code>```

}

答:
If you look at the documentation for Enumerable.Min<float> (https://msdn.microsoft.com/en-us/library/bb361144(v=vs.110).aspx) you will see that under "Exceptions" it lists the InvalidOperationException and gives the reason as: "source contains no elements".

What this likely means is that the list you are looking at doesn't contain any elements.

On looking at what is populating that list there seems to be some confusion in what you expect to be in the line. You do a test for line.Contains("Level1") but if that succeeds then you call Convert.ToSingle(line) which would fail if there was any string data in that line (eg if line did contain that string then the convert would fail).

So it seems likely that the format of the file you are reading is not what you expect it to be leading to your lists being empty leading to this error.

Body:
So i'm making a basic 2D platformer in Unity, I want to be able to save the time it takes the player to complete each level and display the fastest time in a UI element. I'm writing the times to a text file (this works fine), and reading all the times line by line into a list, from there I find the lowest value etc.  However, my code does not work, it gives me the following error when I'm calling the function from another script. I'm new to C# so would greatly appreciate any help anyone can give me!

Thanks!

Full Error Message

InvalidOperationException: Operation is not valid due to the current state of the object
System.Linq.Enumerable.Iterate[Single,Single] (IEnumerable1 source, Single initValue, System.Func3 selector)
System.Linq.Enumerable.Min (IEnumerable`1 source)
SaveScores.ReadData (System.String LevelLoaded) (at Assets/Scripts/Highscores/SaveScores.cs:73)
GameManager.Update () (at Assets/Scripts/GameManager.cs:45)

Code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System;
using System.Linq;

public class SaveScores : MonoBehaviour {

void Start()
{
    //ReadData();
}

public static void WriteData(float time, string LevelLoaded)
{
    try
    {
        //Debug.Log("Saving time");
        StreamWriter sw = new StreamWriter(@"C:\Users\Theo\Documents\Unity Projects\V13\Platformer\Assets\Scripts\Highscores\Scores.txt", true);
        sw.WriteLine(LevelLoaded + " " + time);

        sw.Close();
    }
    catch(Exception e)
    {
        Console.WriteLine("Exception: " + e.Message);
    }
    finally
    {
        Console.WriteLine("Executing final block");
    }
}

public static void ReadData(string LevelLoaded)
{
    List <float> timesLevel1 = new List<float>();
    List <float> timesLevel2 = new List<float>();
    List <float> timesLevel3 = new List<float>();

    try
    {
        var lines = File.ReadAllLines(@"C:\Users\Theo\Documents\Unity Projects\V13\Platformer\Assets\Scripts\Highscores\Scores.txt");

        foreach (var line in lines)
        {
            if (line.Contains("Level1"))
            {
                timesLevel1.Add(Convert.ToSingle(line));
            }
            else if (line.Contains("Level2"))
            {
                timesLevel2.Add(Convert.ToSingle(line));
            }
            else if (line.Contains("Level3"))
            {
                timesLevel3.Add(Convert.ToSingle(line));
            }
        }
    }
    catch (Exception e)
    {
        Console.WriteLine("Exception: " + e.Message);
    }
    finally
    {
        Console.WriteLine("Executing final block");
    }

    switch (LevelLoaded)
    {
        case "Level1":
            UIManager.lowestTime = timesLevel1.Min();
            break;
        case "Level2":
            UIManager.lowestTime = timesLevel2.Min();
            break;
        case "Level3":
           UIManager.lowestTime = timesLevel3.Min();
            break;
    }

}

}


问:
c++ , error: 'shared_ptr' in namespace 'std' does not name a template type
I tried to define a smart pointer to my structure with rhapsody and I have already  included the header file "memory". But I ve got the error above</p>

```<code> typedef std::shared_ptr<my_structure> %s;
</code>```

答:
I think you mean std::shared_ptr and not std::shared.

Also % is not legal in a type name in C++.

If your intent is to create a type alias, then you should do something like this

```<code>using MyType_t = std::shared_ptr<my_structure>;
</code>```

If your intent is to create a variable of type std::shared_ptr<my_structure>, then you should do this

```<code>std::shared_ptr<my_structure> ptr;
</code>```

Body:
I tried to define a smart pointer to my structure with rhapsody and I have already  included the header file "memory". But I ve got the error above

 typedef std::shared_ptr<my_structure> %s;

Body:
I think you mean std::shared_ptr and not std::shared.

Also % is not legal in a type name in C++.

If your intent is to create a type alias, then you should do something like this

using MyType_t = std::shared_ptr<my_structure>;

If your intent is to create a variable of type std::shared_ptr<my_structure>, then you should do this

std::shared_ptr<my_structure> ptr;


问:
How to delete a row from AP_PAYMENT_SCHEDULES_ALL Oracle R12 table?
Please I need to know how to delete a row from AP_PAYMENT_SCHEDULES_ALL table in oracle R12?

Thanks in advance

答:
According to the documentation the primary key on AP_INVOICE_PAYMENTS_ALL is INVOICE_PAYMENT_ID. Therefore, given a valid value for INVOICE_PAYMENT_ID you'd do something like

```<code>DELETE FROM AP_INVOICE_PAYMENTS_ALL
  WHERE INVOICE_PAYMENT_ID = #####
</code>```

where ##### is the invoice payment ID.

Best of luck.

Body:
According to the documentation the primary key on AP_INVOICE_PAYMENTS_ALL is INVOICE_PAYMENT_ID. Therefore, given a valid value for INVOICE_PAYMENT_ID you'd do something like

DELETE FROM AP_INVOICE_PAYMENTS_ALL
  WHERE INVOICE_PAYMENT_ID = #####

where ##### is the invoice payment ID.

Best of luck.


问:
How can I do automatic link and htmlspecialchars conversion at the same time?
I want to create code that meets both of the following two things at the same time.

If text contains any url, the part is automatically converted to a  link.

Apply the func1() to html entity characters on the text, except some  parts generated by the above function. (this is to prevent attack by malicious script.)

So I wrote the following code:

```<code><?php
    function func1($text) //function like htmlspecialchars
    {
        $text = str_replace("&", "&", $text);
        $text = str_replace("\"", """, $text);
        $text = str_replace("'", "'", $text);
        $text = str_replace("<", "<", $text);
        $text = str_replace(">", ">", $text);
        $text = str_replace(" ", " ", $text);
        return $text;
    }
    function func2($text)
    {
        $text = func1($text);
        $url_pattern = "(http|https):\/\/([a-zA-Z0-9.\/?&=%_+-@~:#$]+)";
        $text = preg_replace("/(".$url_pattern.")/i", "<a href='\\1' target='_blank' class='temp_class'>\\1</a>", $text);
        return $text;
    }
    $test_string ="hello universe! https://www.youtube.com/watch?v=test     <iframe src='https://youtube.com/watch?v=good'></iframe> hello world.";
    echo func2($test_string);
?>
</code>```

However, when I run the above code,  is applied 'too widely'. In other words, 'https: //www.~' (...) '~ hello world' is treated as 'a single link'.

What I wanted was three things:

 applies to href="https://www.youtube.com/watch?v=test" rel="nofollow noreferrer">https://www.youtube.com/watch?v=test

href ~ class='temp_class'> applies to href="https://youtube.com/watch?v=good" rel="nofollow noreferrer">https://youtube.com/watch?v=good

<, >, ', etc. in this text are appropriately converted by func1(). So  tag does not work.

1 and 2 are not operating normally.

I can guess why this is happening. Perhaps, func1() transforms <, >, etc. into <, >, etc., so regexp in func2() interprets them as part of url.

I can guess why, but I do not know what to do now.

I'm considering adding some words to $url_pattern in func2() to exclude characters like %nbsp; or < from being interpreted. However, how to express this with regexp is also a big hurdle to me.

I have spent a long time on this problem but it is very difficult. Please help me.

Please leave a comment if there is anything you cannot understand.

答:
The problem is that your func1() converts all spaces in  , and so when there regular expression looks at the result, it sees to breaks - for example after "hello" the next character is & which is allowed in your regular expression.

You should run the URL capture regular expression before you do HTML escaping, and then do HTML escaping later.

BTW - do use htmlspecialchars() instead of your own custom function - as @tadman noted. One main advantage of that is that htmlspecialchars() does not convert spaces and so will not experience the problem you described, and also - converting spaces to non-breaking spaces is not a good idea in general.

Body:
I want to create code that meets both of the following two things at the same time.

If text contains any url, the part is automatically converted to a  link.

Apply the func1() to html entity characters on the text, except some  parts generated by the above function. (this is to prevent attack by malicious script.)

So I wrote the following code:

<?php
    function func1($text) //function like htmlspecialchars
    {
        $text = str_replace("&", "&", $text);
        $text = str_replace("\"", """, $text);
        $text = str_replace("'", "'", $text);
        $text = str_replace("<", "<", $text);
        $text = str_replace(">", ">", $text);
        $text = str_replace(" ", " ", $text);
        return $text;
    }
    function func2($text)
    {
        $text = func1($text);
        $url_pattern = "(http|https):\/\/([a-zA-Z0-9.\/?&=%_+-@~:#$]+)";
        $text = preg_replace("/(".$url_pattern.")/i", "\\1", $text);
        return $text;
    }
    $test_string ="hello universe! https://www.youtube.com/watch?v=test      hello world.";
    echo func2($test_string);
?>

However, when I run the above code,  is applied 'too widely'. In other words, 'https: //www.~' (...) '~ hello world' is treated as 'a single link'.

What I wanted was three things:

 applies to https://www.youtube.com/watch?v=test

 applies to https://youtube.com/watch?v=good

<, >, ', etc. in this text are appropriately converted by func1(). So  tag does not work.

1 and 2 are not operating normally.

I can guess why this is happening. Perhaps, func1() transforms <, >, etc. into <, >, etc., so regexp in func2() interprets them as part of url.

I can guess why, but I do not know what to do now.

I'm considering adding some words to $url_pattern in func2() to exclude characters like %nbsp; or < from being interpreted. However, how to express this with regexp is also a big hurdle to me.

I have spent a long time on this problem but it is very difficult. Please help me.

Please leave a comment if there is anything you cannot understand.

Body:
The problem is that your func1() converts all spaces in &nbsp;, and so when there regular expression looks at the result, it sees to breaks - for example after "hello" the next character is & which is allowed in your regular expression.

You should run the URL capture regular expression before you do HTML escaping, and then do HTML escaping later.

BTW - do use htmlspecialchars() instead of your own custom function - as @tadman noted. One main advantage of that is that htmlspecialchars() does not convert spaces and so will not experience the problem you described, and also - converting spaces to non-breaking spaces is not a good idea in general.


问:
Reactjs, How to compare props.location.pathname to a string?
In my router, I need to do the following:

```<code>if (props.location.pathname !== '/confirm') {
    // redirect to /confirm to force the user to confirm their email
}
</code>```

The if statement is not acting as expected.

If I output:

```<code>console.log(props.location.pathname)
</code>```

I get in the console.

```<code>/confirm
</code>```

However, props.location.pathname with the value of '/confirm' is not being seen as the same as /confirm

What am I doing wrong?

答:
type of both the operands should be same while using == for comparision.Make sure both are of string type or change if to

```<code>if (props.location.pathname != '/confirm') {
// redirect to /confirm to force the user to confirm their email
</code>```

}

Body:
In my router, I need to do the following:

if (props.location.pathname !== '/confirm') {
    // redirect to /confirm to force the user to confirm their email
}

The if statement is not acting as expected.

If I output:

console.log(props.location.pathname)

I get in the console.

/confirm

However, props.location.pathname with the value of '/confirm' is not being seen as the same as /confirm

What am I doing wrong?

Body:
type of both the operands should be same while using == for comparision.Make sure both are of string type or change if to

if (props.location.pathname != '/confirm') {
// redirect to /confirm to force the user to confirm their email

}


问:
Pull notification methods
I want to design a notification component. I want to understand what type of pulling notification methods are used out there to effectively pull the notification with minimal stress on the server.

Let's say for example I want to notify user of a chat message, I imagine I would need to pull the data quite regularly, like every 500ms for a quick response. However, doing this may overload the system. Hypothetically speaking if I have a million user browsing the site that's 2 million requests every second!

I'm thinking of writing an algorithm that will incrementally increase the pull interval by 1 second on each pull up to a maximum of 60 second. The interval will reset to 500ms if there is new data. In this way, if the user has frequent notification it will be instant. But if there hasn't been notification for a longer period of time, there maybe a bit of delay of up to a minute.

In essence I'm compromising between user experience and server load to find a middle ground for both.

Please advise on possible drawback of this approach if any. Is there a proper name for it?

Alternatively, is there a better method out there?

答: The method you are using could lead a network traffic overload on your server if there are many clients connected . Let's suppose you have 1000 clients connected : the server will have to handle 1000 different connections. A better approach is using a push notification system. Check this out https://nodejs.org/it/docs/</p>

Title: Pull notification methods


问:
How to execute maven plugins from gradle without having maven and java installed
I need to execute a maven plugin on a system that does not have both maven and java installed and installing both of them on the system is not an option. While searching for the ways, I found out that by using gradle we can build executable binaries that does not even require gradle to get executed, which perfectly fits my situation :) . Is there any way to execute maven plugins by using gradle. Thanks in advance

答: Both Maven and Gradle require java to be installed. See https://docs.gradle.org/current/userguide/installation.html</p>


问:
Callback not working after deleting comment. REACT
I am getting the comment to delete just fine, but for some reason the callback is not being invoked. I think it could be do to how I pass multiple arguments to the function maybe, but I am not sure.

I will post the code below to help out in this problem.

Show Page:

```<code>renderCommentsButtons(comment) {
    const { post, user, auth } = this.props;

    if(!user) {
      return (<div></div>);
    }

    if(auth) {
      if(user._id === comment.author.id) {
        return (
          <div>
            <button
              onClick={() => this.deleteComment(comment)}
              className="btn btn-xs btn-danger">
              Delete
            </button>
            <Link
              to={`/posts/${post._id}/comments/${comment._id}/edit`}
              className="btn btn-xs btn-warning">
              Edit
            </Link>
          </div>
        )
      }
    }
  }

  renderComments() {
    const { post } = this.props;
    return post.comments.map((comment) => {
      return (
        <li className="list-group-item" key={comment._id}>
          <div>
            {comment.text} : {comment.author.email}
          </div>
          {this.renderCommentsButtons(comment)}
        </li>
      );
    });
  }

  deleteComment(comment) {
    const {id} = this.props.match.params;
    const {user, post, auth} = this.props;

    if(!user) {
      return (<div></div>);
    }

    if(auth) {
      if(user._id === comment.author.id){
        console.log('comment_id:', comment._id, 'post_id:', post._id);
        this.props.deleteComments(post._id, comment._id, () => {
          this.props.history.push(`/posts/${post._id}`);
        });
      }
    }
  }
</code>```

Action:

```<code>export function deleteComments(post_id, comment_id, cb) {
  return function(dispatch) {
    console.log('comment_id:', comment_id, 'post_id:', post_id);
    axios.delete(`${ROOT_URL}/${post_id}/comments/${comment_id}`)
      .then(() => {
        dispatch({
          type: DELETE_COMMENTS,
          payload: comment_id
        });
      })
      .then(() => cb())
      .catch((error) => {
        console.log(error);
      });
  }
}
</code>```

Backend:

```<code>exports.deleteComment = function(req, res, next) {
  const query = {_id: req.params.comment_id};

  Comments.remove(query, function(err, comments) {
    if(err) {
      return next(err);
    } else {
      res.json(comments);
    }
  });
}
</code>```

答:
.then(() => { dispatch(/* action */) } ) doesn't return any promise, that's why .then(() => cb()) is not executing.

You can try to call callback just after dispatching action.

```<code>axios.delete(`${ROOT_URL}/${post_id}/comments/${comment_id}`)
  .then(() => {
    dispatch({ /* action */})
    cb();
  })
  .catch((error) => {
    console.log(error);
  });
</code>```

Body:
I am getting the comment to delete just fine, but for some reason the callback is not being invoked. I think it could be do to how I pass multiple arguments to the function maybe, but I am not sure.

I will post the code below to help out in this problem.

Show Page:

renderCommentsButtons(comment) {
    const { post, user, auth } = this.props;

    if(!user) {
      return (

);
    }

    if(auth) {
      if(user._id === comment.author.id) {
        return (

            <button
              onClick={() => this.deleteComment(comment)}
              className="btn btn-xs btn-danger">
              Delete
            </button>
            <Link
              to={`/posts/${post._id}/comments/${comment._id}/edit`}
              className="btn btn-xs btn-warning">
              Edit
            </Link>

        )
      }
    }
  }

  renderComments() {
    const { post } = this.props;
    return post.comments.map((comment) => {
      return (

            {comment.text} : {comment.author.email}

          {this.renderCommentsButtons(comment)}

      );
    });
  }

  deleteComment(comment) {
    const {id} = this.props.match.params;
    const {user, post, auth} = this.props;

    if(!user) {
      return (

);
    }

    if(auth) {
      if(user._id === comment.author.id){
        console.log('comment_id:', comment._id, 'post_id:', post._id);
        this.props.deleteComments(post._id, comment._id, () => {
          this.props.history.push(`/posts/${post._id}`);
        });
      }
    }
  }

Action:

export function deleteComments(post_id, comment_id, cb) {
  return function(dispatch) {
    console.log('comment_id:', comment_id, 'post_id:', post_id);
    axios.delete(`${ROOT_URL}/${post_id}/comments/${comment_id}`)
      .then(() => {
        dispatch({
          type: DELETE_COMMENTS,
          payload: comment_id
        });
      })
      .then(() => cb())
      .catch((error) => {
        console.log(error);
      });
  }
}

Backend:

exports.deleteComment = function(req, res, next) {
  const query = {_id: req.params.comment_id};

  Comments.remove(query, function(err, comments) {
    if(err) {
      return next(err);
    } else {
      res.json(comments);
    }
  });
}

Body:
.then(() => { dispatch(/* action */) } ) doesn't return any promise, that's why .then(() => cb()) is not executing.

You can try to call callback just after dispatching action.

axios.delete(`${ROOT_URL}/${post_id}/comments/${comment_id}`)
  .then(() => {
    dispatch({ /* action */})
    cb();
  })
  .catch((error) => {
    console.log(error);
  });


问:
Unable to get dropdown selected value from aspx page to backend
Hello Guys i am using a web service and ajax call to bind my cascading drop down lists but i am not able to get the selected value of first drop down  in code behind..

this is my code

```<code> $(document).ready(function () {
              var groups = $('#ddlGrpName');
              var docs = $('#ddlDoctors');

              //var getval = $('#ddlGrpName').val();
              //var anothrva = $('#ddlDoctors').val();

              $.ajax({
                  url: 'Dataservice.asmx/GetGroups',
                  method: 'post',
                  dataType: 'json',
                  success: function (data) {

                      groups.append($('<option/>', { value: -1, text: 'select Group' }));
                      docs.append($('<option/>', { value: -1, text: 'select Doctor' }));
                      docs.prop('disabled', true);
                      $(data).each(function (index, item) {
                          groups.append($('<option/>', { value: item.id, text: item.name }));

                          $('#<%=hdnGroupid.ClientID%>').val(item.id);

                      });

                  }

              });

              groups.change(function () {
                  if ($(this).val() == "-1") {
                      docs.empty();
                      docs.append($('<option/>', { value: -1, text: 'select Doctor' }));
                      docs.val('-1');
                      docs.prop('disabled', true);
                  }

                  else {
                      $.ajax({
                          url: 'Dataservice.asmx/GetGroupsid',
                          method: 'post',
                          data: { groupID: $(this).val() },
                          dataType: 'json',
                          success: function (data) {
                              docs.empty();
                              docs.append($('<option/>', { value: -1, text: 'select Doctor' }));
                              docs.prop('disabled', false);
                              $(data).each(function (index, item) {
                                  docs.append($('<option/>', { value: item.id, text: item.pname }));

                                  $('#<%=hdnDoctorid.ClientID%>').val(item.id);
                              });

                          }

                      });
                  }

              });

          });``
</code>```

drop down values are binding but not able to get the selected value of drop down while saving in the database.
this are two cascading drop downs i am getting the value of second drop down when i take a hidden field , but when i check the same way with the first drop down i am only getting the same value , but drop down selected value changes whenever i change the drop down its not happening

please help??

答:
string fruit = Request.Form[this.ddlname.UniqueID];
            string juice = Request.Form[this.ddname.UniqueID];

This gives the right output..

we can get the drop down selected value using the Request.form collection
https://msdn.microsoft.com/en-us/library/ms525985(v=vs.90).aspx check out here..

hope it helps..

Body:
Hello Guys i am using a web service and ajax call to bind my cascading drop down lists but i am not able to get the selected value of first drop down  in code behind..

this is my code

 $(document).ready(function () {
              var groups = $('#ddlGrpName');
              var docs = $('#ddlDoctors');

              //var getval = $('#ddlGrpName').val();
              //var anothrva = $('#ddlDoctors').val();

              $.ajax({
                  url: 'Dataservice.asmx/GetGroups',
                  method: 'post',
                  dataType: 'json',
                  success: function (data) {

                      groups.append($('<option/>', { value: -1, text: 'select Group' }));
                      docs.append($('<option/>', { value: -1, text: 'select Doctor' }));
                      docs.prop('disabled', true);
                      $(data).each(function (index, item) {
                          groups.append($('<option/>', { value: item.id, text: item.name }));

                          $('#<%=hdnGroupid.ClientID%>').val(item.id);

                      });

                  }

              });

              groups.change(function () {
                  if ($(this).val() == "-1") {
                      docs.empty();
                      docs.append($('<option/>', { value: -1, text: 'select Doctor' }));
                      docs.val('-1');
                      docs.prop('disabled', true);
                  }

                  else {
                      $.ajax({
                          url: 'Dataservice.asmx/GetGroupsid',
                          method: 'post',
                          data: { groupID: $(this).val() },
                          dataType: 'json',
                          success: function (data) {
                              docs.empty();
                              docs.append($('<option/>', { value: -1, text: 'select Doctor' }));
                              docs.prop('disabled', false);
                              $(data).each(function (index, item) {
                                  docs.append($('<option/>', { value: item.id, text: item.pname }));

                                  $('#<%=hdnDoctorid.ClientID%>').val(item.id);
                              });

                          }

                      });
                  }

              });

          });``

drop down values are binding but not able to get the selected value of drop down while saving in the database.
this are two cascading drop downs i am getting the value of second drop down when i take a hidden field , but when i check the same way with the first drop down i am only getting the same value , but drop down selected value changes whenever i change the drop down its not happening

please help??


问:
Link in a flash message, ruby on rails
I have the following line in my application which shows flash message with a hyperlink.

```<code>flash[:danger] = %Q[Click following <a href="#" class="flash_link" id="flash_link" ><strong>link</strong></a> to proceed]
</code>```

Bu rails engine generates following html.

```<code><a href="#" class="flash_link"><strong>link</strong></a>
</code>```

Why didn't it generate id="flash_link" ?

Any suggestions,

Thanks.

答:
I think you problem is not from %Q, I curious with your question, I checked from rails console (as Pavan said it get the result), I also tested with HTML view that rendered by rails with html_safe, I also get the id rendered (probably you can start to trace how you show "flash message"

```<code><%= (%Q[Click following <a href="#" class="flash_link" id="flash_link" ><strong>link</strong></a> to proceed]).html_safe
</code>```

it rendered

```<code><a href="#" class="flash_link" id="flash_link"><strong>link</strong></a>
</code>```

I'm using rails 5.0.2

Title: Link in a flash message, ruby on rails

Body:
I have the following line in my application which shows flash message with a hyperlink.

flash[:danger] = %Q[Click following link to proceed]

Bu rails engine generates following html.

link

Why didn't it generate id="flash_link" ?

Any suggestions,

Thanks.

Body:
I think you problem is not from %Q, I curious with your question, I checked from rails console (as Pavan said it get the result), I also tested with HTML view that rendered by rails with html_safe, I also get the id rendered (probably you can start to trace how you show "flash message"

<%= (%Q[Click following <a href="#" class="flash_link" id="flash_link" ><strong>link</strong></a> to proceed]).html_safe

it rendered

<a href="#" class="flash_link" id="flash_link"><strong>link</strong></a>

I'm using rails 5.0.2


问:
Using javascript to alter span text dynamically and keeping the original text
I have a  html page, inside which i have following code snippet, depending on which case we're following:

```<code>CASE 1)    <p> <span id ="xyz">  some code here  </span> </p>
CASE 2)    <p> <span id ="xyz">   </span> some code here </p>
</code>```

Now in my javascript code I have to write values in span xyz dynamically. If I try to do get reference to span xyz by id and then try to alter its innerHTML, then the html already present in span xyz is lost.

If I keep extra code outside the span, it appears on new line due to some css effects. I cannot alter css due to some reasons.

答:
You can append a new text node to span, if you want to keep the old text.

```<code>var newtext = document.createTextNode(" new text ");
var spanXyz = document.getElementById("xyz");
spanXyz.appendChild(newtext);
</code>```

Refer these: createTextNode, appendChild

Edit: To add new text at the beginning, you can use something like

```<code>spanXyz.textContent = "new text " + spanXyz.textContent;
</code>```

Body:
I have a  html page, inside which i have following code snippet, depending on which case we're following:

CASE 1)
   some code here

CASE 2)
     some code here

Now in my javascript code I have to write values in span xyz dynamically. If I try to do get reference to span xyz by id and then try to alter its innerHTML, then the html already present in span xyz is lost.

If I keep extra code outside the span, it appears on new line due to some css effects. I cannot alter css due to some reasons.

Body:
You can append a new text node to span, if you want to keep the old text.

var newtext = document.createTextNode(" new text ");
var spanXyz = document.getElementById("xyz");
spanXyz.appendChild(newtext);

Refer these: createTextNode, appendChild

Edit: To add new text at the beginning, you can use something like

spanXyz.textContent = "new text " + spanXyz.textContent;


问:
APK upload failed for Alpha version. Errors from apksigner: Digest algorithm and Signature Algorithm Which is not supported on API levels [[16, 17]]
I had signed the APK by using keytool, jarsigner, and zipalign utlities.

I have used the following commands:

```<code>keytool -genkey -v -keystore myAppTransporterKey.keystore -alias myTransporter -keyalg RSA -keysize 2048 -validity 10000
</code>```

cordova plugin rm cordova-plugin-console

cordova build --release android

```<code>jarsigner -verbose -keystore C:\Users\ali\Documents\transporterApp\myAppKey.keystore C:\Users\ali\Documents\transporterApp\platforms\android\build\outputs\apk\android-release-unsigned.apk myTransporter

jarsigner -verify C:\Users\ali\Documents\transporterApp\platforms\android\build\outputs\apk\android-release-unsigned.apk
</code>```

After running:

```<code>jarsigner -verify -verbose -certs C:\Users\ali\Documents\transporterApp\platforms\android\build\outputs\apk\android-release-unsigned.apk
</code>```

getting this message: jar verified

After running:

```<code>zipalign -v 4 C:\Users\ali\Documents\transporterApp\platforms\android\build\outputs\apk\android-release-unsigned.apk C:\Users\ali\Documents\transporterApp\platforms\android\build\outputs\apk\myTransporter-Final.apk
</code>```

get the message: Verification succesful

After uploading to ALPAH in Google play console I am getting following error

Upload new APK to Alpha

Uploading

You have uploaded an APK with an invalid signature ( read more about
  signing ). Errors from apksigner: ERROR (Jar signer D2DTRANS.RSA): JAR
  signature META-INF / D2DTRANS.RSA uses digest algorithm
  2.16.840.1.101.3.4.2.1 and Signature Algorithm 1.2.840.113549.1.1.1 Which is not supported on API levels [[16, 17]]

答:
You need these steps:

```<code>zipalign -v 4 C:\Users\ali\Documents\transporterApp\platforms\android\build\outputs\apk\android-release-unsigned.apk C:\Users\ali\Documents\transporterApp\platforms\android\build\outputs\apk\android-release-unsigned-aligned.apk

apksigner sign --ks C:\Users\ali\Documents\transporterApp\myAppKey.keystore --ks-pass pass:[PASSWORD] --key-pass pass:[PASSWORD] --out C:\Users\ali\Documents\transporterApp\platforms\android\build\outputs\apk\android-release-singned.apk C:\Users\ali\Documents\transporterApp\platforms\android\build\outputs\apk\android-release-unsigned-aligned.apk
</code>```

To sign applications use the BuildTools 24.0.3

https://developer.android.com/studio/releases/build-tools.html

Body:
I had signed the APK by using keytool, jarsigner, and zipalign utlities.

I have used the following commands:

keytool -genkey -v -keystore myAppTransporterKey.keystore -alias myTransporter -keyalg RSA -keysize 2048 -validity 10000

cordova plugin rm cordova-plugin-console

cordova build --release android

jarsigner -verbose -keystore C:\Users\ali\Documents\transporterApp\myAppKey.keystore C:\Users\ali\Documents\transporterApp\platforms\android\build\outputs\apk\android-release-unsigned.apk myTransporter

jarsigner -verify C:\Users\ali\Documents\transporterApp\platforms\android\build\outputs\apk\android-release-unsigned.apk

After running:

jarsigner -verify -verbose -certs C:\Users\ali\Documents\transporterApp\platforms\android\build\outputs\apk\android-release-unsigned.apk

getting this message: jar verified

After running:

zipalign -v 4 C:\Users\ali\Documents\transporterApp\platforms\android\build\outputs\apk\android-release-unsigned.apk C:\Users\ali\Documents\transporterApp\platforms\android\build\outputs\apk\myTransporter-Final.apk

get the message: Verification succesful

After uploading to ALPAH in Google play console I am getting following error

Upload new APK to Alpha

Uploading

You have uploaded an APK with an invalid signature ( read more about
  signing ). Errors from apksigner: ERROR (Jar signer D2DTRANS.RSA): JAR
  signature META-INF / D2DTRANS.RSA uses digest algorithm
  2.16.840.1.101.3.4.2.1 and Signature Algorithm 1.2.840.113549.1.1.1 Which is not supported on API levels [[16, 17]]

Body:
You need these steps:

zipalign -v 4 C:\Users\ali\Documents\transporterApp\platforms\android\build\outputs\apk\android-release-unsigned.apk C:\Users\ali\Documents\transporterApp\platforms\android\build\outputs\apk\android-release-unsigned-aligned.apk

apksigner sign --ks C:\Users\ali\Documents\transporterApp\myAppKey.keystore --ks-pass pass:[PASSWORD] --key-pass pass:[PASSWORD] --out C:\Users\ali\Documents\transporterApp\platforms\android\build\outputs\apk\android-release-singned.apk C:\Users\ali\Documents\transporterApp\platforms\android\build\outputs\apk\android-release-unsigned-aligned.apk

To sign applications use the BuildTools 24.0.3

https://developer.android.com/studio/releases/build-tools.html


问:
Need help speeding up a dplyr aggregation
tl.dr. I have an aggregation problem that I haven't seen in documentation before.  I manage to get it done, but it is way too slow for the intended application.  The data I usually work with have around 500 lines (my gut feeling tells me this isn't much for dplyr) and according to system.time it runs for about 4 s.  My dilemma is I want to run it in an optimisation repeatedly and currently I am looking at hours of run time.

Do you see anything where I can shave off some time?

If need be I can also send some data I work with.

Algorithm
I have a data set:

```<code>sample_dataset <- data_frame( starts = c(1000, 1008, 1017, 2000, 2020, 3000),
                          ends   = c(1009, 1015, 1020, 2015, 2030, 3010),
                          v = list(rep(1,10), rep(2,8),rep(3,4),
                                   rep(4,16), rep(5,11), rep(6,11)) )
</code>```

so each line encodes a signal and a start and end index.  I want to aggregate all lines which have less than closeness (e.g. 10) distance into an single line. In case it matters starts is ordered.

The output should be:

```<code>structure(list(inds = 1:3, starts = c(1000, 2000, 3000), ends = c(1020,
2030, 3010), v = list(c(1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 2, 2, 2,
2, 2, 2, 0, 3, 3, 3, 3), c(4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 0, 0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5), c(6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6))), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -3L), .Names = c("inds", "starts", "ends",
"v"))
</code>```

So the first three lines in the original data set are aggregated, line 4 and 5 aggregated, 6 unchanged.  For overlaps the numbers should be added, for gaps zeros filled in.  The updated starts value is the first starts, the updated ends should be the last ends (suppose I should fix it to the max).  But by the way these are generated end should be also sorted.  The case that one block is completely surrounded by another block should not occur.

I achieved this by following code:

Code

```<code>library(dplyr)

join_lines <- function(dfi) {
  if (nrow(dfi)==1) return(select(dfi,starts,ends, v))
  else
    with(dfi,{
             start <- starts[[1]]
             end <- ends[[length(ends)]]
             vals <- numeric(end-start+1)
             add_val <- function(ddf)
               with(ddf,{
                      vals[(starts-start+1) : (ends-start+1)] <<-
                        vals[(starts-start+1) : (ends-start+1)] + v })
             dfi %>% rowwise() %>% do(tmp=add_val(.))
             data_frame(starts=start, ends=end, v=list(vals))})
}

simplify_semisparse <- function(aframe, closeness = 10){
  aframe %>%
    mutate( join_pre = lag(ends, default=0)+closeness >= (starts),
           inds = cumsum(!join_pre)
           ) %>%
  group_by(inds) %>% do(join_lines(.)) %>% ungroup()
}

res <- simplify_semisparse(sample_dataset)

dput(res) # see above
</code>```

Background

The data I am dealing with is from mass spectrometry.  It's very peculiar in that a vector has around 500,000 entries and less than 10% of these are not zeros, a typical spectrum has around 500 such dense blocks.   I do need to quickly interpolate values along such a spectrum - my idea was to use approx in the "dense" regions.

Comparison of suggestions

I had the chance of comparing your suggestions.

The results produced by @matt-jewett solution did not agree with my intended ones so I did exclude it.

@jeremycgs solution was closest to my original approach, but also did not produce exactly the same results.

most important is for my the runtime, I am comparing using production data. My original solution took 2.165 s. @tjeremy s suggestion took 0.532 s and @uwe-block 0.012 s.

So wow - I need to learn data.table.

答:
Although the OP has requested to speed up a dplyr code I would like to suggest a data.table solution for performance reasons. Furthermore, non of the other answers posted so far have fully addressed OP's requirements, namely,

to keep the structure of sample_data with starts, ends and a list of v values,

to aggregate all lines which have less than closeness (e.g. 10) distance into a single line.

The code below tries to comply with all requirements:

```<code>library(data.table)   # CRAN versio 1.10.4 used
# define threshold: closeness as defined by OP, max_gap used in code
closeness <- 10L
max_gap <- closeness - 1L
# coerce to data.table, and key, i.e., sort by starts and ends
DT <- data.table(sample_dataset, key = c("starts", "ends"))
# compute gaps between ends and starts of next row
# identify rows which belong together: inds is advanced if gap is greater threshhold
DT[, gap := starts - shift(ends, fill = -Inf)][, inds := cumsum(gap > max_gap)][]
# close gaps but only within groups
DT0 <- DT[between(gap, 2L, max_gap), .(starts = starts - (gap - 1L), ends = starts - 1L,
                                       v = Vectorize(rep.int)(0L, gap - 1L), gap, inds)]
# bind rowwise (union in SQL), setkey on result to maintain sort order,
# remove column gap as no longer needed
DT2 <- setkey(rbind(DT, DT0), starts, ends)[, gap := NULL][]
# aggregate groupwise, pick min/max, combine lists
result <- DT2[, .(starts = min(starts), ends = max(ends), v = list(Reduce(c, v))), by = inds]
# alternative code: pick first/last
result <- DT2[, .(starts = first(starts), ends = last(ends), v = list(Reduce(c, v))), by = inds]
result
</code>```

produces

```<code>   inds starts ends            v
1:    1   1000 1020 1,1,1,1,1,1,
2:    2   2000 2030 4,4,4,4,4,4,
3:    3   3000 3010 6,6,6,6,6,6,
</code>```

with

```<code>result$v
</code>```

```<code>[[1]]
 [1] 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 0 3 3 3 3

[[2]]
 [1] 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 0 0 0 0 5 5 5 5 5 5 5 5 5 5 5

[[3]]
 [1] 6 6 6 6 6 6 6 6 6 6 6
</code>```

It can be verified that the number of elements in the v vectors is the same, except for the additional zeros added for the intra-group gaps:

```<code># test that all v values are included
# original
sum(lengths(sample_dataset$v))
#[1] 60
# result with additional zeros removed
sum(sapply(result$v, function(x) sum(x > 0)))
#[1] 60
</code>```

I haven't provided a benchmark because the sample data set is too small.

Data

```<code>sample_dataset <- dplyr::data_frame( starts = c(1000, 1008, 1017, 2000, 2020, 3000),
                                     ends   = c(1009, 1015, 1020, 2015, 2030, 3010),
                                     v = list(rep(1,10), rep(2,8),rep(3,4),
                                              rep(4,16), rep(5,11), rep(6,11)) )
</code>```

Body:
tl.dr. I have an aggregation problem that I haven't seen in documentation before.  I manage to get it done, but it is way too slow for the intended application.  The data I usually work with have around 500 lines (my gut feeling tells me this isn't much for dplyr) and according to system.time it runs for about 4 s.  My dilemma is I want to run it in an optimisation repeatedly and currently I am looking at hours of run time.

Do you see anything where I can shave off some time?

If need be I can also send some data I work with.

Algorithm
I have a data set:

sample_dataset <- data_frame( starts = c(1000, 1008, 1017, 2000, 2020, 3000),
                          ends   = c(1009, 1015, 1020, 2015, 2030, 3010),
                          v = list(rep(1,10), rep(2,8),rep(3,4),
                                   rep(4,16), rep(5,11), rep(6,11)) )

so each line encodes a signal and a start and end index.  I want to aggregate all lines which have less than closeness (e.g. 10) distance into an single line. In case it matters starts is ordered.

The output should be:

structure(list(inds = 1:3, starts = c(1000, 2000, 3000), ends = c(1020,
2030, 3010), v = list(c(1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 2, 2, 2,
2, 2, 2, 0, 3, 3, 3, 3), c(4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 0, 0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5), c(6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6))), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -3L), .Names = c("inds", "starts", "ends",
"v"))

So the first three lines in the original data set are aggregated, line 4 and 5 aggregated, 6 unchanged.  For overlaps the numbers should be added, for gaps zeros filled in.  The updated starts value is the first starts, the updated ends should be the last ends (suppose I should fix it to the max).  But by the way these are generated end should be also sorted.  The case that one block is completely surrounded by another block should not occur.

I achieved this by following code:

Code

library(dplyr)

join_lines <- function(dfi) {
  if (nrow(dfi)==1) return(select(dfi,starts,ends, v))
  else
    with(dfi,{
             start <- starts[[1]]
             end <- ends[[length(ends)]]
             vals <- numeric(end-start+1)
             add_val <- function(ddf)
               with(ddf,{
                      vals[(starts-start+1) : (ends-start+1)] <<-
                        vals[(starts-start+1) : (ends-start+1)] + v })
             dfi %>% rowwise() %>% do(tmp=add_val(.))
             data_frame(starts=start, ends=end, v=list(vals))})
}

simplify_semisparse <- function(aframe, closeness = 10){
  aframe %>%
    mutate( join_pre = lag(ends, default=0)+closeness >= (starts),
           inds = cumsum(!join_pre)
           ) %>%
  group_by(inds) %>% do(join_lines(.)) %>% ungroup()
}

res <- simplify_semisparse(sample_dataset)

dput(res) # see above

Background

The data I am dealing with is from mass spectrometry.  It's very peculiar in that a vector has around 500,000 entries and less than 10% of these are not zeros, a typical spectrum has around 500 such dense blocks.   I do need to quickly interpolate values along such a spectrum - my idea was to use approx in the "dense" regions.

Comparison of suggestions

I had the chance of comparing your suggestions.

The results produced by @matt-jewett solution did not agree with my intended ones so I did exclude it.

@jeremycgs solution was closest to my original approach, but also did not produce exactly the same results.

most important is for my the runtime, I am comparing using production data. My original solution took 2.165 s. @tjeremy s suggestion took 0.532 s and @uwe-block 0.012 s.

So wow - I need to learn data.table.

Body:
Although the OP has requested to speed up a dplyr code I would like to suggest a data.table solution for performance reasons. Furthermore, non of the other answers posted so far have fully addressed OP's requirements, namely,

to keep the structure of sample_data with starts, ends and a list of v values,

to aggregate all lines which have less than closeness (e.g. 10) distance into a single line.

The code below tries to comply with all requirements:

library(data.table)   # CRAN versio 1.10.4 used
# define threshold: closeness as defined by OP, max_gap used in code
closeness <- 10L
max_gap <- closeness - 1L
# coerce to data.table, and key, i.e., sort by starts and ends
DT <- data.table(sample_dataset, key = c("starts", "ends"))
# compute gaps between ends and starts of next row
# identify rows which belong together: inds is advanced if gap is greater threshhold
DT[, gap := starts - shift(ends, fill = -Inf)][, inds := cumsum(gap > max_gap)][]
# close gaps but only within groups
DT0 <- DT[between(gap, 2L, max_gap), .(starts = starts - (gap - 1L), ends = starts - 1L,
                                       v = Vectorize(rep.int)(0L, gap - 1L), gap, inds)]
# bind rowwise (union in SQL), setkey on result to maintain sort order,
# remove column gap as no longer needed
DT2 <- setkey(rbind(DT, DT0), starts, ends)[, gap := NULL][]
# aggregate groupwise, pick min/max, combine lists
result <- DT2[, .(starts = min(starts), ends = max(ends), v = list(Reduce(c, v))), by = inds]
# alternative code: pick first/last
result <- DT2[, .(starts = first(starts), ends = last(ends), v = list(Reduce(c, v))), by = inds]
result

produces

   inds starts ends            v
1:    1   1000 1020 1,1,1,1,1,1,
2:    2   2000 2030 4,4,4,4,4,4,
3:    3   3000 3010 6,6,6,6,6,6,

with

result$v

[[1]]
 [1] 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 0 3 3 3 3

[[2]]
 [1] 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 0 0 0 0 5 5 5 5 5 5 5 5 5 5 5

[[3]]
 [1] 6 6 6 6 6 6 6 6 6 6 6

It can be verified that the number of elements in the v vectors is the same, except for the additional zeros added for the intra-group gaps:

# test that all v values are included
# original
sum(lengths(sample_dataset$v))
#[1] 60
# result with additional zeros removed
sum(sapply(result$v, function(x) sum(x > 0)))
#[1] 60

I haven't provided a benchmark because the sample data set is too small.

Data

sample_dataset <- dplyr::data_frame( starts = c(1000, 1008, 1017, 2000, 2020, 3000),
                                     ends   = c(1009, 1015, 1020, 2015, 2030, 3010),
                                     v = list(rep(1,10), rep(2,8),rep(3,4),
                                              rep(4,16), rep(5,11), rep(6,11)) )


问:
Best way to route method calling from List in Java
What's definitely the best way to call a different method of a class according to a different object type in a List?

common example:

```<code>public class Dog extends Animals{
  ...
  public void say(){
    System.out("i'm a dog");
}

public class Cat extends Animals{
  ...
  public void say(){
    System.out("i'm a cat");
}

public class OtherClass {
  public void route(){
    List<Animals> aList = new ArrayList<>();
    a.add(new Dog());
    a.add(new Cat());
    for(Animals a:aList)
     methodOverloaded(a); ---> that's the point <---
  }
  public methodOverloaded(Dog d){
    d.say();
  }

  public methodOverloaded(Cat c){
    c.say();
 }
}
</code>```

Of course, the metaphorical goal is print I'm a dog on the first iteration and I'm a cat on second running methodOverloaded().

I tried

Visitor Pattern

instanceOf()

but I'm looking for better solution.

edit : I stricrtly want to call the overloaded methods of example's OtherClass.

答:
You need to define the method in Animal and make it abstract

```<code>abstract class Animal {
    public abstract void say();
}
</code>```

this way, you can override this method in each child of Animal, and all you got to do is a.say()
each object will call their respective method.

Body:
What's definitely the best way to call a different method of a class according to a different object type in a List?

common example:

public class Dog extends Animals{
  ...
  public void say(){
    System.out("i'm a dog");
}

public class Cat extends Animals{
  ...
  public void say(){
    System.out("i'm a cat");
}

public class OtherClass {
  public void route(){
    List<Animals> aList = new ArrayList<>();
    a.add(new Dog());
    a.add(new Cat());
    for(Animals a:aList)
     methodOverloaded(a); ---> that's the point <---
  }
  public methodOverloaded(Dog d){
    d.say();
  }

  public methodOverloaded(Cat c){
    c.say();
 }
}

Of course, the metaphorical goal is print I'm a dog on the first iteration and I'm a cat on second running methodOverloaded().

I tried

Visitor Pattern

instanceOf()

but I'm looking for better solution.

edit : I stricrtly want to call the overloaded methods of example's OtherClass.

Body:
You need to define the method in Animal and make it abstract

abstract class Animal {
    public abstract void say();
}

this way, you can override this method in each child of Animal, and all you got to do is a.say()
each object will call their respective method.


问:
Comsol, java API, SwingGraphicsPanel never finished
I have problem with Comsol's Java API.

To plot the result of Comsol model, I have to create an instance of com.comsol.modelguiswing.SwingGraphicsPanel

Here is my code:

```<code>public void start() {
    frame = new JFrame("Beam GUI - based on COMSOL Multiphysics");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(1000, 730);
    JPanel mainPanel = new JPanel();
    frame.getContentPane().add(mainPanel);
    mainPanel.setLayout(new BorderLayout());
    SwingGraphicsPanel.getDefaultLocale();

    System.out.println("before");
    final SwingGraphicsPanel graphicsPanel
            = new SwingGraphicsPanel("window1", "Window1");
    System.out.println("after");

    mainPanel.add(graphicsPanel, BorderLayout.CENTER);
    frame.setVisible(true);
    model = BeamModel.run();
    model.sol("sol1").runAll();
    model.result("pg1").set("window", "window1");
    model.result("pg1").run();

}
</code>```

The problem is that when I call its constructor, it never finished its execution ("before" is printed but "after" never be printed and the program is still running). It seems a deadlock is happened. I am using Comsol 5.3 on Windows 10 64x with JDK 1.8.

Would you please let me know what is the problem?!

答:
SwingGraphicsPanel is an implementation of JPanel in Comsol software. It seems the problem is with Comsol 5.3. And there is no problem with its implementation in Comsol 4.4.
Of course, I did not find any reports in its forum.</p>

Body:
I have problem with Comsol's Java API.

To plot the result of Comsol model, I have to create an instance of com.comsol.modelguiswing.SwingGraphicsPanel

Here is my code:

public void start() {
    frame = new JFrame("Beam GUI - based on COMSOL Multiphysics");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(1000, 730);
    JPanel mainPanel = new JPanel();
    frame.getContentPane().add(mainPanel);
    mainPanel.setLayout(new BorderLayout());
    SwingGraphicsPanel.getDefaultLocale();

    System.out.println("before");
    final SwingGraphicsPanel graphicsPanel
            = new SwingGraphicsPanel("window1", "Window1");
    System.out.println("after");

    mainPanel.add(graphicsPanel, BorderLayout.CENTER);
    frame.setVisible(true);
    model = BeamModel.run();
    model.sol("sol1").runAll();
    model.result("pg1").set("window", "window1");
    model.result("pg1").run();

}

The problem is that when I call its constructor, it never finished its execution ("before" is printed but "after" never be printed and the program is still running). It seems a deadlock is happened. I am using Comsol 5.3 on Windows 10 64x with JDK 1.8.

Would you please let me know what is the problem?!


问:
Load/Deserialize faster Json data to C# object
In my code I use Newtonsoft.Json :

```<code>MyCSharpTargetClass foo = JsonConvert.DeserializeObject<MyCSharpTargetClass>(json_string);
</code>```

The content of the json_string is constant (loaded from a file that never changes).

The functionality is fine but the deserializing process is slow at execution.

My question: is there a way to pre-calculate the object, or to put it in a constant*, or whatever to speed up the execution ?

Note: Actually I didn't manage to put it a constant the result of JsonConvert.DeserializeObject<...>(), but I'm new to C#, so I should have missed something.

Thanks for your help

[EDIT] Solution : Force the Newtonsoft assembly to be loaded at the start of the application.

答:
There's actualy not a lot of thinks you can do to speed this up.

Using ignore attribute, so this fields will not be added. Use this for some properties or calcualatable properties/fields, which can be recalculated later.
Hope this link helps :

https://msdn.microsoft.com/en-us/library/system.runtime.serialization.ignoredatamemberattribute.aspx

Using threads to read/write your objects, if you can customize your data into many files and serialize/deserialize in threads.

Deserialization JSON algorithms requires to read whole file about 3 times.
For better perfomance you can use YAML. Simple as XML/JSON, but with much better perfomance, since it reads file only 1 time.

Using shorter DataMember names to fields
[DataMember(Name = "id")]
public int MyObjectForSomethink{get;set;}

Body:
In my code I use Newtonsoft.Json :

MyCSharpTargetClass foo = JsonConvert.DeserializeObject<MyCSharpTargetClass>(json_string);

The content of the json_string is constant (loaded from a file that never changes).

The functionality is fine but the deserializing process is slow at execution.

My question: is there a way to pre-calculate the object, or to put it in a constant*, or whatever to speed up the execution ?

Note: Actually I didn't manage to put it a constant the result of JsonConvert.DeserializeObject<...>(), but I'm new to C#, so I should have missed something.

Thanks for your help

[EDIT] Solution : Force the Newtonsoft assembly to be loaded at the start of the application.


答:
The best way is to define abstract method in Animal and override it in child classes. That's how the polymorphism works.

No need of overloadings.

```<code>public abstract class Animal {
    public abstract void say();
}

public class Dog extends Animal {

    @Override
    public void say() {
        System.out.println("Bark");
    }
}

public class Cat extends Animal {

    @Override
    public void say() {
        System.out.println("Meow");
    }
}
</code>```

Usage:

```<code>public class Main() {
    public static void main(String[] args) {
        List<Animals> aList = new ArrayList<>();
        a.add(new Dog());
        a.add(new Cat());
        for (Animals a : aList)
            a.say();
    }
}
</code>```

Output:

```<code>Bark
Meow
</code>```

____UPDATE_1

I would like to add some comments why the overloading these methods is not a good idea.

If you will add the following to your code - it will compile:

```<code>public methodOverloaded(Animal a) {
    a.say();
}
</code>```

But it will not work as you're expecting. It will call public methodOverloaded(Animal a) for all the elements of List.

Why does this happen?

For all iterations of the loop, the compile-time type of the parameter is Animal. The runtime type is different in each iteration, but this does not affect the choice of overloading. Because the compile-time type of the parameter is Animal, the only applicable overloading is the third one.

The behavior of this program is counterintuitive because selection among overloaded methods is static, while selection among overridden methods is dynamic.

The correct version of an overridden method is chosen at runtime, based on the runtime type of the object on which the method is invoked.

This can be fixed with:

```<code>public methodOverloaded(Animal a) {
    if (a instanceof Cat) ? "Meow" :
       (a instanceof Dog) ? "Bark" : "Unknown Animal"
}
</code>```

Of course suggested option with overriding methods demonstrates better approach and more clean code.

Also, a safe, conservative policy is never to export two overloadings with
the same number of parameters, because it can confuse the client of the API. You can always give methods different names instead of overloading them.

But there is the case when at least one corresponding formal parameter in each pair of overloadings has a “radically different” (when it's clearly impossible to cast an instance of either type to the other) type in the two overloadings.

For example, ArrayList has one constructor that takes an int and a second constructor that takes a Collection. It is hard to imagine any confusion over which of these two constructors will be invoked under any circumstances.

Title: Best way to route method calling from List in Java

Body:
The best way is to define abstract method in Animal and override it in child classes. That's how the polymorphism works.

No need of overloadings.

public abstract class Animal {
    public abstract void say();
}

public class Dog extends Animal {

    @Override
    public void say() {
        System.out.println("Bark");
    }
}

public class Cat extends Animal {

    @Override
    public void say() {
        System.out.println("Meow");
    }
}

Usage:

public class Main() {
    public static void main(String[] args) {
        List<Animals> aList = new ArrayList<>();
        a.add(new Dog());
        a.add(new Cat());
        for (Animals a : aList)
            a.say();
    }
}

Output:

Bark
Meow

____UPDATE_1

I would like to add some comments why the overloading these methods is not a good idea.

If you will add the following to your code - it will compile:

public methodOverloaded(Animal a) {
    a.say();
}

But it will not work as you're expecting. It will call public methodOverloaded(Animal a) for all the elements of List.

Why does this happen?

For all iterations of the loop, the compile-time type of the parameter is Animal. The runtime type is different in each iteration, but this does not affect the choice of overloading. Because the compile-time type of the parameter is Animal, the only applicable overloading is the third one.

The behavior of this program is counterintuitive because selection among overloaded methods is static, while selection among overridden methods is dynamic.

The correct version of an overridden method is chosen at runtime, based on the runtime type of the object on which the method is invoked.

This can be fixed with:

public methodOverloaded(Animal a) {
    if (a instanceof Cat) ? "Meow" :
       (a instanceof Dog) ? "Bark" : "Unknown Animal"
}

Of course suggested option with overriding methods demonstrates better approach and more clean code.

Also, a safe, conservative policy is never to export two overloadings with
the same number of parameters, because it can confuse the client of the API. You can always give methods different names instead of overloading them.

But there is the case when at least one corresponding formal parameter in each pair of overloadings has a “radically different” (when it's clearly impossible to cast an instance of either type to the other) type in the two overloadings.

For example, ArrayList has one constructor that takes an int and a second constructor that takes a Collection. It is hard to imagine any confusion over which of these two constructors will be invoked under any circumstances.


问:
Disk Space Check in Powershell
I am currently checking disk space size using power shell but was wondering how I can amend the below to add a percentage of space left?

```<code>Format-Table DeviceId, MediaType, @{n="Size";e={[math]::Round($_.Size/1MB,2)}},@{n="FreeSpace";e={[math]::Round($_.FreeSpace/1MB,2)}}
</code>```

I have tried to do it by changing the math but no luck.

```<code>gwmi win32_logicaldisk  -Computername PCNAME| Format-Table DeviceId, MediaType, @{n="Size";e={[math]::Round($_.Size/1MB,2)}},@{n="FreeSpace" (%);e={[math]::Round($_.FreeSpace/$_.Size*100,2)}}|Out-File c:\PMC\Disk\OutPut\Newcastle.txt
</code>```

This just returns an error.

答:
Here is an example how to do it:

```<code>gwmi Win32_LogicalDisk -Filter "DeviceID='C:'" | select Name, FileSystem,FreeSpace,BlockSize,Size | % {$_.BlockSize=(($_.FreeSpace)/($_.Size))*100;$_.FreeSpace=($_.FreeSpace/1GB);$_.Size=($_.Size/1GB);$_}| Format-Table Name, @{n='FS';e={$_.FileSystem}},@{n='Free, Gb';e={'{0:N2}'-f
$_.FreeSpace}}, @{n='Free,%';e={'{0:N2}'-f $_.BlockSize}} -AutoSize
</code>```

output:

```<code>Name FS   Free, Gb Free,%
---- --   -------- ------
C:   NTFS 593.59   31.88
</code>```

Title: Disk Space Check in Powershell

Body:
I am currently checking disk space size using power shell but was wondering how I can amend the below to add a percentage of space left?

Format-Table DeviceId, MediaType, @{n="Size";e={[math]::Round($_.Size/1MB,2)}},@{n="FreeSpace";e={[math]::Round($_.FreeSpace/1MB,2)}}

I have tried to do it by changing the math but no luck.

gwmi win32_logicaldisk  -Computername PCNAME| Format-Table DeviceId, MediaType, @{n="Size";e={[math]::Round($_.Size/1MB,2)}},@{n="FreeSpace" (%);e={[math]::Round($_.FreeSpace/$_.Size*100,2)}}|Out-File c:\PMC\Disk\OutPut\Newcastle.txt

This just returns an error.

Body:
Here is an example how to do it:

gwmi Win32_LogicalDisk -Filter "DeviceID='C:'" | select Name, FileSystem,FreeSpace,BlockSize,Size | % {$_.BlockSize=(($_.FreeSpace)/($_.Size))*100;$_.FreeSpace=($_.FreeSpace/1GB);$_.Size=($_.Size/1GB);$_}| Format-Table Name, @{n='FS';e={$_.FileSystem}},@{n='Free, Gb';e={'{0:N2}'-f
$_.FreeSpace}}, @{n='Free,%';e={'{0:N2}'-f $_.BlockSize}} -AutoSize

output:

Name FS   Free, Gb Free,%
---- --   -------- ------
C:   NTFS 593.59   31.88