问:
Adding consecutive x values to a list
Suppose I have a list with items [123, 124, 125, ... 9820] and from that list I want to append to a second list with a string of every 8 items separated by a space up until the end. For example the list would have:

["123 124 125 126 127 128 129 130", "131, 132, 133, 134, 135, 136, 137, 138",..] etc.

What is the best way to do this in python? I have tried a naive solution of looping from 123 to 9820 but this takes way too much runtime and times out some of my simple tests I have set up. Are there any functions that would be useful to me?

答:
Collect the elements into chunks of length 8 and use join(). Here's an example using an adapted recipe from itertools:

```<code>from itertools import zip_longest

lst = [str(x) for x in range(123, 9821)]

def grouper(iterable, n, fillvalue=""):
    "Collect data into fixed-length chunks or blocks"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

lst2 = [" ".join(x) for x in grouper(lst, 8)]
</code>```

Title: Adding consecutive x values to a list

Body:
Collect the elements into chunks of length 8 and use join(). Here's an example using an adapted recipe from itertools:

from itertools import zip_longest

lst = [str(x) for x in range(123, 9821)]

def grouper(iterable, n, fillvalue=""):
    "Collect data into fixed-length chunks or blocks"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

lst2 = [" ".join(x) for x in grouper(lst, 8)]


来源: stackexchange

问:
Results duplicating
My code below is duplicating my department name results and I don't know why. I need to display the name of the department, job id for the employees who work there and their salary. Plus I need to figure out if department_id or job_id was used in the CUBE expression.

```<code>SELECT d.department_name AS "Name",
       e.job_id AS "Job ID",
       SUM(e.salary) AS "salary",
       DECODE(GROUPING(d.department_id),1, 'Yes', 'No') AS "Department Used",
       DECODE(GROUPING(e.job_id), 1, 'Yes', 'No') AS "Job used"
FROM employees e
    full OUTER JOIN departments d
    ON (e.department_id = d.department_id)
GROUP BY CUBE(d.department_name, e.job_id, d.department_id)
ORDER BY d.department_name;
</code>```

答:
because cube generates subtotals for all combinations. in your example, combination works like that:

1) department_name - job_id - department_id

2) department_name - job_id

3) department_name - department_id

4) department_name

5) job_id - department_id

6) job_id

7) department_id

8) (total)

that's why you getting duplicate values.

I don't know what you exactly need, but I think you need something like that:

```<code>  select d.department_name as "Name",
         e.job_id as "Job ID",
         sum(e.salary) as "Salary",
         decode(grouping(d.department_id), 1, 'Yes', 'No') as "Department Used",
         decode(grouping(e.job_id), 1, 'Yes', 'No') as "Job Used"
    from hr.employees e
    full outer join hr.departments d
      on (e.department_id = d.department_id)
   group by cube(e.job_id), d.department_name, d.department_id
   order by d.department_name;
</code>```

ContentLicense: CC BY-SA 3.0

Title: Results duplicating

Body:
My code below is duplicating my department name results and I don't know why. I need to display the name of the department, job id for the employees who work there and their salary. Plus I need to figure out if department_id or job_id was used in the CUBE expression.

SELECT d.department_name AS "Name",
       e.job_id AS "Job ID",
       SUM(e.salary) AS "salary",
       DECODE(GROUPING(d.department_id),1, 'Yes', 'No') AS "Department Used",
       DECODE(GROUPING(e.job_id), 1, 'Yes', 'No') AS "Job used"
FROM employees e
    full OUTER JOIN departments d
    ON (e.department_id = d.department_id)
GROUP BY CUBE(d.department_name, e.job_id, d.department_id)
ORDER BY d.department_name;

Body:
because cube generates subtotals for all combinations. in your example, combination works like that:

1) department_name - job_id - department_id

2) department_name - job_id

3) department_name - department_id

4) department_name

5) job_id - department_id

6) job_id

7) department_id

8) (total)

that's why you getting duplicate values.

I don't know what you exactly need, but I think you need something like that:

  select d.department_name as "Name",
         e.job_id as "Job ID",
         sum(e.salary) as "Salary",
         decode(grouping(d.department_id), 1, 'Yes', 'No') as "Department Used",
         decode(grouping(e.job_id), 1, 'Yes', 'No') as "Job Used"
    from hr.employees e
    full outer join hr.departments d
      on (e.department_id = d.department_id)
   group by cube(e.job_id), d.department_name, d.department_id
   order by d.department_name;


问:
Position of a point in a circle
Hello again first part is working like a charm, thank you everyone.

But I've another question...

As I've no interface, is there a way to do the same thing with out not knowing the radius of the circle?

Should have refresh the page CodeMonkey solution is exactly what I was looking for...

Thank you again.

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

First I'm not a developer, I'm a simple woodworker that left school far too early...

I'm trying to make one of my tool to work with an autonomous robot.
I made them communicate by reading a lot of tutorials.

But I have one problem I cant figure out.

Robot expect position of the tool as (X,Y) but tool's output is (A,B,C)
A is the distance from tool to north
B distance to east
C distance at 120 degree clockwise from east axe

the border is a circle, radius may change, and may or may not be something I know.

I've been on that for 1 month, and I can't find a way to transform those value into the position.

I made a test with 3 nails on a circle I draw on wood, and if I have the distance there is only one position possible, so I guess its possible.
But how?

Also, if someone as an answer I'd love pseudo code not code so I can practice.

If there is a tool to make a drawing I can use to make it clearer can you point it out to me?

Thank you.

hope it helps :

X, Y are coordinate from center, Da,Db, Dc are known.

Trying to make it more clear (sorry its so clear in my head).

X,Y are the coordinate of the point where is the tool (P).
Center is at 0,0

A is the point where vertical line cut the circle from P, with Da distance P to A;

B is the point where horizontal line cuts the circle fom P, with Db distance P to B.

C is the point where the line at 120 clockwise from horizontal cuts the circle from P, with Dc distance P to C.

Output from tool is an array of int (unit mm): A=123, B=114, C=89
Those are the only informations I have

thanks for all the ideas I'll try them at home later,
Hope it works :)

答:
Assume you know X and Y. R is the radius of the circle.

```<code>|(X, Y + Da)| = R
|(X + Db, Y)| = R
|(X - cos(pi/3) * Dc, Y - cos(pi/6) * Dc)| = R
</code>```

Assuming we don't know the radius R. We can still say

```<code>|(X, Y + Da)|^2 = |(X + Db, Y)|^2
=> X^2 + (Y+Da)^2 = (X+Db)^2 + Y^2
=> 2YDa + Da^2 = 2XDb + Db^2 (I)
</code>```

and denoting cos(pi/3)*Dc as c1 and cos(pi/6)*Dc as c2:

```<code>|(X, Y + Da)|^2 = |(X - c1, Y - c2)|^2
=> X^2 + Y^2 + 2YDa + Da^2 = X^2 - 2Xc1 + c1^2 + Y^2 - 2Yc2 + c2^2
=> 2YDa + Da^2 = - 2Xc1 + c1^2 - 2Yc2 + c2^2
=> Y = (-2Xc1 + c1^2 + c2^2 - Da^2) / 2(c2+Da) (II)
</code>```

Putting (II) back in the equation (I) we get:

```<code>=> (-2Xc1 + c1^2 + c2^2 - Da^2) Da / (c2+Da) + Da^2 = 2XDb + Db^2
=> (-2Xc1 + c1^2 + c2^2 - Da^2) Da + Da^2 * (c2+Da) = 2XDb(c2+Da) + Db^2 * (c2+Da)
=> (-2Xc1 + c1^2 + c2^2) Da + Da^2 * c2 = 2XDb(c2+Da) + Db^2 * (c2+Da)

=> X = ((c1^2 + c2^2) Da + Da^2 * c2 - Db^2 * (c2+Da)) / (2Dbc2 + 2Db*Da + 2Dac1) (III)
</code>```

Knowing X you can get Y by calculating (II).

You can also make some simplifications, e.g. c1^2 + c2^2 = Dc^2

Putting this into Python (almost Pseudocode):

```<code>import math

def GetXYR(Da, Db, Dc):
    c1 = math.cos(math.pi/3) * Dc
    c2 = math.cos(math.pi/6) * Dc

    X = ((c1**2 + c2**2) * Da + Da**2 * c2 - Db * Db * (c2 + Da)) / (2 * Db * c2 + 2 * Db * Da + 2 * Da * c1)
    Y = (-2*X*c1 + c1**2 + c2**2 - Da**2) / (2*(c2+Da))
    R = math.sqrt(X**2 + (Y+Da)**2)
    R2 = math.sqrt(Y**2 + (X+Db)**2)
    R3 = math.sqrt((X - math.cos(math.pi/3) * Dc)**2 + (Y - math.cos(math.pi/6) * Dc)**2)
    return (X, Y, R, R2, R3)

(X, Y, R, R2, R3) = GetXYR(123.0, 114.0, 89.0)

print((X, Y, R, R2, R3))
</code>```

I get the result (X, Y, R, R2, R3) = (-8.129166703588021, -16.205081335032794, 107.1038654949096, 107.10386549490958, 107.1038654949096)

Which seems reasonable if both Da and Db are longer than Dc, then both coordinates are probably negative.

I calculated the Radius from three equations to cross check whether my calculation makes sense. It seems to fulfill all three equations we set up in the beginning.

Title: Position of a point in a circle

Body:
Assume you know X and Y. R is the radius of the circle.

|(X, Y + Da)| = R
|(X + Db, Y)| = R
|(X - cos(pi/3) * Dc, Y - cos(pi/6) * Dc)| = R

Assuming we don't know the radius R. We can still say

|(X, Y + Da)|^2 = |(X + Db, Y)|^2
=> X^2 + (Y+Da)^2 = (X+Db)^2 + Y^2
=> 2YDa + Da^2 = 2XDb + Db^2 (I)

and denoting cos(pi/3)*Dc as c1 and cos(pi/6)*Dc as c2:

|(X, Y + Da)|^2 = |(X - c1, Y - c2)|^2
=> X^2 + Y^2 + 2YDa + Da^2 = X^2 - 2Xc1 + c1^2 + Y^2 - 2Yc2 + c2^2
=> 2YDa + Da^2 = - 2Xc1 + c1^2 - 2Yc2 + c2^2
=> Y = (-2Xc1 + c1^2 + c2^2 - Da^2) / 2(c2+Da) (II)

Putting (II) back in the equation (I) we get:

=> (-2Xc1 + c1^2 + c2^2 - Da^2) Da / (c2+Da) + Da^2 = 2XDb + Db^2
=> (-2Xc1 + c1^2 + c2^2 - Da^2) Da + Da^2 * (c2+Da) = 2XDb(c2+Da) + Db^2 * (c2+Da)
=> (-2Xc1 + c1^2 + c2^2) Da + Da^2 * c2 = 2XDb(c2+Da) + Db^2 * (c2+Da)

=> X = ((c1^2 + c2^2) Da + Da^2 * c2 - Db^2 * (c2+Da)) / (2Dbc2 + 2Db*Da + 2Dac1) (III)

Knowing X you can get Y by calculating (II).

You can also make some simplifications, e.g. c1^2 + c2^2 = Dc^2

Putting this into Python (almost Pseudocode):

import math

def GetXYR(Da, Db, Dc):
    c1 = math.cos(math.pi/3) * Dc
    c2 = math.cos(math.pi/6) * Dc

    X = ((c1**2 + c2**2) * Da + Da**2 * c2 - Db * Db * (c2 + Da)) / (2 * Db * c2 + 2 * Db * Da + 2 * Da * c1)
    Y = (-2*X*c1 + c1**2 + c2**2 - Da**2) / (2*(c2+Da))
    R = math.sqrt(X**2 + (Y+Da)**2)
    R2 = math.sqrt(Y**2 + (X+Db)**2)
    R3 = math.sqrt((X - math.cos(math.pi/3) * Dc)**2 + (Y - math.cos(math.pi/6) * Dc)**2)
    return (X, Y, R, R2, R3)

(X, Y, R, R2, R3) = GetXYR(123.0, 114.0, 89.0)

print((X, Y, R, R2, R3))

I get the result (X, Y, R, R2, R3) = (-8.129166703588021, -16.205081335032794, 107.1038654949096, 107.10386549490958, 107.1038654949096)

Which seems reasonable if both Da and Db are longer than Dc, then both coordinates are probably negative.

I calculated the Radius from three equations to cross check whether my calculation makes sense. It seems to fulfill all three equations we set up in the beginning.


问:
Getting error in Entity Framework at SaveChanges
I'm getting this error:

An exception of type
  'System.Data.Entity.Infrastructure.DbUpdateConcurrencyException'
  occurred in EntityFramework.dll but was not handled in user code

Additional information: Store update, insert, or delete statement
  affected an unexpected number of rows (0). Entities may have been
  modified or deleted since entities were loaded. Refresh
  ObjectStateManager entries.

```<code>dbContext.Productos.Add(producto);
dbContext.Entry(producto).State = System.Data.Entity.EntityState.Modified;
dbContext.SaveChanges();
 }
</code>```

Any idea about what is wrong here?

Thanks.

My stack trace is:

```<code>[OptimisticConcurrencyException: Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.]
   System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.ValidateRowsAffected(Int64 rowsAffected, UpdateCommand source) +232
   System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update() +493
   System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.<Update>b__2(UpdateTranslator ut) +32
   System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update(T noChangesResult, Func`2 updateFunction) +272
   System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update() +143
   System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__35() +34
   System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction(Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) +448
   System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction) +219
   System.Data.Entity.Core.Objects.<>c__DisplayClass2a.<SaveChangesInternal>b__27() +71
   System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func`1 operation) +213
   System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction) +408
   System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options) +39
   System.Data.Entity.Internal.InternalContext.SaveChanges() +320

[DbUpdateConcurrencyException: Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.]
   System.Data.Entity.Internal.InternalContext.SaveChanges() +366
   System.Data.Entity.Internal.LazyInternalContext.SaveChanges() +56
   System.Data.Entity.DbContext.SaveChanges() +52
   Clase5.Data.ProductoRepositorio.Insertar(Producto producto) in c:\Users\Juan\Downloads\Clase_5_-_Codigo_fuente\Clase5\Clase4\Data\ProductoRepositorio.cs:27
   Clase5.Controllers.ProductoController.TresCrearProducto(Producto producto) in c:\Users\Juan\Downloads\Clase_5_-_Codigo_fuente\Clase5\Clase4\Controllers\ProductoController.cs:43
   lambda_method(Closure , ControllerBase , Object[] ) +180
   System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +211
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
   System.Web.Mvc.Async.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41() +28
   System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +10
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +48
   System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +57
   System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +223
   System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +48
   System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +24
   System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +102
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +43
   System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +57
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +47
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
   System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +25
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +47
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9657896
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
</code>```

答: Have you set AutoDetectChangesEnabled to false? If you have done that,please call DetectChanges manually before  SaveChanges, don't change the Entry State directly.</p>

Body:
I'm getting this error:

An exception of type
  'System.Data.Entity.Infrastructure.DbUpdateConcurrencyException'
  occurred in EntityFramework.dll but was not handled in user code

Additional information: Store update, insert, or delete statement
  affected an unexpected number of rows (0). Entities may have been
  modified or deleted since entities were loaded. Refresh
  ObjectStateManager entries.

dbContext.Productos.Add(producto);
dbContext.Entry(producto).State = System.Data.Entity.EntityState.Modified;
dbContext.SaveChanges();
 }

Any idea about what is wrong here?

Thanks.

My stack trace is:

[OptimisticConcurrencyException: Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.]
   System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.ValidateRowsAffected(Int64 rowsAffected, UpdateCommand source) +232
   System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update() +493
   System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.<Update>b__2(UpdateTranslator ut) +32
   System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update(T noChangesResult, Func`2 updateFunction) +272
   System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update() +143
   System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__35() +34
   System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction(Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) +448
   System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction) +219
   System.Data.Entity.Core.Objects.<>c__DisplayClass2a.<SaveChangesInternal>b__27() +71
   System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func`1 operation) +213
   System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction) +408
   System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options) +39
   System.Data.Entity.Internal.InternalContext.SaveChanges() +320

[DbUpdateConcurrencyException: Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.]
   System.Data.Entity.Internal.InternalContext.SaveChanges() +366
   System.Data.Entity.Internal.LazyInternalContext.SaveChanges() +56
   System.Data.Entity.DbContext.SaveChanges() +52
   Clase5.Data.ProductoRepositorio.Insertar(Producto producto) in c:\Users\Juan\Downloads\Clase_5_-_Codigo_fuente\Clase5\Clase4\Data\ProductoRepositorio.cs:27
   Clase5.Controllers.ProductoController.TresCrearProducto(Producto producto) in c:\Users\Juan\Downloads\Clase_5_-_Codigo_fuente\Clase5\Clase4\Controllers\ProductoController.cs:43
   lambda_method(Closure , ControllerBase , Object[] ) +180
   System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +211
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
   System.Web.Mvc.Async.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41() +28
   System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +10
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +48
   System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +57
   System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +223
   System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +48
   System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +24
   System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +102
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +43
   System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +57
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +47
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
   System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +25
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +47
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9657896
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155


问:
storedProcedure.registerStoredProcedureParameter with out Parameter ref cursor with Jpa Eclipse Link
I am new to Jpa i want to execute Procedure

I have Code as Followes

```<code>private static final String PERSISTENCE_UNIT_NAME = "todos";
private static EntityManagerFactory factory;

public static void main(String[] args) {

    factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
    EntityManager em = factory.createEntityManager();

    em.getTransaction().begin();
    StoredProcedureQuery storedProcedure = em.createStoredProcedureQuery("TEST1");
    // set parameters
    storedProcedure.registerStoredProcedureParameter("P_CODE", String.class, ParameterMode.IN);
    storedProcedure.registerStoredProcedureParameter("P_DATE", String.class, ParameterMode.IN);
    storedProcedure.registerStoredProcedureParameter("P_CURSOR", ResultSet.class, ParameterMode.REF_CURSOR );
    storedProcedure.setParameter("P_CODE", "5110" );
    storedProcedure.setParameter("P_DATE", "01/01/2015" );
    // execute SP
    storedProcedure.execute();
    // get result
    Object obj =storedProcedure.getOutputParameterValue("tax");

    em.getTransaction().commit();
    em.close();
</code>```

}

But this is giving an Exception for register out parameter Please tell what we Have to pass
I am using Jpa EclipseLink Implimentation
Exception in thread "main" javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.6.4.v20160829-44060b6): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: ORA-06550: line 1, column 7:
PLS-00306: wrong number or types of arguments in call to 'TEST1'
ORA-06550: line 1, column 7: PL/SQL: Statement ignored  Error Code: 6550
Call: BEGIN TEST1(P_CODE=>?, P_DATE=>?, P_CURSOR=>?); END;  bind => [3 parameters bound] Query: ResultSetMappingQuery()

答:
I think your Store stored Procedure return list, So you do some changes in your code.

Old Code

```<code> storedProcedure.registerStoredProcedureParameter("P_CURSOR", ResultSet.class, ParameterMode.REF_CURSOR );

Object obj =storedProcedure.getOutputParameterValue("tax");
</code>```

New Code

```<code>    storedProcedure.registerStoredProcedureParameter("P_CURSOR",void.class,ParameterMode.REF_CURSOR);

Object obj =storedProcedure.getResultList();
</code>```

Your all data store in obj.

Body:
I am new to Jpa i want to execute Procedure

I have Code as Followes

private static final String PERSISTENCE_UNIT_NAME = "todos";
private static EntityManagerFactory factory;

public static void main(String[] args) {

    factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
    EntityManager em = factory.createEntityManager();

    em.getTransaction().begin();
    StoredProcedureQuery storedProcedure = em.createStoredProcedureQuery("TEST1");
    // set parameters
    storedProcedure.registerStoredProcedureParameter("P_CODE", String.class, ParameterMode.IN);
    storedProcedure.registerStoredProcedureParameter("P_DATE", String.class, ParameterMode.IN);
    storedProcedure.registerStoredProcedureParameter("P_CURSOR", ResultSet.class, ParameterMode.REF_CURSOR );
    storedProcedure.setParameter("P_CODE", "5110" );
    storedProcedure.setParameter("P_DATE", "01/01/2015" );
    // execute SP
    storedProcedure.execute();
    // get result
    Object obj =storedProcedure.getOutputParameterValue("tax");

    em.getTransaction().commit();
    em.close();

}

But this is giving an Exception for register out parameter Please tell what we Have to pass
I am using Jpa EclipseLink Implimentation
Exception in thread "main" javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.6.4.v20160829-44060b6): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: ORA-06550: line 1, column 7:
PLS-00306: wrong number or types of arguments in call to 'TEST1'
ORA-06550: line 1, column 7: PL/SQL: Statement ignored  Error Code: 6550
Call: BEGIN TEST1(P_CODE=>?, P_DATE=>?, P_CURSOR=>?); END;  bind => [3 parameters bound] Query: ResultSetMappingQuery()

Body:
I think your Store stored Procedure return list, So you do some changes in your code.

Old Code

 storedProcedure.registerStoredProcedureParameter("P_CURSOR", ResultSet.class, ParameterMode.REF_CURSOR );

Object obj =storedProcedure.getOutputParameterValue("tax");

New Code

    storedProcedure.registerStoredProcedureParameter("P_CURSOR",void.class,ParameterMode.REF_CURSOR);

Object obj =storedProcedure.getResultList();

Your all data store in obj.


问:
Converting string to byte array in C# (CSV)
I wrote a function to convert byte[] to string, and I add ";" after each byte. Now I want to convert this string to byte[] by splitting the string (similar to a CSV string).

```<code>public string ByteArrayToString(byte[] byteArray,string s)
{
    for (int i = 0; i < byteArray.Length; i++)
    {
        s += byteArray[i].ToString() + ";";
    }
    s = s.Substring(0, s.Length - 1);
    return s;
}
</code>```

How could I write a function to convert this string to that byte array again?

答:
```<code>str.Split(new char[]{';'},
          StringSplitOptions.RemoveEmptyEntries).Select(s => byte.Parse(s)).ToArray();
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I wrote a function to convert byte[] to string, and I add ";" after each byte. Now I want to convert this string to byte[] by splitting the string (similar to a CSV string).

public string ByteArrayToString(byte[] byteArray,string s)
{
    for (int i = 0; i < byteArray.Length; i++)
    {
        s += byteArray[i].ToString() + ";";
    }
    s = s.Substring(0, s.Length - 1);
    return s;
}

How could I write a function to convert this string to that byte array again?


问:
How to get the array value and in structurized using Mongoose?
I am using MeanStack AngularJS. I stored the values into MongoDB like this:

Data format

```<code>"RoleName" : "Verify",
"IsActive" : true,
"UIList" :
    {
        "UiName": "One",
        "View" : false,
        "Edit" : false
    },
    {
       "UiName": "Two",
        "View" : false,
        "Edit" : false
    },
    {
        "UiName": "Three",
        "View" : false,
        "Edit" : false
    },
    {
        "UiName": "Four",
        "View" : false,
        "Edit" : false
    },
    {
        "UiName": "Five",
        "View" : false,
        "Edit" : false
    }
</code>```

Contoller

```<code>$http.get('/Manage_Datashow').success(function (response) {
    $scope.Manage_Roleser = response;
});
</code>```

Server

```<code>app.get('/Manage_Datashow', function (req, res) {
    db.New_Role.find(function (err, docs) {
        console.log(docs);
        res.json(docs);
    });
});
</code>```

Here I attached my sample code. I want to bind the values in list using ng-repeat.

My code:

```<code><ul ng-repeat=Manage_Rolese in Manage_Roleser >
  <li>{{Manage_Rolese.UIList.UiName}}</li>
  <li>{{Manage_Rolese.UIList.View}}</li>
  <li>{{Manage_Rolese.UIList.Edit}}</li>
</ul>
</code>```

Example:

I need output like this.

答:
Try this

     UiName

     View

     Edit

     {{mgr.UiName}}

    |{{mgr.View}}

     {{mgr.View}}

```

Body:
I am using MeanStack AngularJS. I stored the values into MongoDB like this:

Data format

"RoleName" : "Verify",
"IsActive" : true,
"UIList" :
    {
        "UiName": "One",
        "View" : false,
        "Edit" : false
    },
    {
       "UiName": "Two",
        "View" : false,
        "Edit" : false
    },
    {
        "UiName": "Three",
        "View" : false,
        "Edit" : false
    },
    {
        "UiName": "Four",
        "View" : false,
        "Edit" : false
    },
    {
        "UiName": "Five",
        "View" : false,
        "Edit" : false
    }

Contoller

$http.get('/Manage_Datashow').success(function (response) {
    $scope.Manage_Roleser = response;
});

Server

app.get('/Manage_Datashow', function (req, res) {
    db.New_Role.find(function (err, docs) {
        console.log(docs);
        res.json(docs);
    });
});

Here I attached my sample code. I want to bind the values in list using ng-repeat.

My code:

{{Manage_Rolese.UIList.UiName}}

{{Manage_Rolese.UIList.View}}

{{Manage_Rolese.UIList.Edit}}

Example:

I need output like this.

Body:
Try this

<html>
<body>
 <div Class="container" ng-app="myapp" ng-controller="namesctrl">

  <table>
   <thead>
    <th>
     UiName
    </th>
    <th>
     View
    </th>
    <th>
     Edit
    </th>
   </thead>
   <tr ng-repeat="mgr in Manage_Roleser.UIList">
    <td>
     {{mgr.UiName}}
    </td>
    <td>
    |{{mgr.View}}
    </td>
    <td>
     {{mgr.View}}
    </td>
   </tr>
  </table>
 </div>

 <script Src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js"></script>

 <script>
  var app=angular.module("myapp", []);
  app.controller("namesctrl", function($scope){

   $scope.Manage_Roleser=
   {
    "RoleName" : "Verify",
       "IsActive" : true,
    "UIList": [{
    "UiName": "One",
    "View" : false,
    "Edit" : false
   },{
    "UiName": "Two",
    "View" : false,
    "Edit" : false
   },
   {
    "UiName": "Three",
    "View" : false,
    "Edit" : false
   },
   {
    "UiName": "Four",
    "View" : false,
    "Edit" : false
   },
   {
    "UiName": "Five",
    "View" : false,
    "Edit" : false
   }]
  }

  });

 </script>
</body>
</html>


问:
How do you pull an encrypted e-mail address that is attached on an url?
I am trying to pull out an encrypted email I attached to the end of a url.

I want to get the encrypted email, decrypt it and look for the record which has the same email and pull an id from that table and insert it into another table.

```<code>    $password = "hogehoge";
    $gethex = hex2bin($hex);
    $decrypt = openssl_decrypt($gethex, 'aes-256-ecb', $password);
    $user = $this->userinfo->getUserEmail($decrypt);
</code>```

答:
Get all request parameters in laravel.</p>

```<code>use Input;

$params = Input::all();
</code>```

Body:
I am trying to pull out an encrypted email I attached to the end of a url.

I want to get the encrypted email, decrypt it and look for the record which has the same email and pull an id from that table and insert it into another table.

    $password = "hogehoge";
    $gethex = hex2bin($hex);
    $decrypt = openssl_decrypt($gethex, 'aes-256-ecb', $password);
    $user = $this->userinfo->getUserEmail($decrypt);

Body:
Get all request parameters in laravel.

use Input;

$params = Input::all();


问:
Pandas dataframe to json list format
I have large pandas tabular dataframe to convert into JSON.
The standard .to_json() functions does not make a compact format for JSON.
How to get JSON output forma like this,  using pandas only ?

```<code>{"index": [ 0, 1 ,3 ],
 "col1": [ "250", "1" ,"3" ],
 "col2": [ "250", "1" ,"3" ]
}
</code>```

This is a much compact format form of JSON for tabular data.
(I can do a loop over the rows.... but)

答:
It seems you need to_dict first and then dict to json:

```<code>df = pd.DataFrame({"index": [ 0, 1 ,3 ],
 "col1": [ "250", "1" ,"3" ],
 "col2": [ "250", "1" ,"3" ]
})
print (df)
  col1 col2  index
0  250  250      0
1    1    1      1
2    3    3      3

print (df.to_dict(orient='list'))
{'col1': ['250', '1', '3'], 'col2': ['250', '1', '3'], 'index': [0, 1, 3]}
</code>```

```<code>import json

print (json.dumps(df.to_dict(orient='list')))
{"col1": ["250", "1", "3"], "col2": ["250", "1", "3"], "index": [0, 1, 3]}
</code>```

Because it is not implemented yet:

```<code>print (df.to_json(orient='list'))
</code>```

ValueError: Invalid value 'list' for option 'orient'

EDIT:

If index is not column, add reset_index:

```<code>df = pd.DataFrame({"col1": [250, 1, 3],
                   "col2": [250, 1, 3]})
print (df)
   col1  col2
0   250   250
1     1     1
2     3     3

print (df.reset_index().to_dict(orient='list'))
{'col1': [250, 1, 3], 'index': [0, 1, 2], 'col2': [250, 1, 3]}
</code>```

Title: Pandas dataframe to json list format

Body:
I have large pandas tabular dataframe to convert into JSON.
The standard .to_json() functions does not make a compact format for JSON.
How to get JSON output forma like this,  using pandas only ?

{"index": [ 0, 1 ,3 ],
 "col1": [ "250", "1" ,"3" ],
 "col2": [ "250", "1" ,"3" ]
}

This is a much compact format form of JSON for tabular data.
(I can do a loop over the rows.... but)

Body:
It seems you need to_dict first and then dict to json:

df = pd.DataFrame({"index": [ 0, 1 ,3 ],
 "col1": [ "250", "1" ,"3" ],
 "col2": [ "250", "1" ,"3" ]
})
print (df)
  col1 col2  index
0  250  250      0
1    1    1      1
2    3    3      3

print (df.to_dict(orient='list'))
{'col1': ['250', '1', '3'], 'col2': ['250', '1', '3'], 'index': [0, 1, 3]}

import json

print (json.dumps(df.to_dict(orient='list')))
{"col1": ["250", "1", "3"], "col2": ["250", "1", "3"], "index": [0, 1, 3]}

Because it is not implemented yet:

print (df.to_json(orient='list'))

ValueError: Invalid value 'list' for option 'orient'

EDIT:

If index is not column, add reset_index:

df = pd.DataFrame({"col1": [250, 1, 3],
                   "col2": [250, 1, 3]})
print (df)
   col1  col2
0   250   250
1     1     1
2     3     3

print (df.reset_index().to_dict(orient='list'))
{'col1': [250, 1, 3], 'index': [0, 1, 2], 'col2': [250, 1, 3]}


问:
If I do not pass enough parameters when calling a function in a DLL, what will happen?
In a dll project, the function is like this:

```<code>extern "C" __declspec(dllexport) void foo(const wchar_t* a, const wchar_t* b, const wchar_t* c)
</code>```

In a different project, I will use foo function, but I declare foo function in header file with

```<code>extern "C" __declspec(dllimport) void foo(const wchar_t* a, const wchar_t* b)
</code>```

and I call it with only two parameters.

The result is success, I think it about __cdecl call, but I would like to know how and why this works.

答:
32-bit

Default calling convention is __cdecl, which means the caller pushes parameters onto the stack right-to-left then cleans up the stack after the call returns.

So in your case, the caller:

Pushes b

Pushes a

Pushes the return address

Calls the function.

At this point the stack looks like this (assume 4 byte pointers for example, and remember the stack pointer travels backwards when you push things):

+-----+ <--- this is where esp is after pushing stuff
| ret | [esp]
+-----+
|  a  | [esp+4]
+-----+
|  b  | [esp+8]
+-----+ <--- this is where esp was before we started
| ??? | [esp+12 and beyond]
+-----+
```

Ok, great. Now the problem happens on the callee side. The callee is expecting parameters to be at certain locations on the stack, so:

a is assumed to be at [esp+4]

b is assumed to be at [esp+8]

c is assumed to be at [esp+12]

And this is where the issue is: We have no idea what's at [esp+12]. So the callee will see the correct values of a and b, but will interpret whatever unknown garbage happens to be at [esp+12] as c.

At that point it's pretty much undefined, and depends on what your function actually does with c.

After all this is over and the callee returns, assuming your program didn't crash, the caller will restore esp and the stack pointer will be back where it should be. So from the caller's POV everything is probably fine and the stack pointer ends up back where it's supposed to be, but the callee sees junk for c.

64-bit

The mechanics on 64-bit machines is different but the end result is roughly the same effect. Microsoft uses the following calling convention on 64-bit machines regardless of __cdecl or whatever (any convention you specify is ignored and all are treated identically):

First four integer or pointer arguments placed in registers rcx, rdx, r8, and r9, in that order, left-to-right.

First four floating-point arguments placed in registers xmm0, xmm1, xmm2, and xmm3, in that order, left-to-right.

Anything remaining is pushed to the stack, right-to-left.

The caller is responsible for restoring esp as well as restoring the values of all volatile registers after the call.

So in your case, the caller:

Puts a in rcx.

Puts b in rdx.

Allocates an extra 32 bytes of "shadow space" on the stack (see that MS article).

Pushes the return address.

Calls the function.

But the callee is expecting:

a assumed to be in rcx (check!)

b assumed to be in rdx (check!)

c assumed to be in r8 (problem)

And so, as with the 32-bit case, the callee interprets whatever happened to be in r8 as c, and potential hijinks ensue, with the end effect depending on what the callee does with c. When it returns, assuming the program did not crash, the caller restores all volatile registers (rcx and rdx, and also generally includes r8 and friends) and restores esp.

Body:
In a dll project, the function is like this:

extern "C" __declspec(dllexport) void foo(const wchar_t* a, const wchar_t* b, const wchar_t* c)

In a different project, I will use foo function, but I declare foo function in header file with

extern "C" __declspec(dllimport) void foo(const wchar_t* a, const wchar_t* b)

and I call it with only two parameters.

The result is success, I think it about __cdecl call, but I would like to know how and why this works.

Body:
32-bit

Default calling convention is __cdecl, which means the caller pushes parameters onto the stack right-to-left then cleans up the stack after the call returns.

So in your case, the caller:

Pushes b

Pushes a

Pushes the return address

Calls the function.

At this point the stack looks like this (assume 4 byte pointers for example, and remember the stack pointer travels backwards when you push things):

+-----+ <--- this is where esp is after pushing stuff
| ret | [esp]
+-----+
|  a  | [esp+4]
+-----+
|  b  | [esp+8]
+-----+ <--- this is where esp was before we started
| ??? | [esp+12 and beyond]
+-----+

Ok, great. Now the problem happens on the callee side. The callee is expecting parameters to be at certain locations on the stack, so:

a is assumed to be at [esp+4]

b is assumed to be at [esp+8]

c is assumed to be at [esp+12]

And this is where the issue is: We have no idea what's at [esp+12]. So the callee will see the correct values of a and b, but will interpret whatever unknown garbage happens to be at [esp+12] as c.

At that point it's pretty much undefined, and depends on what your function actually does with c.

After all this is over and the callee returns, assuming your program didn't crash, the caller will restore esp and the stack pointer will be back where it should be. So from the caller's POV everything is probably fine and the stack pointer ends up back where it's supposed to be, but the callee sees junk for c.

64-bit

The mechanics on 64-bit machines is different but the end result is roughly the same effect. Microsoft uses the following calling convention on 64-bit machines regardless of __cdecl or whatever (any convention you specify is ignored and all are treated identically):

First four integer or pointer arguments placed in registers rcx, rdx, r8, and r9, in that order, left-to-right.

First four floating-point arguments placed in registers xmm0, xmm1, xmm2, and xmm3, in that order, left-to-right.

Anything remaining is pushed to the stack, right-to-left.

The caller is responsible for restoring esp as well as restoring the values of all volatile registers after the call.

So in your case, the caller:

Puts a in rcx.

Puts b in rdx.

Allocates an extra 32 bytes of "shadow space" on the stack (see that MS article).

Pushes the return address.

Calls the function.

But the callee is expecting:

a assumed to be in rcx (check!)

b assumed to be in rdx (check!)

c assumed to be in r8 (problem)

And so, as with the 32-bit case, the callee interprets whatever happened to be in r8 as c, and potential hijinks ensue, with the end effect depending on what the callee does with c. When it returns, assuming the program did not crash, the caller restores all volatile registers (rcx and rdx, and also generally includes r8 and friends) and restores esp.

ContentLicense: CC BY-SA 4.0


问:
Number of fields in a structure
I'm new in abap development .
Actually, I'm looking for the Number of fields of a table or structure

any suggestion please

答:
Another solution from my side.</p>

```<code>select count(*) into @data(lv_count) from dd03l
    where tabname = 'YOUR STRUCTURE NAME' and AS4LOCAL = 'A'.
</code>```

Title: Number of fields in a structure

Body:
Another solution from my side.

select count(*) into @data(lv_count) from dd03l
    where tabname = 'YOUR STRUCTURE NAME' and AS4LOCAL = 'A'.


问:
Getter for private member object in Java
Say I have a class called Truck and one of the private member variables is of class Wheel. A getter for the Wheel variable, getWheel, would return a reference to it, as follows:

```<code>class Truck{
    private Wheel wheel;

    Truck(){
        wheel=new Wheel();

    }

    Wheel getWheel(){
        return this.wheel;
    }
}

class Wheel{
    int color;
}
</code>```

Now, whoever calls getWheel will be able to modify the private member object at will:

```<code>class me{
    public static void main(String[] args){
        Truck ye=new Truck();
        Wheel v=ye.getWheel();

        v.color=2;
    }
}
</code>```

This would defeat encapsulation, wouldn't it?

What would be the right remedy for this?

答:
You can make a private/package setter for wheel color.
Also, initialize the color in the constructor which would help you do that.

And like other answers, returning a copy of Wheel is also a good way to do this.

Body:
Say I have a class called Truck and one of the private member variables is of class Wheel. A getter for the Wheel variable, getWheel, would return a reference to it, as follows:

class Truck{
    private Wheel wheel;

    Truck(){
        wheel=new Wheel();

    }

    Wheel getWheel(){
        return this.wheel;
    }
}

class Wheel{
    int color;
}

Now, whoever calls getWheel will be able to modify the private member object at will:

class me{
    public static void main(String[] args){
        Truck ye=new Truck();
        Wheel v=ye.getWheel();

        v.color=2;
    }
}

This would defeat encapsulation, wouldn't it?

What would be the right remedy for this?


问:
Is it possible to inject interface with angular2?
i wonder if there is a proper way to inject interfaces in Angular2? (cf. below)

I think this is related with the missing @Injectable() decorator on the interface, but it seems this is not allowed.

Regards.

When CoursesServiceInterface is implemented as an interface, the TypeScript compiler complains "CoursesServiceInterface cannot find name":

```<code>import {CoursesServiceInterface} from './CoursesService.interface';
import {CoursesService} from './CoursesService.service';
import {CoursesServiceMock} from './CoursesServiceMock.service';
bootstrap(AppComponent, [
  ROUTER_PROVIDERS,
  GlobalService,
  provide(CoursesServiceInterface, { useClass: CoursesServiceMock })
  ]);
</code>```

but with CoursesServiceInterface as an interface:

```<code>import {Injectable} from 'angular2/core';
import {Course} from './Course.class';
//@Injectable()
export interface CoursesServiceInterface {
    getAllCourses(): Promise<Course[]>;//{ return null; };
    getCourse(id: number): Promise<Course>;// { return null; };
    remove(id: number): Promise<{}>;// { return null; };
}
</code>```

When service is a class, the TypeScript compiler doesn't complain anymore:

```<code>import {Injectable} from 'angular2/core';
import {Course} from './Course.class';
@Injectable()
export class CoursesServiceInterface {
    getAllCourses() : Promise<Course[]> { return null; };
    getCourse(id: number) :Promise<Course> { return null; };
    remove (id: number) : Promise<{}> { return null; };
}
</code>```

答:
My experience (coming from java backend development) into frontend dev is the following.

If we speak about 'interface' I have the strong expectation that an main principle of using interface is assured by languages who 'offer' interface.
Which is: 'code against interface not against implementation'.

This seems to not be assured by typescript/angular2. (than they shouldn't use word interface yet, maybe).

What was my case (warning: I'm learning angular2 so my workaround could seem ugly to advanced users):

Component A1 has a child component B.

Component B should know the parent and call a method on parent.

So component B receives the parent via DependencyInjection in it's constructor.

```<code>   constructor( private a: A1Component) {}
</code>```

Everything is fine.

Than things get complicated.

Another component A2 can be the parent of comp. B.

Ideally I should inject in B an interface (not implementation) which is implemented by both A1 and A2 (this would be naturally in java world).

Than B would work with this interface. If needed, A typecast to A2 for example would make B aware if the instance he has is really A2 or not.

I speak about plain components/classes, not services (I see that most solutions refers to services).

I tried to use @Host(), @Injectable(), OpaqueToken, Providers but always there was an error. When in the end it seemed to work: in reality the object injected in Component B was an empty object, not the parent - maybe I wrongly used to providers and a new empty object was created instead of injecting the parent object.

What I did in the end: I didn't use interface.

I created a plain base class for A1 and A2 - let's call it ABase.

Component B would keep a reference to this base class. Reference would be set in constructor as this:

```<code>//BComponent:
 parent: ABase;

 constructor(@Optional parentA1: A1Component, @Optional parentA2: A2Component) {
    if( parentA1 )
       this.parent = parentA1;
    else
       this.parent = parentA2
 }
</code>```

Yes, it's a strange workaround, not nice (coming from java world thinking, I agree) - but I just run out of time and was disappointed about the 'interface' thing.

Updated

I reconsider the previous answer (it's bad design, ugly ... was at the my beginnings with angular)

Now Angular's documentation have clear description on this exact issue: finding the parent of a component.

Can not use interface - as interface can not be injected.

"Looking for components that implement an interface would be better. That's not possible because TypeScript interfaces disappear from the transpiled JavaScript, which doesn't support interfaces. There's no artifact to look for."

Can not use base class of possible parents neither ... (this is the root cause of my with previous desperate, bad- answer)

What works? Technique: find a parent by its class-interface.

Mainly:

Child B see a general parent Parent (can be A1Component or A2Component)

```<code>export class BComponent {
  name = 'B';
  constructor( @Optional() public parent: Parent ) { }
}
</code>```

And the each possible parent component provides a Parent (at component level !!!) using class-interface:

```<code>providers: [{ provide: Parent, useExisting: forwardRef(() => A1Component) }],
</code>```

Body:
i wonder if there is a proper way to inject interfaces in Angular2? (cf. below)

I think this is related with the missing @Injectable() decorator on the interface, but it seems this is not allowed.

Regards.

When CoursesServiceInterface is implemented as an interface, the TypeScript compiler complains "CoursesServiceInterface cannot find name":

import {CoursesServiceInterface} from './CoursesService.interface';
import {CoursesService} from './CoursesService.service';
import {CoursesServiceMock} from './CoursesServiceMock.service';
bootstrap(AppComponent, [
  ROUTER_PROVIDERS,
  GlobalService,
  provide(CoursesServiceInterface, { useClass: CoursesServiceMock })
  ]);

but with CoursesServiceInterface as an interface:

import {Injectable} from 'angular2/core';
import {Course} from './Course.class';
//@Injectable()
export interface CoursesServiceInterface {
    getAllCourses(): Promise<Course[]>;//{ return null; };
    getCourse(id: number): Promise<Course>;// { return null; };
    remove(id: number): Promise<{}>;// { return null; };
}

When service is a class, the TypeScript compiler doesn't complain anymore:

import {Injectable} from 'angular2/core';
import {Course} from './Course.class';
@Injectable()
export class CoursesServiceInterface {
    getAllCourses() : Promise<Course[]> { return null; };
    getCourse(id: number) :Promise<Course> { return null; };
    remove (id: number) : Promise<{}> { return null; };
}

Body:
My experience (coming from java backend development) into frontend dev is the following.

If we speak about 'interface' I have the strong expectation that an main principle of using interface is assured by languages who 'offer' interface.
Which is: 'code against interface not against implementation'.

This seems to not be assured by typescript/angular2. (than they shouldn't use word interface yet, maybe).

What was my case (warning: I'm learning angular2 so my workaround could seem ugly to advanced users):

Component A1 has a child component B.

Component B should know the parent and call a method on parent.

So component B receives the parent via DependencyInjection in it's constructor.

   constructor( private a: A1Component) {}

Everything is fine.

Than things get complicated.

Another component A2 can be the parent of comp. B.

Ideally I should inject in B an interface (not implementation) which is implemented by both A1 and A2 (this would be naturally in java world).

Than B would work with this interface. If needed, A typecast to A2 for example would make B aware if the instance he has is really A2 or not.

I speak about plain components/classes, not services (I see that most solutions refers to services).

I tried to use @Host(), @Injectable(), OpaqueToken, Providers but always there was an error. When in the end it seemed to work: in reality the object injected in Component B was an empty object, not the parent - maybe I wrongly used to providers and a new empty object was created instead of injecting the parent object.

What I did in the end: I didn't use interface.

I created a plain base class for A1 and A2 - let's call it ABase.

Component B would keep a reference to this base class. Reference would be set in constructor as this:

//BComponent:
 parent: ABase;

 constructor(@Optional parentA1: A1Component, @Optional parentA2: A2Component) {
    if( parentA1 )
       this.parent = parentA1;
    else
       this.parent = parentA2
 }

Yes, it's a strange workaround, not nice (coming from java world thinking, I agree) - but I just run out of time and was disappointed about the 'interface' thing.

Updated

I reconsider the previous answer (it's bad design, ugly ... was at the my beginnings with angular)

Now Angular's documentation have clear description on this exact issue: finding the parent of a component.

Can not use interface - as interface can not be injected.

"Looking for components that implement an interface would be better. That's not possible because TypeScript interfaces disappear from the transpiled JavaScript, which doesn't support interfaces. There's no artifact to look for."

Can not use base class of possible parents neither ... (this is the root cause of my with previous desperate, bad- answer)

What works? Technique: find a parent by its class-interface.

Mainly:

Child B see a general parent Parent (can be A1Component or A2Component)

export class BComponent {
  name = 'B';
  constructor( @Optional() public parent: Parent ) { }
}

And the each possible parent component provides a Parent (at component level !!!) using class-interface:

providers: [{ provide: Parent, useExisting: forwardRef(() => A1Component) }],


问:
SSL handshake alert: unrecognized_name error since upgrade to Java 1.7.0
I upgraded from Java 1.6 to Java 1.7 today.
Since then an error occur when I try to establish a connection to my webserver over SSL:

```<code>javax.net.ssl.SSLProtocolException: handshake alert:  unrecognized_name
    at sun.security.ssl.ClientHandshaker.handshakeAlert(ClientHandshaker.java:1288)
    at sun.security.ssl.SSLSocketImpl.recvAlert(SSLSocketImpl.java:1904)
    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1027)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1262)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1289)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1273)
    at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:523)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1296)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
    at java.net.URL.openStream(URL.java:1035)
</code>```

Here is the code:

```<code>SAXBuilder builder = new SAXBuilder();
Document document = null;

try {
    url = new URL(https://some url);
    document = (Document) builder.build(url.openStream());
} catch (NoSuchAlgorithmException ex) {
    Logger.getLogger(DownloadLoadiciousComputer.class.getName()).log(Level.SEVERE, null, ex);
}
</code>```

Its only a test project thats why I allow and use untrusted certificates with the code:

```<code>TrustManager[] trustAllCerts = new TrustManager[]{
    new X509TrustManager() {

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(
                java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(
                java.security.cert.X509Certificate[] certs, String authType) {
        }
    }
};

try {

    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {

    Logger.getLogger(DownloadManager.class.getName()).log(Level.SEVERE, null, e);
}
</code>```

I sucessfully tried to connect to https://google.com.
where is my fault?

Thanks.

答:
There is an easier way where you can just use your own HostnameVerifier to implicitly trust certain connections. The issue comes with Java 1.7 where SNI extensions have been added and your error is due to a server misconfiguration.

You can either use "-Djsse.enableSNIExtension=false" to disable SNI across the whole JVM or read my blog where I explain how to implement a custom verifier on top of a URL connection.

Body:
I upgraded from Java 1.6 to Java 1.7 today.
Since then an error occur when I try to establish a connection to my webserver over SSL:

javax.net.ssl.SSLProtocolException: handshake alert:  unrecognized_name
    at sun.security.ssl.ClientHandshaker.handshakeAlert(ClientHandshaker.java:1288)
    at sun.security.ssl.SSLSocketImpl.recvAlert(SSLSocketImpl.java:1904)
    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1027)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1262)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1289)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1273)
    at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:523)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1296)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
    at java.net.URL.openStream(URL.java:1035)

Here is the code:

SAXBuilder builder = new SAXBuilder();
Document document = null;

try {
    url = new URL(https://some url);
    document = (Document) builder.build(url.openStream());
} catch (NoSuchAlgorithmException ex) {
    Logger.getLogger(DownloadLoadiciousComputer.class.getName()).log(Level.SEVERE, null, ex);
}

Its only a test project thats why I allow and use untrusted certificates with the code:

TrustManager[] trustAllCerts = new TrustManager[]{
    new X509TrustManager() {

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(
                java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(
                java.security.cert.X509Certificate[] certs, String authType) {
        }
    }
};

try {

    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {

    Logger.getLogger(DownloadManager.class.getName()).log(Level.SEVERE, null, e);
}

I sucessfully tried to connect to https://google.com.
where is my fault?

Thanks.


问:
What does this Eclipse icon mean in a Merge Results view?
I just did an svn merge from a branch to a trunk in my Eclipse IDE, and in the Merge Results view, there is this following icon:

alt text http://www.freeimagehosting.net/uploads/2a0a0f90b1.jpg

I am dying to know what it means.  I have searched the entire Eclipse documentation and some relevant StackOverflow questions, but couldn't find anything.

The CollabNet documentation about Merge Results View explains what a Merge Results View is, but doesn't mention anything about the meanings of its icons.

Does anyone know?  Thanks!

答:
I've just hit up against the same thing.

After a bit of digging around I believe that it means there were changes to the file in both places however the changes are the same, therefore the files are the same.


问:
How to make two UIImage sizes the same in swift?
I want to match the size of "yellow_noise.png" to the size of the "pickedImage" from the UIImagePickerController. What should I do?

```<code>    originalImageView.image = pickedImage
    overayImageView.image = UIImage(named:"yellow_noise.png")
</code>```

答:
Maybe you could do something like this:</p>

```<code>let overlayImageView = UIImageView(frame: originalImageView.frame)
overlayImageView.image = UIImage(named:"yellow_noise.png")
</code>```

Body:
I want to match the size of "yellow_noise.png" to the size of the "pickedImage" from the UIImagePickerController. What should I do?

    originalImageView.image = pickedImage
    overayImageView.image = UIImage(named:"yellow_noise.png")

Body:
Maybe you could do something like this:

let overlayImageView = UIImageView(frame: originalImageView.frame)
overlayImageView.image = UIImage(named:"yellow_noise.png")


问:
Spring-Boot Thymeleaf Binding Enum at hidden field
I would like to bind an enum at a hidden field to keep the information when submitting the form. Somehow the field of enum is null then.

My Object looks like:

```<code>public class Check {
    @NotNull        private String name;
    @NotNull        private CheckType type; // ENUM with GETTER & SETTER

    // BESIDE NORMAL GETTER & SETTER ANOTHER TRY ...
    public String getTypeName() {
        return type == null ? null : type.name();
    }

    public void setTypeName(String name) {
        type = CheckType.valueOf(name);
    }

    ...
}
</code>```

In my Thymeleaf-Template I am iterating through the Objects and want to hold the enum:

```<code><input type="hidden" th:field="*{checks[__${checkStat.index}__].type}" />

<!-- ALSO TRIED ... -->
<input type="hidden" th:field="*{checks[__${checkStat.index}__].typeName}" />
</code>```

After sending Form, type is null. What am I missing?

答:
Okay, I have the issue but was not viewable in my question. The enum mapping works, but what I also have in my class is something like:

```<code>public Integer getSpecialValue() {
    if (type == SOMETHING) {
        return rareEventThreshold;
    } else {
        throw new IllegalStateException();
    }
}

// EQUALS TO SETTER
</code>```

In fact I cant trust in which order the Getter & Setter are called, so that is not a good idea. I will now use a DTO Object with "normal" Getter & Setter without any logic.

Body:
I would like to bind an enum at a hidden field to keep the information when submitting the form. Somehow the field of enum is null then.

My Object looks like:

public class Check {
    @NotNull        private String name;
    @NotNull        private CheckType type; // ENUM with GETTER & SETTER

    // BESIDE NORMAL GETTER & SETTER ANOTHER TRY ...
    public String getTypeName() {
        return type == null ? null : type.name();
    }

    public void setTypeName(String name) {
        type = CheckType.valueOf(name);
    }

    ...
}

In my Thymeleaf-Template I am iterating through the Objects and want to hold the enum:

<input type="hidden" th:field="*{checks[__${checkStat.index}__].type}" />

<input type="hidden" th:field="*{checks[__${checkStat.index}__].typeName}" />

After sending Form, type is null. What am I missing?

Body:
Okay, I have the issue but was not viewable in my question. The enum mapping works, but what I also have in my class is something like:

public Integer getSpecialValue() {
    if (type == SOMETHING) {
        return rareEventThreshold;
    } else {
        throw new IllegalStateException();
    }
}

// EQUALS TO SETTER

In fact I cant trust in which order the Getter & Setter are called, so that is not a good idea. I will now use a DTO Object with "normal" Getter & Setter without any logic.


问:
Python - aiohttp - Why won't my tests run?
I have downloaded the code here https://github.com/aosabook/500lines.

This is an educational open source project with many sub-projects. The one I am studying currently is the 'crawler' project. It requires python 3.4+ and aiohttp 1.2+. My current setup is Windows 10, Python 3.6.1, and aiohttp 2.0.4.

Strangely, my tests do not run and it is related to aiohttp. Can anybody familiar with aiohttp tell me why?

Here is the output I get:

```<code>C:\Users\Primary User\Desktop\500lines-master\crawler\code>python test.py
C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web.py:54: ResourceWarning: loop argument is deprecated
  warnings.warn("loop argument is deprecated", ResourceWarning)
E.E..EEEEEEEEEE..
======================================================================
ERROR: test_content_type (__main__.TestCrawler)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test.py", line 314, in test_content_type
    self.add_page(content_type='foo')
  File "test.py", line 93, in add_page
    self.add_handler(url, handler)
  File "test.py", line 76, in add_handler
    self.app.router.add_route('GET', url, handler)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 823, in add_route
    resource = self.add_resource(path, name=name)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 787, in add_resource
    self.register_resource(resource)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 762, in register_resource
    "Cannot register a resource into frozen router.")
RuntimeError: Cannot register a resource into frozen router.

======================================================================
ERROR: test_encoding (__main__.TestCrawler)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test.py", line 309, in test_encoding
    test_charset('', 'utf-8')
  File "test.py", line 305, in test_charset
    self.add_page(url, content_type=content_type)
  File "test.py", line 93, in add_page
    self.add_handler(url, handler)
  File "test.py", line 76, in add_handler
    self.app.router.add_route('GET', url, handler)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 823, in add_route
    resource = self.add_resource(path, name=name)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 787, in add_resource
    self.register_resource(resource)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 762, in register_resource
    "Cannot register a resource into frozen router.")
RuntimeError: Cannot register a resource into frozen router.

======================================================================
ERROR: test_link (__main__.TestCrawler)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test.py", line 126, in test_link
    self.add_page('/', ['/foo'])
  File "test.py", line 93, in add_page
    self.add_handler(url, handler)
  File "test.py", line 76, in add_handler
    self.app.router.add_route('GET', url, handler)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 823, in add_route
    resource = self.add_resource(path, name=name)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 787, in add_resource
    self.register_resource(resource)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 762, in register_resource
    "Cannot register a resource into frozen router.")
RuntimeError: Cannot register a resource into frozen router.

======================================================================
ERROR: test_link_cycle (__main__.TestCrawler)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test.py", line 137, in test_link_cycle
    url = self.add_page('/foo', ['/bar'])
  File "test.py", line 93, in add_page
    self.add_handler(url, handler)
  File "test.py", line 76, in add_handler
    self.app.router.add_route('GET', url, handler)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 823, in add_route
    resource = self.add_resource(path, name=name)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 787, in add_resource
    self.register_resource(resource)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 762, in register_resource
    "Cannot register a resource into frozen router.")
RuntimeError: Cannot register a resource into frozen router.

======================================================================
ERROR: test_max_tasks (__main__.TestCrawler)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test.py", line 264, in test_max_tasks
    self.add_handler(url, handler)
  File "test.py", line 76, in add_handler
    self.app.router.add_route('GET', url, handler)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 823, in add_route
    resource = self.add_resource(path, name=name)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 787, in add_resource
    self.register_resource(resource)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 762, in register_resource
    "Cannot register a resource into frozen router.")
RuntimeError: Cannot register a resource into frozen router.

======================================================================
ERROR: test_max_tries (__main__.TestCrawler)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test.py", line 281, in test_max_tries
    self.add_handler('/', handler)
  File "test.py", line 76, in add_handler
    self.app.router.add_route('GET', url, handler)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 823, in add_route
    resource = self.add_resource(path, name=name)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 787, in add_resource
    self.register_resource(resource)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 762, in register_resource
    "Cannot register a resource into frozen router.")
RuntimeError: Cannot register a resource into frozen router.

======================================================================
ERROR: test_non_html (__main__.TestCrawler)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test.py", line 322, in test_non_html
    self.add_page('/xml', body=body, content_type='application/xml')
  File "test.py", line 93, in add_page
    self.add_handler(url, handler)
  File "test.py", line 76, in add_handler
    self.app.router.add_route('GET', url, handler)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 823, in add_route
    resource = self.add_resource(path, name=name)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 787, in add_resource
    self.register_resource(resource)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 762, in register_resource
    "Cannot register a resource into frozen router.")
RuntimeError: Cannot register a resource into frozen router.

======================================================================
ERROR: test_non_http (__main__.TestCrawler)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test.py", line 333, in test_non_http
    self.add_page(body=body)
  File "test.py", line 93, in add_page
    self.add_handler(url, handler)
  File "test.py", line 76, in add_handler
    self.app.router.add_route('GET', url, handler)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 823, in add_route
    resource = self.add_resource(path, name=name)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 787, in add_resource
    self.register_resource(resource)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 762, in register_resource
    "Cannot register a resource into frozen router.")
RuntimeError: Cannot register a resource into frozen router.

======================================================================
ERROR: test_prohibited_host (__main__.TestCrawler)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test.py", line 152, in test_prohibited_host
    self.add_page('/', ['http://example.com'])
  File "test.py", line 93, in add_page
    self.add_handler(url, handler)
  File "test.py", line 76, in add_handler
    self.app.router.add_route('GET', url, handler)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 823, in add_route
    resource = self.add_resource(path, name=name)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 787, in add_resource
    self.register_resource(resource)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 762, in register_resource
    "Cannot register a resource into frozen router.")
RuntimeError: Cannot register a resource into frozen router.

======================================================================
ERROR: test_redirect (__main__.TestCrawler)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test.py", line 196, in test_redirect
    url = self.add_redirect('/', foo)
  File "test.py", line 101, in add_redirect
    self.add_handler(url, handler)
  File "test.py", line 76, in add_handler
    self.app.router.add_route('GET', url, handler)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 823, in add_route
    resource = self.add_resource(path, name=name)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 787, in add_resource
    self.register_resource(resource)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 762, in register_resource
    "Cannot register a resource into frozen router.")
RuntimeError: Cannot register a resource into frozen router.

======================================================================
ERROR: test_redirect_cycle (__main__.TestCrawler)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test.py", line 214, in test_redirect_cycle
    url = self.add_redirect('/bar', foo)
  File "test.py", line 101, in add_redirect
    self.add_handler(url, handler)
  File "test.py", line 76, in add_handler
    self.app.router.add_route('GET', url, handler)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 823, in add_route
    resource = self.add_resource(path, name=name)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 787, in add_resource
    self.register_resource(resource)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 762, in register_resource
    "Cannot register a resource into frozen router.")
RuntimeError: Cannot register a resource into frozen router.

======================================================================
ERROR: test_redirect_join (__main__.TestCrawler)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test.py", line 230, in test_redirect_join
    self.add_redirect('/foo', baz)
  File "test.py", line 101, in add_redirect
    self.add_handler(url, handler)
  File "test.py", line 76, in add_handler
    self.app.router.add_route('GET', url, handler)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 823, in add_route
    resource = self.add_resource(path, name=name)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 787, in add_resource
    self.register_resource(resource)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 762, in register_resource
    "Cannot register a resource into frozen router.")
RuntimeError: Cannot register a resource into frozen router.

----------------------------------------------------------------------
Ran 17 tests in 0.034s

FAILED (errors=12)

C:\Users\Primary User\Desktop\500lines-master\crawler\code>
</code>```

答:
I am also learning it. I found this issue https://github.com/hangoutsbot/hangoutsbot/pull/655. Then code like this

```<code>@asyncio.coroutine
def _create_server(self):
    app = web.Application(loop=self.loop)
    return app

def add_handler(self, url, handler):
    self.app.router.add_route('GET', url, handler)
    handler_factory = self.app.make_handler(debug=True)
    srv = yield from self.loop.create_server(
        handler_factory, '127.0.0.1', self.port)

    # Prevent "Task destroyed but it is pending" warnings.
    self.addCleanup(lambda: self.loop.run_until_complete(
        handler_factory.finish_connections()))

    self.addCleanup(srv.close)
</code>```

I think you should run crawl.py. Another problem, aiohttp 2.0.4 has no results after running for me. Using aiohttp 0.21 fixed it.

Body:
I have downloaded the code here https://github.com/aosabook/500lines.

This is an educational open source project with many sub-projects. The one I am studying currently is the 'crawler' project. It requires python 3.4+ and aiohttp 1.2+. My current setup is Windows 10, Python 3.6.1, and aiohttp 2.0.4.

Strangely, my tests do not run and it is related to aiohttp. Can anybody familiar with aiohttp tell me why?

Here is the output I get:

C:\Users\Primary User\Desktop\500lines-master\crawler\code>python test.py
C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web.py:54: ResourceWarning: loop argument is deprecated
  warnings.warn("loop argument is deprecated", ResourceWarning)
E.E..EEEEEEEEEE..
======================================================================
ERROR: test_content_type (__main__.TestCrawler)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test.py", line 314, in test_content_type
    self.add_page(content_type='foo')
  File "test.py", line 93, in add_page
    self.add_handler(url, handler)
  File "test.py", line 76, in add_handler
    self.app.router.add_route('GET', url, handler)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 823, in add_route
    resource = self.add_resource(path, name=name)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 787, in add_resource
    self.register_resource(resource)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 762, in register_resource
    "Cannot register a resource into frozen router.")
RuntimeError: Cannot register a resource into frozen router.

======================================================================
ERROR: test_encoding (__main__.TestCrawler)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test.py", line 309, in test_encoding
    test_charset('', 'utf-8')
  File "test.py", line 305, in test_charset
    self.add_page(url, content_type=content_type)
  File "test.py", line 93, in add_page
    self.add_handler(url, handler)
  File "test.py", line 76, in add_handler
    self.app.router.add_route('GET', url, handler)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 823, in add_route
    resource = self.add_resource(path, name=name)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 787, in add_resource
    self.register_resource(resource)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 762, in register_resource
    "Cannot register a resource into frozen router.")
RuntimeError: Cannot register a resource into frozen router.

======================================================================
ERROR: test_link (__main__.TestCrawler)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test.py", line 126, in test_link
    self.add_page('/', ['/foo'])
  File "test.py", line 93, in add_page
    self.add_handler(url, handler)
  File "test.py", line 76, in add_handler
    self.app.router.add_route('GET', url, handler)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 823, in add_route
    resource = self.add_resource(path, name=name)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 787, in add_resource
    self.register_resource(resource)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 762, in register_resource
    "Cannot register a resource into frozen router.")
RuntimeError: Cannot register a resource into frozen router.

======================================================================
ERROR: test_link_cycle (__main__.TestCrawler)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test.py", line 137, in test_link_cycle
    url = self.add_page('/foo', ['/bar'])
  File "test.py", line 93, in add_page
    self.add_handler(url, handler)
  File "test.py", line 76, in add_handler
    self.app.router.add_route('GET', url, handler)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 823, in add_route
    resource = self.add_resource(path, name=name)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 787, in add_resource
    self.register_resource(resource)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 762, in register_resource
    "Cannot register a resource into frozen router.")
RuntimeError: Cannot register a resource into frozen router.

======================================================================
ERROR: test_max_tasks (__main__.TestCrawler)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test.py", line 264, in test_max_tasks
    self.add_handler(url, handler)
  File "test.py", line 76, in add_handler
    self.app.router.add_route('GET', url, handler)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 823, in add_route
    resource = self.add_resource(path, name=name)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 787, in add_resource
    self.register_resource(resource)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 762, in register_resource
    "Cannot register a resource into frozen router.")
RuntimeError: Cannot register a resource into frozen router.

======================================================================
ERROR: test_max_tries (__main__.TestCrawler)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test.py", line 281, in test_max_tries
    self.add_handler('/', handler)
  File "test.py", line 76, in add_handler
    self.app.router.add_route('GET', url, handler)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 823, in add_route
    resource = self.add_resource(path, name=name)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 787, in add_resource
    self.register_resource(resource)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 762, in register_resource
    "Cannot register a resource into frozen router.")
RuntimeError: Cannot register a resource into frozen router.

======================================================================
ERROR: test_non_html (__main__.TestCrawler)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test.py", line 322, in test_non_html
    self.add_page('/xml', body=body, content_type='application/xml')
  File "test.py", line 93, in add_page
    self.add_handler(url, handler)
  File "test.py", line 76, in add_handler
    self.app.router.add_route('GET', url, handler)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 823, in add_route
    resource = self.add_resource(path, name=name)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 787, in add_resource
    self.register_resource(resource)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 762, in register_resource
    "Cannot register a resource into frozen router.")
RuntimeError: Cannot register a resource into frozen router.

======================================================================
ERROR: test_non_http (__main__.TestCrawler)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test.py", line 333, in test_non_http
    self.add_page(body=body)
  File "test.py", line 93, in add_page
    self.add_handler(url, handler)
  File "test.py", line 76, in add_handler
    self.app.router.add_route('GET', url, handler)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 823, in add_route
    resource = self.add_resource(path, name=name)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 787, in add_resource
    self.register_resource(resource)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 762, in register_resource
    "Cannot register a resource into frozen router.")
RuntimeError: Cannot register a resource into frozen router.

======================================================================
ERROR: test_prohibited_host (__main__.TestCrawler)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test.py", line 152, in test_prohibited_host
    self.add_page('/', ['http://example.com'])
  File "test.py", line 93, in add_page
    self.add_handler(url, handler)
  File "test.py", line 76, in add_handler
    self.app.router.add_route('GET', url, handler)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 823, in add_route
    resource = self.add_resource(path, name=name)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 787, in add_resource
    self.register_resource(resource)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 762, in register_resource
    "Cannot register a resource into frozen router.")
RuntimeError: Cannot register a resource into frozen router.

======================================================================
ERROR: test_redirect (__main__.TestCrawler)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test.py", line 196, in test_redirect
    url = self.add_redirect('/', foo)
  File "test.py", line 101, in add_redirect
    self.add_handler(url, handler)
  File "test.py", line 76, in add_handler
    self.app.router.add_route('GET', url, handler)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 823, in add_route
    resource = self.add_resource(path, name=name)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 787, in add_resource
    self.register_resource(resource)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 762, in register_resource
    "Cannot register a resource into frozen router.")
RuntimeError: Cannot register a resource into frozen router.

======================================================================
ERROR: test_redirect_cycle (__main__.TestCrawler)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test.py", line 214, in test_redirect_cycle
    url = self.add_redirect('/bar', foo)
  File "test.py", line 101, in add_redirect
    self.add_handler(url, handler)
  File "test.py", line 76, in add_handler
    self.app.router.add_route('GET', url, handler)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 823, in add_route
    resource = self.add_resource(path, name=name)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 787, in add_resource
    self.register_resource(resource)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 762, in register_resource
    "Cannot register a resource into frozen router.")
RuntimeError: Cannot register a resource into frozen router.

======================================================================
ERROR: test_redirect_join (__main__.TestCrawler)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test.py", line 230, in test_redirect_join
    self.add_redirect('/foo', baz)
  File "test.py", line 101, in add_redirect
    self.add_handler(url, handler)
  File "test.py", line 76, in add_handler
    self.app.router.add_route('GET', url, handler)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 823, in add_route
    resource = self.add_resource(path, name=name)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 787, in add_resource
    self.register_resource(resource)
  File "C:\Users\Primary User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\web_urldispatcher.py", line 762, in register_resource
    "Cannot register a resource into frozen router.")
RuntimeError: Cannot register a resource into frozen router.

----------------------------------------------------------------------
Ran 17 tests in 0.034s

FAILED (errors=12)

C:\Users\Primary User\Desktop\500lines-master\crawler\code>

Body:
I am also learning it. I found this issue https://github.com/hangoutsbot/hangoutsbot/pull/655. Then code like this

@asyncio.coroutine
def _create_server(self):
    app = web.Application(loop=self.loop)
    return app

def add_handler(self, url, handler):
    self.app.router.add_route('GET', url, handler)
    handler_factory = self.app.make_handler(debug=True)
    srv = yield from self.loop.create_server(
        handler_factory, '127.0.0.1', self.port)

    # Prevent "Task destroyed but it is pending" warnings.
    self.addCleanup(lambda: self.loop.run_until_complete(
        handler_factory.finish_connections()))

    self.addCleanup(srv.close)

I think you should run crawl.py. Another problem, aiohttp 2.0.4 has no results after running for me. Using aiohttp 0.21 fixed it.


问:
jQuery File tree from remote Server
I am implementing a file tree in my website that fetches directory information over a remote source (ssh user@remote).

Currently my web page looks like this. The file tree is supposed to be in the left marked panel.

I have used the paramiko library to fetch the current list of directories.
However, I wish to display the directory information in a nice tree view format, like normal file explorers usually do.

Is there a jQuery file manager that incorporates the remote aspect? I don't wish to write an entire file tree from scratch because DRY

I have looked over jQuery file tree but it fails to achieve the remote purpose.

Any leads would be great.

答:
Incase someone stumbles upon this, I finally solved it using Fancy Tree Library that has a parameter source, which I can then refer to my AJAX :)

$(#fancytree).fancytree({
source: {
        url: "refreshDirectory"
    }});

Title: jQuery File tree from remote Server


问:
how to print reverse number pattern triangle in java
This is my code:

```<code>for (int i = 4; i >= 1; i--) {
    for (int j = 1; j < i; j++) {
        System.out.print(" ");
    }
    for (int k = i; k <= 4; k++) {
        System.out.print(k+"");
    }
    System.out.println();
}
</code>```

Current output:

```<code>   4
  34
 234
1234
</code>```

Desired output:

```<code>   1
  21
 321
4321
</code>```

What changes are necessary in order for me to get the desired output as shown above?

答:
for (int i = 1; i <= 4; i++)
{
  for (int k = i; k <= 4; k++)
   {
      System.out.print(" ");
   }
  for (int j = 1; j < i; j++)
   {
      System.out.print(j);
   }
    System.out.println();
 }```

Body:
This is my code:

for (int i = 4; i >= 1; i--) {
    for (int j = 1; j < i; j++) {
        System.out.print(" ");
    }
    for (int k = i; k <= 4; k++) {
        System.out.print(k+"");
    }
    System.out.println();
}

Current output:

   4
  34
 234
1234

Desired output:

   1
  21
 321
4321

What changes are necessary in order for me to get the desired output as shown above?