问:
TSQL - How can I get the total count in a group as part of a subquery
I need to get the total calls per hour per user for the current day, and then calculate the percentage of incoming calls taken by that user.  The purpose in the final analysis is to calculate the percentage of a bonus pot per user per hour.

I can get most of the bits, but am stuck calculating the total calls per hour i.e. total calls for each hour group...

Assume the following data (change the date to the current date if necessary):

```<code>EnteredBy           EnteredOn
Lisa Scandaleyes    05/07/2017 07:40:04
Fred Smith          05/07/2017 07:54:17
A User              05/07/2017 08:15:06
Johnny Johnson      05/07/2017 08:20:57
A User              05/07/2017 09:27:29
A User              05/07/2017 09:36:16
A User              05/07/2017 09:42:36
A User              05/07/2017 10:09:57
</code>```

I can easily get the calls per hour:

```<code>SELECT DATEPART(HOUR, [EnteredOn]) AS Hour, Count(*) as CallsPerHour
FROM CallHandlingCallData
WHERE DATEDIFF(d, EnteredOn, GetDate())= 0
GROUP BY DATEPART(HOUR, [EnteredOn])
ORDER BY Hour;
</code>```

I can also get the calls per hour per user:

```<code>SELECT DATEPART(HOUR, [EnteredOn]) AS Hour, EnteredBy, Count(*) as CallsTaken
FROM CallHandlingCallData
WHERE DATEDIFF(d,EnteredOn, GetDate())= 0
GROUP BY DATEPART(HOUR, [EnteredOn]), EnteredBy
ORDER BY Hour, EnteredBy;
</code>```

I can even get almost everything I want EXCEPT that the TotalCalls value and therefore the percentage is based on ALL CALLS for the day:

```<code>SELECT Hour, EnteredBy, CallsTaken, TotalCalls,
CAST(CallsTaken AS Decimal(10,2)) * 100 / CASE TOTALCALLS WHEN 0 THEN 1 ELSE TotalCalls END AS Percentage
FROM
(
    SELECT DATEPART(HOUR, [EnteredOn]) AS Hour, EnteredBy, Count(*)as CallsTaken,
    (SELECT Count(*) FROM CallHandlingCallData WHERE DATEDIFF(d, EnteredOn, GetDate())= 0) AS TotalCalls
    FROM CallHandlingCallData
    WHERE DATEDIFF(d,EnteredOn, GetDate())= 0
    GROUP BY DATEPART(HOUR, [EnteredOn]), EnteredBy
) data
ORDER BY Hour, EnteredBy;
</code>```

This is really close, I just need to get the sub-query to give me the total calls for that hour, instead of for the whole day.

Notes

I am unable to use OVER() as it is not supported by one of the database engines that may be used with the final query.

I would prefer to do such calculations in the UI, but the result has to be output to a spreadsheet removing that option

Any suggestions would be most gratefully received.

答:
Calculate the group totals separately, then join them up.

```<code>SELECT
    DATEPART(HOUR, C1.EnteredOn) AS [Hour],
    C1.EnteredBy,
    COUNT(*) AS CallsTaken,
    Totals.TotalCalls,
    CAST(COUNT(*) * 100.0 / Totals.TotalCalls AS DECIMAL(10, 2)) AS [Percentage]
FROM CallHandlingCallData AS C1
JOIN (
    SELECT DATEPART(HOUR, C2.EnteredOn) AS [Hour], COUNT(*) AS TotalCalls
    FROM CallHandlingCallData AS C2
    WHERE DATEDIFF(d, C2.EnteredOn, GetDate()) = 0
    GROUP BY DATEPART(HOUR, C2.EnteredOn)
) Totals ON Totals.[Hour] = DATEPART(HOUR, C1.EnteredOn)
WHERE DATEDIFF(d, C1.EnteredOn, GetDate()) = 0
GROUP BY
    DATEPART(HOUR, C1.EnteredOn),
    C1.EnteredBy,
    Totals.TotalCalls
</code>```

If it looks like I'm overdoing it with the aliases: I find it's much better to be safe than sorry when it comes to disambiguating inner and outer column references.

If you need rows with zeroes for hours where nothing happened as well, that's a whole 'nother kettle of fish with UNION ALL and number tables and I'm not going there unless we have to.

Body:
I need to get the total calls per hour per user for the current day, and then calculate the percentage of incoming calls taken by that user.  The purpose in the final analysis is to calculate the percentage of a bonus pot per user per hour.

I can get most of the bits, but am stuck calculating the total calls per hour i.e. total calls for each hour group...

Assume the following data (change the date to the current date if necessary):

EnteredBy           EnteredOn
Lisa Scandaleyes    05/07/2017 07:40:04
Fred Smith          05/07/2017 07:54:17
A User              05/07/2017 08:15:06
Johnny Johnson      05/07/2017 08:20:57
A User              05/07/2017 09:27:29
A User              05/07/2017 09:36:16
A User              05/07/2017 09:42:36
A User              05/07/2017 10:09:57

I can easily get the calls per hour:

SELECT DATEPART(HOUR, [EnteredOn]) AS Hour, Count(*) as CallsPerHour
FROM CallHandlingCallData
WHERE DATEDIFF(d, EnteredOn, GetDate())= 0
GROUP BY DATEPART(HOUR, [EnteredOn])
ORDER BY Hour;

I can also get the calls per hour per user:

SELECT DATEPART(HOUR, [EnteredOn]) AS Hour, EnteredBy, Count(*) as CallsTaken
FROM CallHandlingCallData
WHERE DATEDIFF(d,EnteredOn, GetDate())= 0
GROUP BY DATEPART(HOUR, [EnteredOn]), EnteredBy
ORDER BY Hour, EnteredBy;

I can even get almost everything I want EXCEPT that the TotalCalls value and therefore the percentage is based on ALL CALLS for the day:

SELECT Hour, EnteredBy, CallsTaken, TotalCalls,
CAST(CallsTaken AS Decimal(10,2)) * 100 / CASE TOTALCALLS WHEN 0 THEN 1 ELSE TotalCalls END AS Percentage
FROM
(
    SELECT DATEPART(HOUR, [EnteredOn]) AS Hour, EnteredBy, Count(*)as CallsTaken,
    (SELECT Count(*) FROM CallHandlingCallData WHERE DATEDIFF(d, EnteredOn, GetDate())= 0) AS TotalCalls
    FROM CallHandlingCallData
    WHERE DATEDIFF(d,EnteredOn, GetDate())= 0
    GROUP BY DATEPART(HOUR, [EnteredOn]), EnteredBy
) data
ORDER BY Hour, EnteredBy;

This is really close, I just need to get the sub-query to give me the total calls for that hour, instead of for the whole day.

Notes

I am unable to use OVER() as it is not supported by one of the database engines that may be used with the final query.

I would prefer to do such calculations in the UI, but the result has to be output to a spreadsheet removing that option

Any suggestions would be most gratefully received.

Body:
Calculate the group totals separately, then join them up.

SELECT
    DATEPART(HOUR, C1.EnteredOn) AS [Hour],
    C1.EnteredBy,
    COUNT(*) AS CallsTaken,
    Totals.TotalCalls,
    CAST(COUNT(*) * 100.0 / Totals.TotalCalls AS DECIMAL(10, 2)) AS [Percentage]
FROM CallHandlingCallData AS C1
JOIN (
    SELECT DATEPART(HOUR, C2.EnteredOn) AS [Hour], COUNT(*) AS TotalCalls
    FROM CallHandlingCallData AS C2
    WHERE DATEDIFF(d, C2.EnteredOn, GetDate()) = 0
    GROUP BY DATEPART(HOUR, C2.EnteredOn)
) Totals ON Totals.[Hour] = DATEPART(HOUR, C1.EnteredOn)
WHERE DATEDIFF(d, C1.EnteredOn, GetDate()) = 0
GROUP BY
    DATEPART(HOUR, C1.EnteredOn),
    C1.EnteredBy,
    Totals.TotalCalls

If it looks like I'm overdoing it with the aliases: I find it's much better to be safe than sorry when it comes to disambiguating inner and outer column references.

If you need rows with zeroes for hours where nothing happened as well, that's a whole 'nother kettle of fish with UNION ALL and number tables and I'm not going there unless we have to.


来源: stackexchange

问:
How do I refocus on an input field after tabbing past the last one?
I have thee input fields. Two require input one is type submit. Like you see below.

```<code><input id="cs1"   type="text"   value="" placeholder="Call Sign"  onkeyup="showHint(this.value);"  maxlength="16" onmousedown="isKeyPressed(event)" autofocus="autofocus" />

<input id="Fname" type="text"   value="" name="Fname" placeholder="First Name" onkeyup="nameHint(this.value);" onblur="checkIn();" />

<input id="ckin1" type="submit" value="Check In"  />
</code>```

The usual method is input into cs1, which drops hints at possible values. Select a possible value and tab to the Name input. At which time a name may have been automatically filled or not. Either enter the name or accept the one there. Then tab to the submit input and either click on it or press tab.
This is where the problem is, if you tab you are placed on the URL (address bar) which is bad. If you click the submit the cursor is returned correctly to the cs1 input again.
I've tried all kinds of stuff like you see below, but none of it works.

```<code>$(document).ready(function () {
    $('#ckin1').on('keydown', function (e) {
        if (e.keyCode == 9) {
            document.body.firstElementChild.focus();
            e.preventDefault();
            return false;

        }
    });
})
$(document).ready(function () {
$( "#ckin1" ).click(function() {
                $( "#cs1" ).focus();
            });
       });
</code>```

How do I get the cursor to return automatically to the cs1 input filed after a tab from the ckin1 submit?

答:
This seems to work just fine. Since you are already using jQuery, use it to focus the first element.

$("#ckin1").on('keydown', function(e) {
  var keyCode = e.keyCode || e.which;

  if (keyCode == 9 && !e.shiftKey) {
    e.preventDefault();
    $('#cs1').focus();
    return false;
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="cs1"   type="text"   value="" placeholder="Call Sign"  maxlength="16" />

<input id="Fname" type="text"   value="" name="Fname" placeholder="First Name" />

<input id="ckin1" type="submit" value="Check In"  /></code>```

ContentLicense: CC BY-SA 3.0

Body:
I have thee input fields. Two require input one is type submit. Like you see below.

<input id="cs1"   type="text"   value="" placeholder="Call Sign"  onkeyup="showHint(this.value);"  maxlength="16" onmousedown="isKeyPressed(event)" autofocus="autofocus" />

<input id="Fname" type="text"   value="" name="Fname" placeholder="First Name" onkeyup="nameHint(this.value);" onblur="checkIn();" />

<input id="ckin1" type="submit" value="Check In"  />

The usual method is input into cs1, which drops hints at possible values. Select a possible value and tab to the Name input. At which time a name may have been automatically filled or not. Either enter the name or accept the one there. Then tab to the submit input and either click on it or press tab.
This is where the problem is, if you tab you are placed on the URL (address bar) which is bad. If you click the submit the cursor is returned correctly to the cs1 input again.
I've tried all kinds of stuff like you see below, but none of it works.

$(document).ready(function () {
    $('#ckin1').on('keydown', function (e) {
        if (e.keyCode == 9) {
            document.body.firstElementChild.focus();
            e.preventDefault();
            return false;

        }
    });
})
$(document).ready(function () {
$( "#ckin1" ).click(function() {
                $( "#cs1" ).focus();
            });
       });

How do I get the cursor to return automatically to the cs1 input filed after a tab from the ckin1 submit?

Body:
This seems to work just fine. Since you are already using jQuery, use it to focus the first element.

$("#ckin1").on('keydown', function(e) {
  var keyCode = e.keyCode || e.which;

  if (keyCode == 9 && !e.shiftKey) {
    e.preventDefault();
    $('#cs1').focus();
    return false;
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="cs1"   type="text"   value="" placeholder="Call Sign"  maxlength="16" />

<input id="Fname" type="text"   value="" name="Fname" placeholder="First Name" />

<input id="ckin1" type="submit" value="Check In"  />


问:
Easy way to integrate branches into trunk
I'm running Subversion version 1.4.3 (r23084) + tortoise, and my problem is integrating an branch into trunk. Tortoise's merge didnt work, i got to do this from console.

Its always a hard work to do because of many issues, so i've been thinking about some changes.
Will a subversion update (its on 1.6 now) resolve my problem?
Or its better to change everything and start all over again with GIT ?

tnx!

答:
Merge tracking was added to svn in 1.5, so yes upgrading will likely solve some of your merging issues.

If your only complaint about svn is its merging, you should upgrade before doing something as drastic as switching to git.

That said, git is much better than svn for lots of reasons, and I highly recommend it.

ContentLicense: CC BY-SA 2.5


问:
Export to Excel/print HTML table with gridlines
I currently have an HTML table in my ASP.NET MVC project that can be exported to Excel or printed using some JavaScript I found online. Both of these features export/print the table without gridlines, which makes the data very hard to read especially when there's significant amounts of text in a cell.

The table is wrapped in a div#table-wrapper, and #printer and #excel are small icons that when clicked print/export the table. Here is the JavaScript:

```<code>$("#printer").on("click", function () {
    var divToPrint = document.getElementById('table-wrapper');
    newWin = window.open("");
    newWin.document.write(divToPrint.outerHTML);
    newWin.print();
    newWin.close();
});

$("#excel").on("click", function (e) {
    e.preventDefault();

    var data_type = 'data:application/vnd.ms-excel';
    var table_div = document.getElementById('table-wrapper');
    var table_html = table_div.outerHTML.replace(/ /g, '%20');

    var a = document.createElement('a');
    a.href = data_type + ', ' + table_html;
    a.download = 'exported_table_' + Math.floor(Math.random() * 9999999 + 1000000) + '.xls';
    a.click();
});
</code>```

Here's a picture of the spreadsheet:

Here's a picture of the print preview:

If someone knows how I can add gridlines to these that would be much appreciated!

EDIT: I've added this stylesheet to my project and still have no luck on the print table.

```<code>@media print {
    th, td {
        border: 1px solid #000;
        padding: 0.5em;
    }
}
</code>```

EDIT #2: Here's the table.

```<code><div id="table-wrapper">
    <table class="table table-striped table-bordered" id="results-grid">
        <thead>
            <tr id="results-heading">
                <th>Submission #</th>
                <th>First Named Insured</th>
                <th>Status</th>
                <th>TA Name</th>
                <th>Policy #</th>
                <th>Branch</th>
                <th>Underwriter</th>
                <th>Division</th>
                <th>Project Name</th>
                <th>Project Address</th>
                <th>Project City/State/Zip</th>
            </tr>
        </thead>
        @if (Model.Projects.Any())
        {
            <tbody>
                @foreach (var item in Model.Projects)
                {
                <tr data-id="@item.id" data-subNum="@item.submission_number" data-readOnly="@Model.ReadOnly" class="clickable-row">
                    @if (Model.Cleared)
                    {
                        <td><a onclick="displayDetails(@item.id)">@Html.DisplayFor(modelItem => item.submission_number)</a></td>
                    }
                    else
                    {
                        <td>@Html.DisplayFor(modelItem => item.submission_number)</td>
                    }
                    <td>@Html.DisplayFor(modelItem => item.first_named_insured)</td>
                    <td>@Html.DisplayFor(modelItem => item.status)</td>
                    <td>@Html.DisplayFor(modelItem => item.ta_name)</td>
                    <td>@Html.DisplayFor(modelItem => item.policy_number)</td>
                    <td>@Html.DisplayFor(modelItem => item.branch)</td>
                    <td>@Html.DisplayFor(modelItem => item.underwriter)</td>
                    <td>@Html.DisplayFor(modelItem => item.division)</td>
                    <td>@Html.DisplayFor(modelItem => item.project_name)</td>
                    <td>@Html.DisplayFor(modelItem => item.project_address)</td>
                    <td>@Html.DisplayFor(modelItem => item.project_city), @Html.DisplayFor(modelItem => item.project_state), @Html.DisplayFor(modelItem => item.project_zip_code)</td>
                </tr>
                }
            </tbody>
        }
    </table>
</div>
</code>```

答:
As Mark mentioned in the comments, you can use media queries for different media types. Here's the syntax to add to your CSS stylesheet:

```<code>@media print {
/* CSS code that adds lines or bottom border to table */
}
</code>```

You can also have different stylesheets for different media by defining them in the head of your html like this:

```<code><link rel="stylesheet" media="print" href="print.css">
</code>```

Body:
I currently have an HTML table in my ASP.NET MVC project that can be exported to Excel or printed using some JavaScript I found online. Both of these features export/print the table without gridlines, which makes the data very hard to read especially when there's significant amounts of text in a cell.

The table is wrapped in a div#table-wrapper, and #printer and #excel are small icons that when clicked print/export the table. Here is the JavaScript:

$("#printer").on("click", function () {
    var divToPrint = document.getElementById('table-wrapper');
    newWin = window.open("");
    newWin.document.write(divToPrint.outerHTML);
    newWin.print();
    newWin.close();
});

$("#excel").on("click", function (e) {
    e.preventDefault();

    var data_type = 'data:application/vnd.ms-excel';
    var table_div = document.getElementById('table-wrapper');
    var table_html = table_div.outerHTML.replace(/ /g, '%20');

    var a = document.createElement('a');
    a.href = data_type + ', ' + table_html;
    a.download = 'exported_table_' + Math.floor(Math.random() * 9999999 + 1000000) + '.xls';
    a.click();
});

Here's a picture of the spreadsheet:

Here's a picture of the print preview:

If someone knows how I can add gridlines to these that would be much appreciated!

EDIT: I've added this stylesheet to my project and still have no luck on the print table.

@media print {
    th, td {
        border: 1px solid #000;
        padding: 0.5em;
    }
}

EDIT #2: Here's the table.

                Submission #
                First Named Insured
                Status
                TA Name
                Policy #
                Branch
                Underwriter
                Division
                Project Name
                Project Address
                Project City/State/Zip

        @if (Model.Projects.Any())
        {

                @foreach (var item in Model.Projects)
                {

                    @if (Model.Cleared)
                    {
                        @Html.DisplayFor(modelItem => item.submission_number)
                    }
                    else
                    {
                        @Html.DisplayFor(modelItem => item.submission_number)
                    }
                    @Html.DisplayFor(modelItem => item.first_named_insured)
                    @Html.DisplayFor(modelItem => item.status)
                    @Html.DisplayFor(modelItem => item.ta_name)
                    @Html.DisplayFor(modelItem => item.policy_number)
                    @Html.DisplayFor(modelItem => item.branch)
                    @Html.DisplayFor(modelItem => item.underwriter)
                    @Html.DisplayFor(modelItem => item.division)
                    @Html.DisplayFor(modelItem => item.project_name)
                    @Html.DisplayFor(modelItem => item.project_address)
                    @Html.DisplayFor(modelItem => item.project_city), @Html.DisplayFor(modelItem => item.project_state), @Html.DisplayFor(modelItem => item.project_zip_code)

                }

        }

Body:
As Mark mentioned in the comments, you can use media queries for different media types. Here's the syntax to add to your CSS stylesheet:

@media print {
/* CSS code that adds lines or bottom border to table */
}

You can also have different stylesheets for different media by defining them in the head of your html like this:

<link rel="stylesheet" media="print" href="print.css">


问:
Dropbox API error when uploading image (Python)
I am currently doing a motion detection program. I have already managed to capture images when motion is detected. I want the photos to be uploaded to Dropbox when captured. It works fine for the first few images but stops working after awhile. It displays the following error

ApiError: ApiError('', UploadError(u'path', UploadWriteFailed(reason=WriteError(u'conflict', WriteConflictError(u'file', None)), upload_session_id=u'')))

This is my code

```<code>def TakePicUpload(avg):
</code>```

答:
You're getting a file WriteConflictError:

https://dropbox-sdk-python.readthedocs.io/en/latest/api/files.html?highlight=writeconflicterror#dropbox.files.WriteConflictError

That's documented as:

There’s a file in the way.

So, that just means there's already at the path (savetolocation in your case) where you're trying to upload.

You can either remove that file if you don't want it, or specify a different write mode when calling files_upload:

https://dropbox-sdk-python.readthedocs.io/en/latest/api/dropbox.html?highlight=files_upload#dropbox.dropbox.Dropbox.files_upload

More specifically you can add mode=dropbox.files.WriteMode.overwrite as a parameter to files_upload method.

Body:
I am currently doing a motion detection program. I have already managed to capture images when motion is detected. I want the photos to be uploaded to Dropbox when captured. It works fine for the first few images but stops working after awhile. It displays the following error

ApiError: ApiError('', UploadError(u'path', UploadWriteFailed(reason=WriteError(u'conflict', WriteConflictError(u'file', None)), upload_session_id=u'')))

This is my code

def TakePicUpload(avg):

ContentLicense: CC BY-SA 4.0


问:
Injecting a singleton into JAX-RS (Jersey) resources, as a Tomcat servlet
I'm trying to build a RESTful web service. This component is an addition to an existing Tomcat 7 web application that contains several Servlets already. I'm using Jersey 2.25.

I need to instantiate a few components (objects) that are related to the existing system. I wish to do that once, while the application loads - and than read them from each Resource.

My current classes are:

```<code>@ApplicationPath("resources")
public class MyApplication extends ResourceConfig {

    public MyApplication() {
        packages("plc_webservice.PersonResource");

        register(new MyBinder());
    }
}

public class MyBinder extends AbstractBinder{

    @Override
    protected void configure() {
        bind(new MyService()).to(MyService.class);
    }
}
</code>```

This is the class that I want to use as a singleton:

```<code>public class MyService {
    String name;

    public MyService() {
        name = "John";
    }

    public String getName() {
        return name;
    }
}
</code>```

And a resource:

```<code>@Path("Person")
public class PersonResource {

    @Inject
    private MyService service;

    @GET
    public String test() {
        String result = "Hello!";

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

I can't figure out why am I getting this exception:

javax.servlet.ServletException: A MultiException has 3 exceptions.
  They are:
  1. org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at
  SystemInjecteeImpl(requiredType=MyService,parent=PersonResource,qualifiers={},position=-1,optional=false,self=false,unqualified=null,1688478701)
  2. java.lang.IllegalArgumentException: While attempting to resolve the dependencies of plc_webservice.PersonResource errors were found
  3. java.lang.IllegalStateException: Unable to perform operation: resolve on plc_webservice.PersonResource

org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:489)
    org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
  root cause

A MultiException has 3 exceptions.  They are:
  1. org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at
  SystemInjecteeImpl(requiredType=MyService,parent=PersonResource,qualifiers={},position=-1,optional=false,self=false,unqualified=null,1688478701)
  2. java.lang.IllegalArgumentException: While attempting to resolve the dependencies of plc_webservice.PersonResource errors were found
  3. java.lang.IllegalStateException: Unable to perform operation: resolve on plc_webservice.PersonResource

org.jvnet.hk2.internal.Collector.throwIfErrors(Collector.java:89)
    org.jvnet.hk2.internal.ClazzCreator.resolveAllDependencies(ClazzCreator.java:250)
    org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:358)
    org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:487)
    org.glassfish.jersey.process.internal.RequestScope.findOrCreate(RequestScope.java:162)
    org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2022)
    org.jvnet.hk2.internal.ServiceLocatorImpl.internalGetService(ServiceLocatorImpl.java:774)
    org.jvnet.hk2.internal.ServiceLocatorImpl.internalGetService(ServiceLocatorImpl.java:737)
    org.jvnet.hk2.internal.ServiceLocatorImpl.getService(ServiceLocatorImpl.java:707)
    org.glassfish.jersey.internal.inject.Injections.getOrCreate(Injections.java:172)
    org.glassfish.jersey.server.model.MethodHandler$ClassBasedMethodHandler.getInstance(MethodHandler.java:284)
    org.glassfish.jersey.server.internal.routing.PushMethodHandlerRouter.apply(PushMethodHandlerRouter.java:74)
    org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:109)
    org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
    org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
    org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
    org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:92)
    org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:61)
    org.glassfish.jersey.process.internal.Stages.process(Stages.java:197)
    org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:318)
    org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
    org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305)
    org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)
    org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:473)
    org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
  root cause

org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no
  object available for injection at
  SystemInjecteeImpl(requiredType=MyService,parent=PersonResource,qualifiers={},position=-1,optional=false,self=false,unqualified=null,1688478701)  org.jvnet.hk2.internal.ThreeThirtyResolver.resolve(ThreeThirtyResolver.java:75)
    org.jvnet.hk2.internal.ClazzCreator.resolve(ClazzCreator.java:212)
    org.jvnet.hk2.internal.ClazzCreator.resolveAllDependencies(ClazzCreator.java:235)
    org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:358)
    org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:487)
    org.glassfish.jersey.process.internal.RequestScope.findOrCreate(RequestScope.java:162)
    org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2022)
    org.jvnet.hk2.internal.ServiceLocatorImpl.internalGetService(ServiceLocatorImpl.java:774)
    org.jvnet.hk2.internal.ServiceLocatorImpl.internalGetService(ServiceLocatorImpl.java:737)
    org.jvnet.hk2.internal.ServiceLocatorImpl.getService(ServiceLocatorImpl.java:707)
    org.glassfish.jersey.internal.inject.Injections.getOrCreate(Injections.java:172)
    org.glassfish.jersey.server.model.MethodHandler$ClassBasedMethodHandler.getInstance(MethodHandler.java:284)
    org.glassfish.jersey.server.internal.routing.PushMethodHandlerRouter.apply(PushMethodHandlerRouter.java:74)
    org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:109)
    org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
    org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
    org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
    org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:92)
    org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:61)
    org.glassfish.jersey.process.internal.Stages.process(Stages.java:197)
    org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:318)
    org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
    org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305)
    org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)
    org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:473)
    org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)

Thank you.

答: I think this is a CDI question. Do you have beans.xml defined? Also, if you want MyService to be a singleton, I think you want to annotate it with @ApplicationScoped.

Body:
I'm trying to build a RESTful web service. This component is an addition to an existing Tomcat 7 web application that contains several Servlets already. I'm using Jersey 2.25.

I need to instantiate a few components (objects) that are related to the existing system. I wish to do that once, while the application loads - and than read them from each Resource.

My current classes are:

@ApplicationPath("resources")
public class MyApplication extends ResourceConfig {

    public MyApplication() {
        packages("plc_webservice.PersonResource");

        register(new MyBinder());
    }
}

public class MyBinder extends AbstractBinder{

    @Override
    protected void configure() {
        bind(new MyService()).to(MyService.class);
    }
}

This is the class that I want to use as a singleton:

public class MyService {
    String name;

    public MyService() {
        name = "John";
    }

    public String getName() {
        return name;
    }
}

And a resource:

@Path("Person")
public class PersonResource {

    @Inject
    private MyService service;

    @GET
    public String test() {
        String result = "Hello!";

        return result;
    }
}

I can't figure out why am I getting this exception:

javax.servlet.ServletException: A MultiException has 3 exceptions.
  They are:
  1. org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at
  SystemInjecteeImpl(requiredType=MyService,parent=PersonResource,qualifiers={},position=-1,optional=false,self=false,unqualified=null,1688478701)
  2. java.lang.IllegalArgumentException: While attempting to resolve the dependencies of plc_webservice.PersonResource errors were found
  3. java.lang.IllegalStateException: Unable to perform operation: resolve on plc_webservice.PersonResource

org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:489)
    org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
  root cause

A MultiException has 3 exceptions.  They are:
  1. org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at
  SystemInjecteeImpl(requiredType=MyService,parent=PersonResource,qualifiers={},position=-1,optional=false,self=false,unqualified=null,1688478701)
  2. java.lang.IllegalArgumentException: While attempting to resolve the dependencies of plc_webservice.PersonResource errors were found
  3. java.lang.IllegalStateException: Unable to perform operation: resolve on plc_webservice.PersonResource

org.jvnet.hk2.internal.Collector.throwIfErrors(Collector.java:89)
    org.jvnet.hk2.internal.ClazzCreator.resolveAllDependencies(ClazzCreator.java:250)
    org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:358)
    org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:487)
    org.glassfish.jersey.process.internal.RequestScope.findOrCreate(RequestScope.java:162)
    org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2022)
    org.jvnet.hk2.internal.ServiceLocatorImpl.internalGetService(ServiceLocatorImpl.java:774)
    org.jvnet.hk2.internal.ServiceLocatorImpl.internalGetService(ServiceLocatorImpl.java:737)
    org.jvnet.hk2.internal.ServiceLocatorImpl.getService(ServiceLocatorImpl.java:707)
    org.glassfish.jersey.internal.inject.Injections.getOrCreate(Injections.java:172)
    org.glassfish.jersey.server.model.MethodHandler$ClassBasedMethodHandler.getInstance(MethodHandler.java:284)
    org.glassfish.jersey.server.internal.routing.PushMethodHandlerRouter.apply(PushMethodHandlerRouter.java:74)
    org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:109)
    org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
    org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
    org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
    org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:92)
    org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:61)
    org.glassfish.jersey.process.internal.Stages.process(Stages.java:197)
    org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:318)
    org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
    org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305)
    org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)
    org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:473)
    org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
  root cause

org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no
  object available for injection at
  SystemInjecteeImpl(requiredType=MyService,parent=PersonResource,qualifiers={},position=-1,optional=false,self=false,unqualified=null,1688478701)  org.jvnet.hk2.internal.ThreeThirtyResolver.resolve(ThreeThirtyResolver.java:75)
    org.jvnet.hk2.internal.ClazzCreator.resolve(ClazzCreator.java:212)
    org.jvnet.hk2.internal.ClazzCreator.resolveAllDependencies(ClazzCreator.java:235)
    org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:358)
    org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:487)
    org.glassfish.jersey.process.internal.RequestScope.findOrCreate(RequestScope.java:162)
    org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2022)
    org.jvnet.hk2.internal.ServiceLocatorImpl.internalGetService(ServiceLocatorImpl.java:774)
    org.jvnet.hk2.internal.ServiceLocatorImpl.internalGetService(ServiceLocatorImpl.java:737)
    org.jvnet.hk2.internal.ServiceLocatorImpl.getService(ServiceLocatorImpl.java:707)
    org.glassfish.jersey.internal.inject.Injections.getOrCreate(Injections.java:172)
    org.glassfish.jersey.server.model.MethodHandler$ClassBasedMethodHandler.getInstance(MethodHandler.java:284)
    org.glassfish.jersey.server.internal.routing.PushMethodHandlerRouter.apply(PushMethodHandlerRouter.java:74)
    org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:109)
    org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
    org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
    org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
    org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:92)
    org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:61)
    org.glassfish.jersey.process.internal.Stages.process(Stages.java:197)
    org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:318)
    org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
    org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305)
    org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)
    org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:473)
    org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)

Thank you.


问:
Best way to convert list data to another with a desired format in c# using LINQ
How I need to insert a chart in my project and I use the C3 library to do so, which expect a specific format to work.

I retrieve my data from my database and I get it into this format

```<code>{"TotalbeAbsencesDepartmentByReason":[
[   {"Label":"DQUA","Reason":"AUT","AbsNumber":1,"AbsenceHours":3.75},
    {"Label":"DQUA","Reason":"NOAUT","AbsNumber":1,"AbsenceHours":3.75},
    {"Label":"DQUA","Reason":"CM","AbsNumber":4,"AbsenceHours":32}
],
[{"Label":"DPRO","Reason":"AUT","AbsNumber":10,"AbsenceHours":43.9},{"Label":"DPRO","Reason":"CM","AbsNumber":18,"AbsenceHours":144}],
[{"Label":"DMAI","Reason":"AUT","AbsNumber":2,"AbsenceHours":1.6999999999999993}],
[{"Label":"DENG","Reason":"CM","AbsNumber":2,"AbsenceHours":16}]
]}
</code>```

My expected format that I want to work on is :

```<code>"TotaleAbsDepartementByReason":
[
    {"Label":"DQUA","Aut":3.75,"NoAut":3.75,"CM":32},
    {"Label":"DPRO","Aut":43.9,"NoAut":0,"CM":144},
    {"Label":"DMAI","Aut":1.6999999999999993,"NoAut":0,"CM":0},
    {"Label":"DENG","Aut":0,"NoAut":0,"CM":16}
]
</code>```

This is my solution it works perfectly, But I think that there is another way to proceed for better performance :

```<code>var DeptNames = TotalbeAbsencesDepartmentByReason.Select(b => b.Label).Distinct();
var TotaleAbsDepartementByReason = new List<AbsByReason>();
foreach (var name in DeptNames)
{
    var auth = TotalbeAbsencesDepartmentByReason.Where(a => a.Label == name && a.Reason == "AUT").FirstOrDefault();
    var noauth = TotalbeAbsencesDepartmentByReason.Where(a => a.Label == name && a.Reason == "NOAUT").FirstOrDefault();
    var cm = TotalbeAbsencesDepartmentByReason.Where(a => a.Label == name && a.Reason == "CM").FirstOrDefault();
    TotaleAbsDepartementByReason.Add(new AbsByReason
    {
        Aut = auth != null ? auth.AbsenceHours.Value : 0 ,
        CM = cm != null ? cm.AbsenceHours.Value : 0,
        NoAut = noauth != null ? noauth.AbsenceHours.Value : 0,
        Label = name
    });
}
</code>```

答:
You can organize your code slightly better, at-least from maintainability perspective, and removing some redundancies should hopefully offer some performance boost. Below is the refactored code

```<code>public class RowData {
    public string Label { get; set; }
    public string Reason { get; set; }
    public int AbsNumber { get; set; }
    public decimal? AbsenceHours { get; set; }
}

public class AbsByReason {
    public decimal Aut { get; set; }
    public decimal CM { get; set; }
    public string Label { get; set; }
    public object NoAut { get; set; }
}

public static IEnumerable<AbsByReason> TransformData(List<RowData> totalbeAbsencesDepartmentByReason) {
    return totalbeAbsencesDepartmentByReason
                .GroupBy(row => row.Label)
                .Select(XFormLabelGroupToAbsByReason);
}

private static AbsByReason XFormLabelGroupToAbsByReason(IEnumerable<RowData> labelGroup) {
    var reason = new AbsByReason();
    foreach (var rowData in labelGroup) {
        if (rowData.Reason == "AUT")
            reason.Aut = rowData.AbsenceHours ?? 0;
        else if (rowData.Reason == "NOAUT")
            reason.NoAut = rowData.AbsenceHours ?? 0;
        else if (rowData.Reason == "CM")
            reason.CM = rowData.AbsenceHours ?? 0;
    }
    return reason;
}
</code>```

Let me explain what I have done. GroupBy is very helpful when using grouped data as you are in this case. Once you group your data, you only need to transform that group (instead of all the data in the list). You can use LINQ, but I would rather use a simple for-loop and if-else-if combination. I find it better to do things in single-pass than in multi-pass LINQ way even though you are pretty much talking about no more than 3 items in the list.

Body:
How I need to insert a chart in my project and I use the C3 library to do so, which expect a specific format to work.

I retrieve my data from my database and I get it into this format

{"TotalbeAbsencesDepartmentByReason":[
[   {"Label":"DQUA","Reason":"AUT","AbsNumber":1,"AbsenceHours":3.75},
    {"Label":"DQUA","Reason":"NOAUT","AbsNumber":1,"AbsenceHours":3.75},
    {"Label":"DQUA","Reason":"CM","AbsNumber":4,"AbsenceHours":32}
],
[{"Label":"DPRO","Reason":"AUT","AbsNumber":10,"AbsenceHours":43.9},{"Label":"DPRO","Reason":"CM","AbsNumber":18,"AbsenceHours":144}],
[{"Label":"DMAI","Reason":"AUT","AbsNumber":2,"AbsenceHours":1.6999999999999993}],
[{"Label":"DENG","Reason":"CM","AbsNumber":2,"AbsenceHours":16}]
]}

My expected format that I want to work on is :

"TotaleAbsDepartementByReason":
[
    {"Label":"DQUA","Aut":3.75,"NoAut":3.75,"CM":32},
    {"Label":"DPRO","Aut":43.9,"NoAut":0,"CM":144},
    {"Label":"DMAI","Aut":1.6999999999999993,"NoAut":0,"CM":0},
    {"Label":"DENG","Aut":0,"NoAut":0,"CM":16}
]

This is my solution it works perfectly, But I think that there is another way to proceed for better performance :

var DeptNames = TotalbeAbsencesDepartmentByReason.Select(b => b.Label).Distinct();
var TotaleAbsDepartementByReason = new List<AbsByReason>();
foreach (var name in DeptNames)
{
    var auth = TotalbeAbsencesDepartmentByReason.Where(a => a.Label == name && a.Reason == "AUT").FirstOrDefault();
    var noauth = TotalbeAbsencesDepartmentByReason.Where(a => a.Label == name && a.Reason == "NOAUT").FirstOrDefault();
    var cm = TotalbeAbsencesDepartmentByReason.Where(a => a.Label == name && a.Reason == "CM").FirstOrDefault();
    TotaleAbsDepartementByReason.Add(new AbsByReason
    {
        Aut = auth != null ? auth.AbsenceHours.Value : 0 ,
        CM = cm != null ? cm.AbsenceHours.Value : 0,
        NoAut = noauth != null ? noauth.AbsenceHours.Value : 0,
        Label = name
    });
}

Body:
You can organize your code slightly better, at-least from maintainability perspective, and removing some redundancies should hopefully offer some performance boost. Below is the refactored code

public class RowData {
    public string Label { get; set; }
    public string Reason { get; set; }
    public int AbsNumber { get; set; }
    public decimal? AbsenceHours { get; set; }
}

public class AbsByReason {
    public decimal Aut { get; set; }
    public decimal CM { get; set; }
    public string Label { get; set; }
    public object NoAut { get; set; }
}

public static IEnumerable<AbsByReason> TransformData(List<RowData> totalbeAbsencesDepartmentByReason) {
    return totalbeAbsencesDepartmentByReason
                .GroupBy(row => row.Label)
                .Select(XFormLabelGroupToAbsByReason);
}

private static AbsByReason XFormLabelGroupToAbsByReason(IEnumerable<RowData> labelGroup) {
    var reason = new AbsByReason();
    foreach (var rowData in labelGroup) {
        if (rowData.Reason == "AUT")
            reason.Aut = rowData.AbsenceHours ?? 0;
        else if (rowData.Reason == "NOAUT")
            reason.NoAut = rowData.AbsenceHours ?? 0;
        else if (rowData.Reason == "CM")
            reason.CM = rowData.AbsenceHours ?? 0;
    }
    return reason;
}

Let me explain what I have done. GroupBy is very helpful when using grouped data as you are in this case. Once you group your data, you only need to transform that group (instead of all the data in the list). You can use LINQ, but I would rather use a simple for-loop and if-else-if combination. I find it better to do things in single-pass than in multi-pass LINQ way even though you are pretty much talking about no more than 3 items in the list.


问:
My C# grading program keep outputting the same result
I just started C# and was making this very simple C# program to print a grade according to the inputed marks.

Here's my program:

```<code>    class data
{

    int marks;
    public void input()
    {
        Console.WriteLine("Enter your marks");
        marks = Convert.ToInt16(Console.ReadLine());

    }

    public void output()
    {
        if (marks >= 75)
        {
            Console.WriteLine("Merit");
        }
        else if (marks < 75)
        {
            Console.WriteLine("Distiction");
        }
        else if (marks < 65)
        {
            Console.WriteLine("Credit");
        }
        else if (marks < 55)
        {
            Console.WriteLine("Pass");
        }
        else Console.WriteLine("Fail");

    }
}
}
</code>```

And here's the main:

```<code> class Program
{
    static void Main(string[] args)
    {
        data obj1 = new data();
        obj1.input();
        obj1.output();
        Console.ReadLine();

    }
}
}
</code>```

Problem is it keeps outputting "Distinction" as the grade no matter what input I give. What am I doing wrong?

Edit - Fail marks is below 40

答:
I'm also having a difficult time trying to resolve your logic - I'll take a hit in negative votes just to get a better feel for your intent.

But I think it's good for you to see that if asked to check if a number sits "between two numbers", you can construct an IF to check only for the lower boundary.

Edit - Fail Mark below 40

```<code>  if (marks >= 75) Console.WriteLine("Merit");
  else if (marks >= 65) Console.WriteLine("Distinction");
  else if (marks >= 55) Console.WriteLine("Credit");
  else if (marks >= 40) Console.WriteLine("Pass");
  else Console.WriteLine("Fail");
</code>```

Body:
I just started C# and was making this very simple C# program to print a grade according to the inputed marks.

Here's my program:

    class data
{

    int marks;
    public void input()
    {
        Console.WriteLine("Enter your marks");
        marks = Convert.ToInt16(Console.ReadLine());

    }

    public void output()
    {
        if (marks >= 75)
        {
            Console.WriteLine("Merit");
        }
        else if (marks < 75)
        {
            Console.WriteLine("Distiction");
        }
        else if (marks < 65)
        {
            Console.WriteLine("Credit");
        }
        else if (marks < 55)
        {
            Console.WriteLine("Pass");
        }
        else Console.WriteLine("Fail");

    }
}
}

And here's the main:

 class Program
{
    static void Main(string[] args)
    {
        data obj1 = new data();
        obj1.input();
        obj1.output();
        Console.ReadLine();

    }
}
}

Problem is it keeps outputting "Distinction" as the grade no matter what input I give. What am I doing wrong?

Edit - Fail marks is below 40

Body:
I'm also having a difficult time trying to resolve your logic - I'll take a hit in negative votes just to get a better feel for your intent.

But I think it's good for you to see that if asked to check if a number sits "between two numbers", you can construct an IF to check only for the lower boundary.

Edit - Fail Mark below 40

  if (marks >= 75) Console.WriteLine("Merit");
  else if (marks >= 65) Console.WriteLine("Distinction");
  else if (marks >= 55) Console.WriteLine("Credit");
  else if (marks >= 40) Console.WriteLine("Pass");
  else Console.WriteLine("Fail");


问:
How to get Null values of records in aerospike

I'm working with aerospike. Using AQL, I inserted some data. I want to get null values of records with particular fields in aerospike. I'm tagging picture in that picture one record does not have a name its empty space

答:
Aeropsike is schemaless - each record is self describing. Any bin that is non-null is part of the record. Any bin that is updated to null actually gets deleted from the record. So, think in terms of units of record instead of a table with columns.  You can query for a specific bin from a record and if not found, Aeropsike will return a null.  Here is the java API:</p>

```<code>public final Record get(Policy policy,
         Key key,
         String... binNames)
                 throws AerospikeException
Read record header and bins for specified key. The policy can be used to specify timeouts.
Specified by:
get in interface IAerospikeClient
Parameters:
policy - generic configuration parameters, pass in null for defaults
key - unique record identifier
binNames - bins to retrieve
Returns:
if found, return record instance. If not found, return null.
Throws:
AerospikeException - if read fails
</code>```

Body:
Aeropsike is schemaless - each record is self describing. Any bin that is non-null is part of the record. Any bin that is updated to null actually gets deleted from the record. So, think in terms of units of record instead of a table with columns.  You can query for a specific bin from a record and if not found, Aeropsike will return a null.  Here is the java API:

public final Record get(Policy policy,
         Key key,
         String... binNames)
                 throws AerospikeException
Read record header and bins for specified key. The policy can be used to specify timeouts.
Specified by:
get in interface IAerospikeClient
Parameters:
policy - generic configuration parameters, pass in null for defaults
key - unique record identifier
binNames - bins to retrieve
Returns:
if found, return record instance. If not found, return null.
Throws:
AerospikeException - if read fails


问:
Jquery .load() function confusion
In the body of my main html page, I have Something to be changed. I have a script that loads in a tag from another page every second with $("#someID").load("otherPage.html #IDfromOtherPage");

On the other html page, the only lines I have are tags for example:

1
 2

At the beginning of the script I have an alert that is alert(document.getElementByID("someID").innerHTML set for debugging purposes and before the .load, the alert says "Something to be changed.", which is correct. Then it runs the .load, waits a second then runs the function again with the next alert. Every alert after the very first correct one says the entire line from the otherPage.html file. The alert says "1" instead of just "1".

Am I doing something wrong? (these id names and file names are just to hopefully make this question easier to follow, not actual variable names)

main html file:

```<code><body>
       <span id="someID">Text to change.</span>
 </body>
 <script>
    $(document).ready(function(){
        $.ajaxSetup({ cache: false });
        setInterval(function(){
            alert(document.getElementById("someID").innerHTML);
            $("#someID").load("values.html #IDfromOtherPage");
        }, 1000);
    });
</script>
</code>```

in my other html file

    1
    2

答:
The documentation of jQuery load (with a fragment #selector) states:

This element, along with its contents, is inserted

So the innerHTML of #someId becomes 1, and not just 1 as you seem to be expecting. This explains why the alert shows that full HTML fragment.

To see just 1, try this:

```<code>alert(document.getElementById("someID").textContent);
</code>```

This will strip off all HTML and just use the text(s) that are present inside the element.

Title: Jquery .load() function confusion

Body:
In the body of my main html page, I have Something to be changed. I have a script that loads in a tag from another page every second with $("#someID").load("otherPage.html #IDfromOtherPage");

On the other html page, the only lines I have are tags for example:

1
 2

At the beginning of the script I have an alert that is alert(document.getElementByID("someID").innerHTML set for debugging purposes and before the .load, the alert says "Something to be changed.", which is correct. Then it runs the .load, waits a second then runs the function again with the next alert. Every alert after the very first correct one says the entire line from the otherPage.html file. The alert says "1" instead of just "1".

Am I doing something wrong? (these id names and file names are just to hopefully make this question easier to follow, not actual variable names)

main html file:

       Text to change.

in my other html file

    1
    2

Body:
The documentation of jQuery load (with a fragment #selector) states:

This element, along with its contents, is inserted

So the innerHTML of #someId becomes <span id="IDfromOtherPage">1</span>, and not just 1 as you seem to be expecting. This explains why the alert shows that full HTML fragment.

To see just 1, try this:

alert(document.getElementById("someID").textContent);

This will strip off all HTML and just use the text(s) that are present inside the element.


问:
How can I solve Error: object 'opencpu' not found
I tried to load the appdemo into opencpu and it gave me an error. How should I solve this error?

Steps to Reproduce:

```<code> 1. git clone git clone https://github.com/rwebapps/appdemo.git
 2. sudo -i R[enter image description here][1]
 3. library(opencpu)
 4. opencpu$browse("/library/appdemo/www")
</code>```

picture of the error on my terminal

答:
In OpenCPU 2.0 you need a different command to start the server:

```<code>ocpu_start_server()
</code>```

Or to directly start the appdemo app

```<code>ocpu_start_app("rwebapps/appdemo")
</code>```

Body:
I tried to load the appdemo into opencpu and it gave me an error. How should I solve this error?

Steps to Reproduce:

 1. git clone git clone https://github.com/rwebapps/appdemo.git
 2. sudo -i R[enter image description here][1]
 3. library(opencpu)
 4. opencpu$browse("/library/appdemo/www")

picture of the error on my terminal

Body:
In OpenCPU 2.0 you need a different command to start the server:

ocpu_start_server()

Or to directly start the appdemo app

ocpu_start_app("rwebapps/appdemo")


问:
Google Dataproc cluster created via HTTP but not listed in SDK or viewer
I am currently working on Google Cloud Platform to run Spark Jobs in the cloud. To do so, I am planning to use Google Cloud Dataproc.

Here's the work flow I am automatising :

Upload a csv file on Google Cloud Storage which will be the input of my Spark job

On upload, trigger a Google Cloud Functions which should create the cluster, submit a job and shutdown the cluster though the HTTP API available for Dataproc

I am able to create a cluster from my Google Cloud Function using the google apis nodejs client (http://google.github.io/google-api-nodejs-client/latest/dataproc.html). But the problem is that I cannot see this cluster on the Dataproc cluster viewer or even by using the Gcloud sdk : gcloud dataproc clusters list.

However, I am able to see my newly created cluster on Google Api explorer : https://developers.google.com/apis-explorer/#p/dataproc/v1/dataproc.projects.regions.clusters.list.

Note that I am creating my cluster in the current project.

What can I possibly do wrong not to be able to see that cluster when listing with gcloud sdk ?

Thank you in advance for your help.

Regards.

答:
I bet it has to do with "region" field. Out of the box Cloud SDK defaults to "global" region [1]. Try using dataproc Cloud SDK commands with --region flag (e.g., gcloud dataproc clusters list --region)

[1] https://cloud.google.com/dataproc/docs/concepts/regional-endpoints


问:
Check if an array is empty hence disable a button
Am trying to disable a button if an array isemty but fails

```<code><button [disabled]="(users.length ==0 )?true:false">Send mass emails</button>
</code>```

IN the ts file

```<code>users: UsersModel[];
</code>```

THe above throws an error

```<code>Bindings cannot contain assignments at column
</code>```

How do i disable that button if the array is emty

答:
It doesn't look like you initialized the users: UsersModel[] array in your component so it's coming back as undefined and you are trying to access length property of an undefined object/array. Try the following to disable the button if users array has NOT been initialized or the length is equal to 0:

```<code><button type="button" [disabled]="!users || users.length === 0">Send Mass Emails</button>
</code>```

Here is plunkr demonstrating this in action.

What you could also consider is initializing the user array to an empty array in your component:

```<code>users: UsersModel[] = [];
</code>```

Then you could simply do to disable/enable the button based on users length being zero/falsy:

```<code><button type="button" [disabled]="!user.length">Send mass emails</button>
</code>```

Here is a plunkr demonstrating initializing the users array to an empty array and checking length to disable button accordingly.

Hopefully that helps!

Body:
Am trying to disable a button if an array isemty but fails

<button [disabled]="(users.length ==0 )?true:false">Send mass emails</button>

IN the ts file

users: UsersModel[];

THe above throws an error

Bindings cannot contain assignments at column

How do i disable that button if the array is emty

Body:
It doesn't look like you initialized the users: UsersModel[] array in your component so it's coming back as undefined and you are trying to access length property of an undefined object/array. Try the following to disable the button if users array has NOT been initialized or the length is equal to 0:

<button type="button" [disabled]="!users || users.length === 0">Send Mass Emails</button>

Here is plunkr demonstrating this in action.

What you could also consider is initializing the user array to an empty array in your component:

users: UsersModel[] = [];

Then you could simply do to disable/enable the button based on users length being zero/falsy:

<button type="button" [disabled]="!user.length">Send mass emails</button>

Here is a plunkr demonstrating initializing the users array to an empty array and checking length to disable button accordingly.

Hopefully that helps!


问:
How to implement the VirtualizedList with remote data?
I have a remote API which generates a call history list. This can of course get quite long, so I need to lazyload it. From the RN docs I gather that the best choice would be a VirtualizedList. But the documentation is terribly lacking. For example, it talks about item keys. I can provide my own function for that (using date/time value), but the getItem prop is still asking for array indexes starting with 0. So what does RN use the keys for?

Another thing is, I am printing out the calls to getItem, and renderItem, and I see a really weird pattern (I have set both initialNumToRender and maxToRenderPerBatch to 13). This is all on app startup, no user interaction. Also my getItemCount returns 15:

```<code>VirtualizedList.render() call
getItem 13 times: 0-12
getItem 0
renderItem 13 times: 0-12
VirtualizedList.render() call
getItem 13 times: 0-12
getItem 12
getItem 0
renderItem 12 times: 0-12
getItem 0
getItem 12
VirtualizedList.render() call
getItem 13 times: 0-12
getItem 12
getItem 0
renderItem 12 times: 0-12
getItem 0
getItem 12
getItem 0
getItem 12
(10 more like the 2 repeating above)
getItem 0-12
getItem 1
getItem 2
getItem 3
getItem 4
getItem 5
getItem 6
getItem 9
getItem 10
getItem 12   (Skipping some items here???)
onViewableItemsChanged, info= Object {viewableItems: Array(9), changed: Array(9)}
getItem 0-14
getItem 0-14
renderItem 0-14
onEndReached, info= Object {distanceFromEnd: 93.5}  (what is that value 93.5????)
getItem 0-12
getItem 0-11
onViewableItemsChanged, info= Object {viewableItems: Array(12), changed: Array(5)}
getItem 0-14
onEndReached, info= Object {distanceFromEnd: 221???}
getItem 0-11
getItem 0-10
onViewableItemsChanged, info= Object {viewableItems: Array(11), changed: Array(1)}
getItem 0-14
</code>```

Note that I haven't touched the screen yet. Now, when I scroll up a little I get the following events:

```<code>getItem 0-12
(repeats for around 20 times)
onViewableItemsChanged, info= Object {viewableItems: Array(12), changed: Array(1)}
getItem 0-12
(repeats for around 20 times)
</code>```

It seems for each pixel I scroll, all items are retrieved.

For reference, here's my code:

```<code>import Expo from 'expo';
import React, { PureComponent } from 'react';
import { Platform, FlatList, VirtualizedList, View, StyleSheet, Text } from 'react-native';
import { combineReducers } from 'redux';
import { ListItem } from 'react-native-elements';
import { connect } from 'react-redux';
import I18n from '../i18n';
import { takeEvery, all, call, put, select } from 'redux-saga/effects';
import RecentRow from '../components/RecentRow';
import { getUserId } from './Settings';
import { AppText, AppHeaderText } from '../components/AppText';

// action types
const RECENT_LOAD = 'RECENT_LOAD';
const RECENT_LOAD_OK = 'RECENT_LOAD_OK';
const RECENT_LOAD_ERROR = 'RECENT_LOAD_ERROR';

// action functions
export function recentLoad(offset) {
  return {
    type: RECENT_LOAD,
    offset: offset,
  };
}

// reducers
function recent(state = { offset: 1, data: [] }, action) {
  //console.log('recent', action);
  switch (action.type) {
    case RECENT_LOAD:
      return {
        ...state,
        offset: action.offset
      };

    case RECENT_LOAD_OK:
      return {
        ...state,
        data: action.data,
      };
    default:
      return state;
  }
}

// combined reducer
export const recentList = combineReducers({
  recent: recent,
});

export const getRecent = state => state.recent;
export const getAccount = state => state.settings.account;

function* recentLoadData(action) {
  const account = yield select(getAccount);
  const URL = `https://www.xxxxx.xx/api/calls.php?userrname=${account.email}&offset=${action.offset}`;
  try {
    const response = yield call(fetch, URL);
    if (response.status === 200) {
      result = yield call([response, 'json']);
      yield put({ type: RECENT_LOAD_OK, data: result });
    } else {
      yield put({ type: RECENT_LOAD_ERROR, error: response.status });
    }
  }
  catch(error) {
    console.log('error:', error);
    yield put({ type: RECENT_LOAD_ERROR, error: error })
  }
}

function* recentLoadSaga() {
  yield takeEvery('RECENT_LOAD', recentLoadData);
}

export function* recentSaga() {
  yield all([
    recentLoadSaga(),
  ])
}

class RecentList extends PureComponent {
  componentDidMount() {
    this.props.loadRecentCalls();
  }

  _renderItem = (item, userid) => {
    console.log('_renderItem', item);
    //return <RecentRow row={item} userid={userid} />
    return <ListItem title={item.item.name + ' ' + item.item.id } />
  }

  renderSeparator = () => {
    return (
      <View
        style={{
          height: 1,
          width: "95%",
          backgroundColor: "#CED0CE",
          marginLeft: "5%"
        }}
      />
    );
  };

  render() {
    console.log('RecentList.render()');
    return (
      <View style={styles.container}>
        <View style={styles.lineitem}>
          <View style={styles.header}>
            <AppHeaderText>{I18n.t('calls')}</AppHeaderText>
          </View>
        </View>
        <VirtualizedList
          data={this.props.recent.data}
          extraData={this.props}
          keyExtractor={item => item.somekey}
          renderItem={(item) => this._renderItem(item, this.props.userid)}
          initialNumToRender="13"
          maxToRenderPerBatch="13"
          //ItemSeparatorComponent={this.renderSeparator}
          ListEmptyComponent={ () => {
            return (
              <View style={styles.centerScreen}>
                <View>
                  <AppText>{I18n.t('nocallsfound')}</AppText>
                </View>
              </View>
            )
          }}
          ListFooterComponent={ () => {
            return (
              <Text>Footer goes here</Text>
            )
          }}
          ListHeaderComponent={ () => {
            return (
              <Text>Header goes here</Text>
            )
          }}
          getItem={ (data, index) => {
            console.log('getItem', index);
            return {name: 'My Name', id: index, somekey: index+1000};
          }}
          getItemCount={ (data, index) => {
            //console.log('getItemCount');
            return 15;
          }}
          onEndReached={ (info) => {
          console.log('onEndReached, info=', info);
          }}
          onViewableItemsChanged={ (info) => {
            console.log('onViewableItemsChanged, info=', info);
          }}
          />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'flex-start',

    backgroundColor: 'whitesmoke',
  },
  header: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',

    borderColor: 'grey',
    borderBottomWidth: 1,
    height: 40,
  },
  lineitem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',

    backgroundColor: 'white',
    padding: 5,
  },
  centerScreen: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
    height: 300,
  }
});

const mapStateToProps = (state, props) => {
  return {
    recent: state.recentList.recent,
    userid: getUserId(state),
  };
};

const mapDispatchToProps = (dispatch, props) => {
  return {
    loadRecentCalls: () => dispatch(recentLoad(0)),
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(RecentList);
</code>```

So my main question is, how do I put all this together lazyloading my data?

答:
I solved this using redux-saga, which is so much better than redux-thunk.
Here's my code, lightly edited:

Actions and reducers:

```<code>const LOAD = 'LOAD';
const LOAD_OK = 'LOAD_OK';
const LOAD_ERROR = 'LOAD_ERROR';
const REFRESH_START = 'REFRESH_START';

export function mylistRefreshStart() {
  return {
    type: REFRESH_START,
    append: false,
  };
}

export function mylistLoad() {
  return {
    type: LOAD,
    append: true,
  };
}

// reducer
export const mylist = (state = { offset: 0, limit: 50, data: [], refreshing: true }, action) => {
  //console.log('mylist:', action);
  switch (action.type) {
    case REFRESH_START:
      return {
        ...state,
        refreshing: true,
        offset: 0,
        limit: 50,
      };

    case LOAD_OK:
      return {
        ...state,
        data: action.append ? state.data.concat(action.data) : action.data,
        refreshing: false,
        limit: action.data.length !== 50 ? 0 : 50,
      };

    case LOAD_ERROR:
      return {
        ...state,
        refreshing: false,
      };

    default:
      return state;
  }
};

// selector
export const getMyData = state => state.mylist;
</code>```

Actually loading the data:

```<code>function* mylistLoadData(action) {
  const mylist = yield select(getMyData);
  if (mylist.limit === 0) {
    //console.log('nothing left to fetch');
    return;
  }
  try {
    const response = yield call(fetch, 'https://www.example.com/api/mylist.php', {
      method: 'post',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        offset: action.append ? mylist.offset + mylist.data.length : mylist.offset,
        limit: mylist.limit,
      }),
    });
    if (response.status === 200) {
      result = yield call([response, 'json']);
      yield put({ type: LOAD_OK, data: result, append: action.append });
    } else {
      yield put({ type: LOAD_ERROR, error: response.status });
    }
  }
  catch(error) {
    console.log('error:', error);
    yield put({ type: LOAD_ERROR, error: error })
  }
}
</code>```

The saga that handles all processing:

```<code>export function* mylistSaga() {
  yield takeLatest(REFRESH_START, mylistLoadData);
  yield takeLatest(LOAD, mylistLoadData);
}
</code>```

Rendering:

```<code>class MyList extends PureComponent {
  componentDidMount = () => {
    this.props.refreshStart();
  };

  onRefresh = () => {
    this.props.refreshStart();
  };

  onEndReached = () => {
    this.props.mylistLoad();
  };

  render = () => {
    return (
      <View style={styles.container}>
        <FlatList
          data={this.props.mylist.data}
          extraData={this.props}
          keyExtractor={item => item.id}
          refreshing={this.props.recent.refreshing}
          renderItem={(item) => this._renderItem(item)}
          ListEmptyComponent={ () => {
            if (this.props.mylist.refreshing) return null;
            return (
              <View style={styles.centerScreen}>
                <View>
                  <Text>Nothing found</Text>
                </View>
              </View>
            )
            }
          }
          onRefresh={() => this.onRefresh()}
          onEndReached={() => this.onEndReached()}
          />
      </View>
    );
  }
}
</code>```

and connecting the actions:

```<code>const mapStateToProps = (state, props) => {
  return {
    mylist: state.mylist,
  };
};

const mapDispatchToProps = (dispatch, props) => {
  return {
    refreshStart: () => dispatch(recentRefreshStart()),
    mylistLoad: () => dispatch(mylistLoad()),
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(MyList);
</code>```

Basically I am just filling the data[] part in my store, and let FlatList doing the rendering of whatever is needed to be shown.

Body:
I have a remote API which generates a call history list. This can of course get quite long, so I need to lazyload it. From the RN docs I gather that the best choice would be a VirtualizedList. But the documentation is terribly lacking. For example, it talks about item keys. I can provide my own function for that (using date/time value), but the getItem prop is still asking for array indexes starting with 0. So what does RN use the keys for?

Another thing is, I am printing out the calls to getItem, and renderItem, and I see a really weird pattern (I have set both initialNumToRender and maxToRenderPerBatch to 13). This is all on app startup, no user interaction. Also my getItemCount returns 15:

VirtualizedList.render() call
getItem 13 times: 0-12
getItem 0
renderItem 13 times: 0-12
VirtualizedList.render() call
getItem 13 times: 0-12
getItem 12
getItem 0
renderItem 12 times: 0-12
getItem 0
getItem 12
VirtualizedList.render() call
getItem 13 times: 0-12
getItem 12
getItem 0
renderItem 12 times: 0-12
getItem 0
getItem 12
getItem 0
getItem 12
(10 more like the 2 repeating above)
getItem 0-12
getItem 1
getItem 2
getItem 3
getItem 4
getItem 5
getItem 6
getItem 9
getItem 10
getItem 12   (Skipping some items here???)
onViewableItemsChanged, info= Object {viewableItems: Array(9), changed: Array(9)}
getItem 0-14
getItem 0-14
renderItem 0-14
onEndReached, info= Object {distanceFromEnd: 93.5}  (what is that value 93.5????)
getItem 0-12
getItem 0-11
onViewableItemsChanged, info= Object {viewableItems: Array(12), changed: Array(5)}
getItem 0-14
onEndReached, info= Object {distanceFromEnd: 221???}
getItem 0-11
getItem 0-10
onViewableItemsChanged, info= Object {viewableItems: Array(11), changed: Array(1)}
getItem 0-14

Note that I haven't touched the screen yet. Now, when I scroll up a little I get the following events:

getItem 0-12
(repeats for around 20 times)
onViewableItemsChanged, info= Object {viewableItems: Array(12), changed: Array(1)}
getItem 0-12
(repeats for around 20 times)

It seems for each pixel I scroll, all items are retrieved.

For reference, here's my code:

import Expo from 'expo';
import React, { PureComponent } from 'react';
import { Platform, FlatList, VirtualizedList, View, StyleSheet, Text } from 'react-native';
import { combineReducers } from 'redux';
import { ListItem } from 'react-native-elements';
import { connect } from 'react-redux';
import I18n from '../i18n';
import { takeEvery, all, call, put, select } from 'redux-saga/effects';
import RecentRow from '../components/RecentRow';
import { getUserId } from './Settings';
import { AppText, AppHeaderText } from '../components/AppText';

// action types
const RECENT_LOAD = 'RECENT_LOAD';
const RECENT_LOAD_OK = 'RECENT_LOAD_OK';
const RECENT_LOAD_ERROR = 'RECENT_LOAD_ERROR';

// action functions
export function recentLoad(offset) {
  return {
    type: RECENT_LOAD,
    offset: offset,
  };
}

// reducers
function recent(state = { offset: 1, data: [] }, action) {
  //console.log('recent', action);
  switch (action.type) {
    case RECENT_LOAD:
      return {
        ...state,
        offset: action.offset
      };

    case RECENT_LOAD_OK:
      return {
        ...state,
        data: action.data,
      };
    default:
      return state;
  }
}

// combined reducer
export const recentList = combineReducers({
  recent: recent,
});

export const getRecent = state => state.recent;
export const getAccount = state => state.settings.account;

function* recentLoadData(action) {
  const account = yield select(getAccount);
  const URL = `https://www.xxxxx.xx/api/calls.php?userrname=${account.email}&offset=${action.offset}`;
  try {
    const response = yield call(fetch, URL);
    if (response.status === 200) {
      result = yield call([response, 'json']);
      yield put({ type: RECENT_LOAD_OK, data: result });
    } else {
      yield put({ type: RECENT_LOAD_ERROR, error: response.status });
    }
  }
  catch(error) {
    console.log('error:', error);
    yield put({ type: RECENT_LOAD_ERROR, error: error })
  }
}

function* recentLoadSaga() {
  yield takeEvery('RECENT_LOAD', recentLoadData);
}

export function* recentSaga() {
  yield all([
    recentLoadSaga(),
  ])
}

class RecentList extends PureComponent {
  componentDidMount() {
    this.props.loadRecentCalls();
  }

  _renderItem = (item, userid) => {
    console.log('_renderItem', item);
    //return <RecentRow row={item} userid={userid} />
    return <ListItem title={item.item.name + ' ' + item.item.id } />
  }

  renderSeparator = () => {
    return (
      <View
        style={{
          height: 1,
          width: "95%",
          backgroundColor: "#CED0CE",
          marginLeft: "5%"
        }}
      />
    );
  };

  render() {
    console.log('RecentList.render()');
    return (
      <View style={styles.container}>
        <View style={styles.lineitem}>
          <View style={styles.header}>
            <AppHeaderText>{I18n.t('calls')}</AppHeaderText>
          </View>
        </View>
        <VirtualizedList
          data={this.props.recent.data}
          extraData={this.props}
          keyExtractor={item => item.somekey}
          renderItem={(item) => this._renderItem(item, this.props.userid)}
          initialNumToRender="13"
          maxToRenderPerBatch="13"
          //ItemSeparatorComponent={this.renderSeparator}
          ListEmptyComponent={ () => {
            return (
              <View style={styles.centerScreen}>
                <View>
                  <AppText>{I18n.t('nocallsfound')}</AppText>
                </View>
              </View>
            )
          }}
          ListFooterComponent={ () => {
            return (
              <Text>Footer goes here</Text>
            )
          }}
          ListHeaderComponent={ () => {
            return (
              <Text>Header goes here</Text>
            )
          }}
          getItem={ (data, index) => {
            console.log('getItem', index);
            return {name: 'My Name', id: index, somekey: index+1000};
          }}
          getItemCount={ (data, index) => {
            //console.log('getItemCount');
            return 15;
          }}
          onEndReached={ (info) => {
          console.log('onEndReached, info=', info);
          }}
          onViewableItemsChanged={ (info) => {
            console.log('onViewableItemsChanged, info=', info);
          }}
          />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'flex-start',

    backgroundColor: 'whitesmoke',
  },
  header: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',

    borderColor: 'grey',
    borderBottomWidth: 1,
    height: 40,
  },
  lineitem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',

    backgroundColor: 'white',
    padding: 5,
  },
  centerScreen: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
    height: 300,
  }
});

const mapStateToProps = (state, props) => {
  return {
    recent: state.recentList.recent,
    userid: getUserId(state),
  };
};

const mapDispatchToProps = (dispatch, props) => {
  return {
    loadRecentCalls: () => dispatch(recentLoad(0)),
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(RecentList);

So my main question is, how do I put all this together lazyloading my data?

Body:
I solved this using redux-saga, which is so much better than redux-thunk.
Here's my code, lightly edited:

Actions and reducers:

const LOAD = 'LOAD';
const LOAD_OK = 'LOAD_OK';
const LOAD_ERROR = 'LOAD_ERROR';
const REFRESH_START = 'REFRESH_START';

export function mylistRefreshStart() {
  return {
    type: REFRESH_START,
    append: false,
  };
}

export function mylistLoad() {
  return {
    type: LOAD,
    append: true,
  };
}

// reducer
export const mylist = (state = { offset: 0, limit: 50, data: [], refreshing: true }, action) => {
  //console.log('mylist:', action);
  switch (action.type) {
    case REFRESH_START:
      return {
        ...state,
        refreshing: true,
        offset: 0,
        limit: 50,
      };

    case LOAD_OK:
      return {
        ...state,
        data: action.append ? state.data.concat(action.data) : action.data,
        refreshing: false,
        limit: action.data.length !== 50 ? 0 : 50,
      };

    case LOAD_ERROR:
      return {
        ...state,
        refreshing: false,
      };

    default:
      return state;
  }
};

// selector
export const getMyData = state => state.mylist;

Actually loading the data:

function* mylistLoadData(action) {
  const mylist = yield select(getMyData);
  if (mylist.limit === 0) {
    //console.log('nothing left to fetch');
    return;
  }
  try {
    const response = yield call(fetch, 'https://www.example.com/api/mylist.php', {
      method: 'post',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        offset: action.append ? mylist.offset + mylist.data.length : mylist.offset,
        limit: mylist.limit,
      }),
    });
    if (response.status === 200) {
      result = yield call([response, 'json']);
      yield put({ type: LOAD_OK, data: result, append: action.append });
    } else {
      yield put({ type: LOAD_ERROR, error: response.status });
    }
  }
  catch(error) {
    console.log('error:', error);
    yield put({ type: LOAD_ERROR, error: error })
  }
}

The saga that handles all processing:

export function* mylistSaga() {
  yield takeLatest(REFRESH_START, mylistLoadData);
  yield takeLatest(LOAD, mylistLoadData);
}

Rendering:

class MyList extends PureComponent {
  componentDidMount = () => {
    this.props.refreshStart();
  };

  onRefresh = () => {
    this.props.refreshStart();
  };

  onEndReached = () => {
    this.props.mylistLoad();
  };

  render = () => {
    return (
      <View style={styles.container}>
        <FlatList
          data={this.props.mylist.data}
          extraData={this.props}
          keyExtractor={item => item.id}
          refreshing={this.props.recent.refreshing}
          renderItem={(item) => this._renderItem(item)}
          ListEmptyComponent={ () => {
            if (this.props.mylist.refreshing) return null;
            return (
              <View style={styles.centerScreen}>
                <View>
                  <Text>Nothing found</Text>
                </View>
              </View>
            )
            }
          }
          onRefresh={() => this.onRefresh()}
          onEndReached={() => this.onEndReached()}
          />
      </View>
    );
  }
}

and connecting the actions:

const mapStateToProps = (state, props) => {
  return {
    mylist: state.mylist,
  };
};

const mapDispatchToProps = (dispatch, props) => {
  return {
    refreshStart: () => dispatch(recentRefreshStart()),
    mylistLoad: () => dispatch(mylistLoad()),
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(MyList);

Basically I am just filling the data[] part in my store, and let FlatList doing the rendering of whatever is needed to be shown.


问:
How to assign addEventListener as ON in JavaScript?
How to assign addEventListener as on
in pure JavaScript? Not jQuery.

// i can do this
// assigning document as d
// assigning querySelector as $

const d = document
const $ = x => d.querySelector(x)

//but how to do this

$('button').addEventListener('click',doSomething)

//to

$('button').on('click',doSomething)

//assiging addEventListener as on ```

答:
You could create your own on() function -

```<code>function on(object, event, callback) {
    object.addEventListener(event, callback);
}
</code>```

Or you could look into prototyping for object functions - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype

Body:
You could create your own on() function -

function on(object, event, callback) {
    object.addEventListener(event, callback);
}

Or you could look into prototyping for object functions - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype


问:
request not work, Error: Invalid protocol: 127.0.0.1:?
I am new to node.js, I use request send the post request.but I got a error!</p>

```<code>     request({
         method: 'POST',
         url: config.api + '/index',
         body: {
         name: "name"
        },
        json: true
      })

        throw er; // Unhandled 'error' event
        ^

         Error: Invalid protocol: 127.0.0.1:
</code>```

答: Your code is incorrect: follow the instructions on the NPM module page.</p>

Body:
I am new to node.js, I use request send the post request.but I got a error!

     request({
         method: 'POST',
         url: config.api + '/index',
         body: {
         name: "name"
        },
        json: true
      })

        throw er; // Unhandled 'error' event
        ^

         Error: Invalid protocol: 127.0.0.1:


问:
Calculating Outdegree and Indegree of Adjacency list

Question

Calculate time complexity in calculating Outdegree and Indegree of Adjacency list.

My Approach/Doubt

Let Adj[] be an array of size V where V=No. of vertices  in a directed graph
for representing adjacency list.

I know that ,

Outdegree of vertex u (u belongs to V) is actually the length of Adj[u]

and

Indegree of vertex u (u belongs to V) is actually the count of u in list Adj.

In both the cases , i think the time complexity should be theta (V*E)

Where V=no. of vertices

```<code>  E=no. of edges
</code>```

because for calculating outdegree,we scan all vertices and under each vertices we scan all the edges of that vertices.

Then why it is Thrta (V+E)

Please correct me where i am wrong?

Thanks!

答:
we can allocate an array arr[] of size |V| and initialize its entries to zero. Then we only need to scan the lists in Adj once, incrementing arr [u] when we see u in the lists.

The values in arr[] will be the out-degrees of every vertex. This can be done in Θ (|V| + |E|) time with Θ (|V|) additional storage.

Body:
Question

Calculate time complexity in calculating Outdegree and Indegree of Adjacency list.

My Approach/Doubt

Let Adj[] be an array of size V where V=No. of vertices  in a directed graph
for representing adjacency list.

I know that ,

Outdegree of vertex u (u belongs to V) is actually the length of Adj[u]

and

Indegree of vertex u (u belongs to V) is actually the count of u in list Adj.

In both the cases , i think the time complexity should be theta (V*E)

Where V=no. of vertices

  E=no. of edges

because for calculating outdegree,we scan all vertices and under each vertices we scan all the edges of that vertices.

Then why it is Thrta (V+E)

Please correct me where i am wrong?

Thanks!


问:
How to change server time?
I need to change server time from asp.net page. Is it possible?</p>

答:
Possible or not, it's a bad idea.  And the only way I can think of allowing this is if the user account the app pool is executing under has some serious access rights to the machine; which is also a very bad idea.

Servers should be sync'd with a time server.  This is normally controlled at the OS level.

All sorts of funky things can happen once one server in a mix gets out of an acceptable date range.

Which leads us to the question: Why?

UPDATE

You could pinvoke SetSystemTime.  This will require the user the app pool is running under to have the SeSystemTimePrivilege.  More information and an example of pinvoking here: http://bytes.com/topic/c-sharp/answers/274594-how-set-system-date-c

Again, this is a Bad Idea(tm).

Title: How to change server time?


问:
Zed Attack Proxy automated scanning of WebApi with OAuth
I have configured ZAP 2.6 so that it is acting as a proxy for requests from an Android app to a web service over HTTPS. The authentication mechanism is OAuth 2, and so in my login response I get an access token which is then sent in all subsequent request headers as follows

```<code>Authorization: Bearer my_long_and_encoded_access_token
</code>```

Is it possible to get ZAP to recognise this token and use it in tests initiated from the ZAP UI?

I have looked at Automate OAuth access token for Zed Attack Proxy Scans but don't believe this covers my situation.

Thanks.

答:
Yes, you can create a script which extracts this token and then uses it in future requests.
If you need help with such a script then asking on the ZAP User Group might be a better option than asking here ;)</p>

Body:
I have configured ZAP 2.6 so that it is acting as a proxy for requests from an Android app to a web service over HTTPS. The authentication mechanism is OAuth 2, and so in my login response I get an access token which is then sent in all subsequent request headers as follows

Authorization: Bearer my_long_and_encoded_access_token

Is it possible to get ZAP to recognise this token and use it in tests initiated from the ZAP UI?

I have looked at Automate OAuth access token for Zed Attack Proxy Scans but don't believe this covers my situation.

Thanks.


问:
extending model : Access parent attribute from the child
have to accessing parent attribute from child

after instanciate objectTwo, $object_two->some_objectone_field get null value instead of expected value

below both objects structure :

object one

```<code><?php namespace Username\Plugin\Models;
use Model;
class ObjectOne extends Model
{
    use \October\Rain\Database\Traits\Validation;
    public $rules = [
     ....
    ];

    public $table = 'username_plugin_objectone';

    public function __construct()
    {
        parent::__construct();
    }

}
</code>```

object two

```<code><?php namespace Username\Plugin\Models;

use Username\Plugin\Models\ObjectOne;

class ObjectTwo extends ObjectOne
{

    public $rules = [
     ....
    ];

    public $table = 'username_plugin_objecttwo';

    public function __construct()
    {
        parent::__construct();
    }

}
</code>```

database tables

```<code>username_plugin_objectone table :
id
some_objectone_field
...

username_plugin_objecttwo table:
id
objectone_id
some_objecttwo_field
...
</code>```

what am i going wrong ? thanks by advance

答: ok, things are more clear, i can't access parent properties from database because the parent $table property is overload by child $table property ...</p>

Body:
have to accessing parent attribute from child

after instanciate objectTwo, $object_two->some_objectone_field get null value instead of expected value

below both objects structure :

object one

<?php namespace Username\Plugin\Models;
use Model;
class ObjectOne extends Model
{
    use \October\Rain\Database\Traits\Validation;
    public $rules = [
     ....
    ];

    public $table = 'username_plugin_objectone';

    public function __construct()
    {
        parent::__construct();
    }

}

object two

<?php namespace Username\Plugin\Models;

use Username\Plugin\Models\ObjectOne;

class ObjectTwo extends ObjectOne
{

    public $rules = [
     ....
    ];

    public $table = 'username_plugin_objecttwo';

    public function __construct()
    {
        parent::__construct();
    }

}

database tables

username_plugin_objectone table :
id
some_objectone_field
...

username_plugin_objecttwo table:
id
objectone_id
some_objecttwo_field
...

what am i going wrong ? thanks by advance


问:
Material-UI's Tabs integration with react router 4?
The new react-router syntax uses the Link component to move around the routes. But how could this be integrated with material-ui?

In my case, I'm using tabs as the main navigation system, So in theory I should have something like this:

const TabLink = ({ onClick, href, isActive, label }) =>
  <Tab
    label={label}
    onActive={onClick}
  />

export default class NavBar extends React.Component {
  render () {
    return (
      <Tabs>
        <Link to="/">{params => <TabLink label="Home" {...params}/>}</Link>
        <Link to="/shop">{params => <TabLink label="shop" {...params}/>}</Link>
        <Link to="/gallery">{params => <TabLink label="gallery" {...params}/>}</Link>
      </Tabs>
    )
  }
}
```

But when it renders, material-ui throws an error that the child of Tabs must be a Tab component. What could be the way to proceed? How do I manage the isActive prop for the tab?

Thanks in advance

答:
The error you are seeing from material-ui is because it expects to have a <Tab> component rendered as direct child of <Tabs> component.

Now, here is a way that I've found to integrate the link into the <Tabs> component without loosing the styles:

```<code>import React, {Component} from 'react';
import {Tabs, Tab} from 'material-ui/Tabs';
import {Link} from 'react-router-dom';

export default class MyComponent extends Component {
    render() {
        const {location} = this.props;
        const {pathname} = location;

        return (
            <Tabs value={pathname}>
                <Tab label="First tab" containerElement={<Link to="/my-firs-tab-view" />} value="/my-firs-tab-view">
                    {/* insert your component to be rendered inside the tab here */}
                </Tab>
                <Tab label="Second tab" containerElement={<Link to="/my-second-tab-view" />} value="/my-second-tab-view">
                    {/* insert your component to be rendered inside the tab here */}
                </Tab>
            </Tabs>
        );
    }
}
</code>```

To manage the 'active' property for the tabs, you can use the value property in the <Tabs> component and you also need to have a value property for each tab, so when both of the properties match, it will apply the active style to that tab.

Body:
The new react-router syntax uses the Link component to move around the routes. But how could this be integrated with material-ui?

In my case, I'm using tabs as the main navigation system, So in theory I should have something like this:

const TabLink = ({ onClick, href, isActive, label }) =>
  <Tab
    label={label}
    onActive={onClick}
  />

export default class NavBar extends React.Component {
  render () {
    return (
      <Tabs>
        <Link to="/">{params => <TabLink label="Home" {...params}/>}</Link>
        <Link to="/shop">{params => <TabLink label="shop" {...params}/>}</Link>
        <Link to="/gallery">{params => <TabLink label="gallery" {...params}/>}</Link>
      </Tabs>
    )
  }
}

But when it renders, material-ui throws an error that the child of Tabs must be a Tab component. What could be the way to proceed? How do I manage the isActive prop for the tab?

Thanks in advance

Body:
The error you are seeing from material-ui is because it expects to have a <Tab> component rendered as direct child of <Tabs> component.

Now, here is a way that I've found to integrate the link into the <Tabs> component without loosing the styles:

import React, {Component} from 'react';
import {Tabs, Tab} from 'material-ui/Tabs';
import {Link} from 'react-router-dom';

export default class MyComponent extends Component {
    render() {
        const {location} = this.props;
        const {pathname} = location;

        return (
            <Tabs value={pathname}>
                <Tab label="First tab" containerElement={<Link to="/my-firs-tab-view" />} value="/my-firs-tab-view">
                    {/* insert your component to be rendered inside the tab here */}
                </Tab>
                <Tab label="Second tab" containerElement={<Link to="/my-second-tab-view" />} value="/my-second-tab-view">
                    {/* insert your component to be rendered inside the tab here */}
                </Tab>
            </Tabs>
        );
    }
}

To manage the 'active' property for the tabs, you can use the value property in the <Tabs> component and you also need to have a value property for each tab, so when both of the properties match, it will apply the active style to that tab.


问:
Emulator to test APK
Is there any emulator, which tests the APK, for all kind of android devices. There is one called YouWave, but it is not good.

What I want is, one emulator, when the APK file is loaded, performs automatic testing like UI interface, performance, etc, and provide a report for the same. Saying that for this combination your APK does not works correctly.

答: to test online, use appetize and upload your apk. very easy. they will send a link to test.</p>

Title: Emulator to test APK