问:
SOA, TDD, DI & DDD - a shell game?
Okay, I'm going to try and go short and straight to the point.  I am trying to develop a loosely-coupled, multi-tier service application that is testable and supports dependency injection.  Here's what I have:

At the service layer, I have a StartSession method that accepts some key data required to, well, start the session.  My service class is a facade and delegates to an instance of the ISessionManager interface that is injected into the service class constructor.

I am using the Repository pattern in the data access layer.  So I have an ISessionRepository that my domain objects will work with and that I implement using the data access technology du jour.  ISessionRepository has methods for GetById, Add and Update.

Since my service class is just a facade, I think it is safe to say that my ISessionManager implementation is the actual service class in my architecture.  This class coordinates the operations with my Session domain/business object.  And here's where the shell game and problem comes in.

In my SessionManager class (the concrete ISessionManager), here's how I have StartSession implemented:

```<code>public ISession StartSession(object sessionStartInfo)
{
    var session = Session.GetSession(sessionStartInfo);

    if (session == null)
        session = Session.NewSession(sessionStartInfo);

    return session;
}
</code>```

I have three problems with this code:

First, obviously I could move this logic into a StartSession method in my Session class but I think that would defeat the purpose of the SessionManager class which then simply becomes a second facade (or is it still considered a coordinator?). Alas, the shell game.

Second, SessionManager has a tightly-coupled dependance upon the Session class.  I considered creating an ISessionFactory/SessionFactory that could be injected into SessionManager but then I'd have the same tight-coupling inside the factory.  But, maybe that's okay?

Finally, it seems to me that true DI and factory methods don't mix.  After all, we want to avoid "new"ing an instance of an object and let the container return the instance to us. And true DI says that we should not reference the container directly.  So, how then do I get the concrete ISessionRepository class injected into my Session domain object?  Do I have it injected into the factory class then manually pass it into Session when constructing a new instance (using "new")?

Keep in mind that this is also only one operation and I also need to perform other tasks such as saving a session, listing sessions based on various criteria plus work with other domain objects in my solution.  Plus, the Session object also encapsulates business logic for authorization, validation, etc. so (I think) it needs to be there.

The key to what I am looking to accomplish is not only functional but testable.  I am using DI to break dependencies so we can easily implement unit tests using mocks as well as give us the ability to make changes to the concrete implementations without requiring changes in multiple areas.

Can you help me wrap my head around the best practices for such a design and how I can best achieve my goals for a solid SOA, DDD and TDD solution?

UPDATE

I was asked to provide some additional code, so as succinctly as possible:

```<code>[ServiceContract()]
public class SessionService : ISessionService
{
    public SessionService(ISessionManager manager) { Manager = manager; }

    public ISessionManager Manager { get; private set; }

    [OperationContract()]
    public SessionContract StartSession(SessionCriteriaContract criteria)
    {
        var session = Manager.StartSession(Mapper.Map<SessionCriteria>(criteria));

        return Mapper.Map<SessionContract>(session);
    }
}

public class SessionManager : ISessionManager
{
    public SessionManager() { }

    public ISession StartSession(SessionCriteria criteria)
    {
        var session = Session.GetSession(criteria);

        if (session == null)
            session = Session.NewSession(criteria);

        return session;
    }
}

public class Session : ISession
{
    public Session(ISessionRepository repository, IValidator<ISession> validator)
    {
        Repository = repository;
        Validator = validator;
    }

    // ISession Properties

    public static ISession GetSession(SessionCriteria criteria)
    {
        return Repository.FindOne(criteria);
    }

    public static ISession NewSession(SessionCriteria criteria)
    {
        var session = ????;

        // Set properties based on criteria object

        return session;
    }

    public Boolean Save()
    {
        if (!Validator.IsValid(this))
            return false;

        return Repository.Save(this);
    }
}
</code>```

And, obviously, there is an ISessionRepository interface and concrete XyzSessionRepository class that I don't think needs to be shown.

2nd UPDATE

I added the IValidator dependency to the Session domain object to illustrate that there are other components in use.

答:
I thought I'd post the approach I ended up following while giving due credit above.

After reading some additional articles on DDD, I finally came across the observation that our domain objects should not be responsible for their creation or persistence as well as the notion that it is okay to "new" an instance of a domain object from within the Domain Layer (as Arnis eluded).

So, I retained my SessionManager class but renamed it SessionService so it would be clearer that it is a Domain Service (not to be confused with the SessionService in the facade layer).  It is now implemented like:

```<code>public class SessionService : ISessionService
{
    public SessionService(ISessionFactory factory, ISessionRepository repository)
    {
        Factory = factory;
        Repository = repository;
    }

    public ISessionFactory Factory { get; private set; }
    public ISessionRepository Repository { get; private set; }

    public ISession StartSession(SessionCriteria criteria)
    {
        var session = Repository.GetSession(criteria);

        if (session == null)
            session = Factory.CreateSession(criteria);
        else if (!session.CanResume)
            thrown new InvalidOperationException("Cannot resume the session.");

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

The Session class is now more of a true domain object only concerned with the state and logic required when working with the Session, such as the CanResume property shown above and validation logic.

The SessionFactory class is responsible for creating new instances and allows me to still inject the ISessionValidator instance provided by the container without directly referencing the container itself:

```<code>public class SessionFactory : ISessionFactory
{
    public SessionFactory(ISessionValidator validator)
    {
        Validator = validator;
    }

    public ISessionValidator Validator { get; private set; }

    public Session CreateSession(SessionCriteria criteria)
    {
        var session = new Session(Validator);

        // Map properties

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

Unless someone can point out a flaw in my approach, I'm pretty comfortable that this is consistent with DDD and gives me full support for unit testing, etc. - everything I was after.

ContentLicense: CC BY-SA 2.5

Title: SOA, TDD, DI & DDD - a shell game?

Body:
Okay, I'm going to try and go short and straight to the point.  I am trying to develop a loosely-coupled, multi-tier service application that is testable and supports dependency injection.  Here's what I have:

At the service layer, I have a StartSession method that accepts some key data required to, well, start the session.  My service class is a facade and delegates to an instance of the ISessionManager interface that is injected into the service class constructor.

I am using the Repository pattern in the data access layer.  So I have an ISessionRepository that my domain objects will work with and that I implement using the data access technology du jour.  ISessionRepository has methods for GetById, Add and Update.

Since my service class is just a facade, I think it is safe to say that my ISessionManager implementation is the actual service class in my architecture.  This class coordinates the operations with my Session domain/business object.  And here's where the shell game and problem comes in.

In my SessionManager class (the concrete ISessionManager), here's how I have StartSession implemented:

public ISession StartSession(object sessionStartInfo)
{
    var session = Session.GetSession(sessionStartInfo);

    if (session == null)
        session = Session.NewSession(sessionStartInfo);

    return session;
}

I have three problems with this code:

First, obviously I could move this logic into a StartSession method in my Session class but I think that would defeat the purpose of the SessionManager class which then simply becomes a second facade (or is it still considered a coordinator?). Alas, the shell game.

Second, SessionManager has a tightly-coupled dependance upon the Session class.  I considered creating an ISessionFactory/SessionFactory that could be injected into SessionManager but then I'd have the same tight-coupling inside the factory.  But, maybe that's okay?

Finally, it seems to me that true DI and factory methods don't mix.  After all, we want to avoid "new"ing an instance of an object and let the container return the instance to us. And true DI says that we should not reference the container directly.  So, how then do I get the concrete ISessionRepository class injected into my Session domain object?  Do I have it injected into the factory class then manually pass it into Session when constructing a new instance (using "new")?

Keep in mind that this is also only one operation and I also need to perform other tasks such as saving a session, listing sessions based on various criteria plus work with other domain objects in my solution.  Plus, the Session object also encapsulates business logic for authorization, validation, etc. so (I think) it needs to be there.

The key to what I am looking to accomplish is not only functional but testable.  I am using DI to break dependencies so we can easily implement unit tests using mocks as well as give us the ability to make changes to the concrete implementations without requiring changes in multiple areas.

Can you help me wrap my head around the best practices for such a design and how I can best achieve my goals for a solid SOA, DDD and TDD solution?

UPDATE

I was asked to provide some additional code, so as succinctly as possible:

[ServiceContract()]
public class SessionService : ISessionService
{
    public SessionService(ISessionManager manager) { Manager = manager; }

    public ISessionManager Manager { get; private set; }

    [OperationContract()]
    public SessionContract StartSession(SessionCriteriaContract criteria)
    {
        var session = Manager.StartSession(Mapper.Map<SessionCriteria>(criteria));

        return Mapper.Map<SessionContract>(session);
    }
}

public class SessionManager : ISessionManager
{
    public SessionManager() { }

    public ISession StartSession(SessionCriteria criteria)
    {
        var session = Session.GetSession(criteria);

        if (session == null)
            session = Session.NewSession(criteria);

        return session;
    }
}

public class Session : ISession
{
    public Session(ISessionRepository repository, IValidator<ISession> validator)
    {
        Repository = repository;
        Validator = validator;
    }

    // ISession Properties

    public static ISession GetSession(SessionCriteria criteria)
    {
        return Repository.FindOne(criteria);
    }

    public static ISession NewSession(SessionCriteria criteria)
    {
        var session = ????;

        // Set properties based on criteria object

        return session;
    }

    public Boolean Save()
    {
        if (!Validator.IsValid(this))
            return false;

        return Repository.Save(this);
    }
}

And, obviously, there is an ISessionRepository interface and concrete XyzSessionRepository class that I don't think needs to be shown.

2nd UPDATE

I added the IValidator dependency to the Session domain object to illustrate that there are other components in use.

Body:
I thought I'd post the approach I ended up following while giving due credit above.

After reading some additional articles on DDD, I finally came across the observation that our domain objects should not be responsible for their creation or persistence as well as the notion that it is okay to "new" an instance of a domain object from within the Domain Layer (as Arnis eluded).

So, I retained my SessionManager class but renamed it SessionService so it would be clearer that it is a Domain Service (not to be confused with the SessionService in the facade layer).  It is now implemented like:

public class SessionService : ISessionService
{
    public SessionService(ISessionFactory factory, ISessionRepository repository)
    {
        Factory = factory;
        Repository = repository;
    }

    public ISessionFactory Factory { get; private set; }
    public ISessionRepository Repository { get; private set; }

    public ISession StartSession(SessionCriteria criteria)
    {
        var session = Repository.GetSession(criteria);

        if (session == null)
            session = Factory.CreateSession(criteria);
        else if (!session.CanResume)
            thrown new InvalidOperationException("Cannot resume the session.");

        return session;
    }
}

The Session class is now more of a true domain object only concerned with the state and logic required when working with the Session, such as the CanResume property shown above and validation logic.

The SessionFactory class is responsible for creating new instances and allows me to still inject the ISessionValidator instance provided by the container without directly referencing the container itself:

public class SessionFactory : ISessionFactory
{
    public SessionFactory(ISessionValidator validator)
    {
        Validator = validator;
    }

    public ISessionValidator Validator { get; private set; }

    public Session CreateSession(SessionCriteria criteria)
    {
        var session = new Session(Validator);

        // Map properties

        return session;
    }
}

Unless someone can point out a flaw in my approach, I'm pretty comfortable that this is consistent with DDD and gives me full support for unit testing, etc. - everything I was after.


来源: stackexchange

问:
Export results from postman such that they can be viewed using tool other than postman(e.g browser, csv)
I am currently testing APIs used in my tool using Postman Collections. I am able to see the current & previous results in the Recent Runs section. However there is no way to track this or export this outside postman. I would like to be able to export these results in a format such that another person without Postman can also view the results (say in a browser).

I have been using newman and the export feature in Newman which allows me to export the test results in a csv or html format.However I would like to know if such feature exists in Postman. Also where would I be able to find the program data for Postman in case I need to write a custom reporting module.

答:
Actually there is no Feature like this in newman.
But: In Postman Runner you can export your results in a JSON Format. And In the Postman Client you can save your responses if needed.</p>

ContentLicense: CC BY-SA 4.0


问:
Html Table Button Taking too much space
I want make two buttons sit next to each other within the same cell. How can I go about that without having alot space in the cell. Only Enough space to have the buttons sit in comfortable space between each other.

I have used display: inline-block; as well as display:block and style='white-space: nowrap'. Have looked at similar questions and their answers don't work with my project.

    Employee Name
    Email Address
    Action

    Johnny Depp
    hotdog69@gmail.com

      <button type="button">Add</button>
      <button type="button">Edit</button>

```

When one or two buttons are present within a cell, they create this super long horizontal cell. The buttons are also far apart from each other.

答: Turns out a button's style was controlling all the buttons in my project. I should have given that button an id so it wouldn't control all the buttons in a general sense.</p>

Title: Html Table Button Taking too much space

Body:
I want make two buttons sit next to each other within the same cell. How can I go about that without having alot space in the cell. Only Enough space to have the buttons sit in comfortable space between each other.

I have used display: inline-block; as well as display:block and style='white-space: nowrap'. Have looked at similar questions and their answers don't work with my project.

    Employee Name
    Email Address
    Action

    Johnny Depp
    hotdog69@gmail.com

      <button type="button">Add</button>
      <button type="button">Edit</button>

When one or two buttons are present within a cell, they create this super long horizontal cell. The buttons are also far apart from each other.


问:
It's possible to integrate reactive Spring Data with mysql?
In the past, I integrated reactive spring data with mongoDb and everything gone fine.
Now I want the same non blocking access using mysql, but i didnt find any article about it.
I wish to use a mature and standard spring library, if you know one, please share it to me.</p>

答:
What you are looking for is R2DBC and Spring Data R2DBC.

R2DBC is a reactive alternative to JDBC.
And Spring Data R2DBC is a Spring Data module for it.

Since R2DBC is only a specification/API you also need a driver for the database of your choice. For MySql that would be https://github.com/jasync-sql/jasync-sql


问:
Mock cookies attribute of requests.session
Session.cookies is defined inside the Session constructor and thus I can't mock it. Is there any way to mock it?

```<code>from requests import Session
from settings import URL
from unittest.mock import patch

@patch.object(Session, 'cookies', new='my custom mock object')
def test_request():
    assert function_that_uses_request_cookies()
</code>```

This raises AttributeError: <class 'requests.sessions.Session'> does not have the attribute 'cookies'

If session instance was defined on the module scope, I could patch the session instance directly. But session is defined only on function_that_uses_request_cookies scope. Is there any way to patch the instance inside the function scope?

答:
As written, the code will patch an attribute of the Session class, but what you want to do is patch an attribute of a Session instance. To do this without interrupting other aspects of session behaviour, you can create a mock object that wraps Session.

def test_request():
    mock_session_klass = MagicMock(wraps=Session)
    with patch('requests.Session', new=mock_session_klass):
        session_instance = mock_session_klass.return_value
        session_instance.cookies.return_value = 'my custom mock object'
        assert function_that_uses_request_cookies()
```

Body:
Session.cookies is defined inside the Session constructor and thus I can't mock it. Is there any way to mock it?

from requests import Session
from settings import URL
from unittest.mock import patch

@patch.object(Session, 'cookies', new='my custom mock object')
def test_request():
    assert function_that_uses_request_cookies()

This raises AttributeError: <class 'requests.sessions.Session'> does not have the attribute 'cookies'

If session instance was defined on the module scope, I could patch the session instance directly. But session is defined only on function_that_uses_request_cookies scope. Is there any way to patch the instance inside the function scope?


问:
How to get the list of child of child in firebase?
I am trying to make an arraylist of firebase child. Here is my json data:

```<code>{

  "Posts" : {

    "4dBtdsgxgMdWahQKLW3dfZ3QYnv110-05-201909:19:00 PM" : {

      "location" : "",
      "postimg" : {
            "0":"http://something.com"
            "1":"http://something.com"
            "2":"http://something.com"
            },
      "uid" : "4dBtdsgxgMdWahQKLW3dfZ3QYnv1"
    },
    "4dBtdsgxgMdWahQKLW3dfZ3QYnv110-05-201909:28:48 PM" : {
      "location" : "",
      "postimg" : {
            "0":"http://something.com"
            "1":"http://something.com"
            },
      "uid" : "4dBtdsgxgMdWahQKLW3dfZ3QYnv1"
    },

    "jOt0sDoVvwcse3yTbpByxnrX2xy224-05-201912:29:14 AM" : {

      "location" : "",
      "postimg" : {
            "0":"http://something.com"
            "1":"http://something.com"
            "2":"http://something.com"
            "3":"http://something.com"
            },
      "uid" : "jOt0sDoVvwcse3yTbpByxnrX2xy2"
    },
    "jOt0sDoVvwcse3yTbpByxnrX2xy228-05-201902:15:20 AM" : {

      "location" : "",
     "postimg" : {
            "0":"http://something.com"
            "1":"http://something.com"
            },
      "uid" : "jOt0sDoVvwcse3yTbpByxnrX2xy2"
    },
    "jOt0sDoVvwcse3yTbpByxnrX2xy229-05-201912:27:16 AM" : {

      "location" : "",
     "postimg" : {
            "0":"http://something.com"
            "1":"http://something.com"
            },
      "uid" : "jOt0sDoVvwcse3yTbpByxnrX2xy2"
    },

  },
}
</code>```

Now i want to make arraylist of postimg child of specific uid of Posts node.

Suppose CurrentUserId is jOt0sDoVvwcse3yTbpByxnrX2xy2.

```<code>    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    //Returning the layout file after inflating
    //Change R.layout.tab1 in you classes
    View view  =  inflater.inflate(R.layout.photos_user_fragment_tab, null);

    mAuth=FirebaseAuth.getInstance();
    CurrentUserId=mAuth.getCurrentUser().getUid();
    UserRef=FirebaseDatabase.getInstance().getReference().child("Users").child(CurrentUserId);

    PostRef=FirebaseDatabase.getInstance().getReference().child("Posts");
    final List<ImageView> imageViewList = new ArrayList<>();
    imageViewList.add(firstPhoto);
    imageViewList.add(secondPhoto);
    imageViewList.add(thirdPhoto);

    PostRef.orderByChild("uid").equalTo(CurrentUserId).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot)
        {

            ArrayList<String> list = new ArrayList<>();
                for (DataSnapshot ing : dataSnapshot.child("postimg").getChildren())
                {
                    list.add(ing.getValue().toString());
                }

            int index = 0;
            for(ImageView imageView : imageViewList) {
                if (index == list.size()) break;
                Picasso.get().load(list.get(index)).into(imageView);
                index++;
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

    return view;
}
</code>```

How can I fix this?

答:
Your app is crashing because if list is empty then there is no position for get() method.

You should either check if list has valid length and then fill the imageViews, but then you can have 1 image, 2 images, 3 or more, so you could think for some workaround, e.g. create list of imageViews to fill into.

```<code>List<ImageView> imageViewList = new ArrayList<>();
imageViewList.add(firstPhoto);
imageViewList.add(secondPhoto);
imageViewList.add(thirdPhoto);

for (DataSnapshot childDataSnapshot: dataSnapshot.getChildren()) {
    ArrayList <String> list = new ArrayList<>();
    for (DataSnapshot ing: childDataSnapshot.child("postimg").getChildren()) {
        list.add(ing.getValue().toString());
    }

    int index = 0;
    for(ImageView imageView : imageViewList) {
        if(index == list.size()) break;
        Picasso.get().load(list.get(index)).into(imageView);
        index++;
    }
}
</code>```

But again, remember that if there will be 4 images and you will have 3 imageViews there will be crash as there won't be fourth item in the imageViewList

Body:
I am trying to make an arraylist of firebase child. Here is my json data:

{

  "Posts" : {

    "4dBtdsgxgMdWahQKLW3dfZ3QYnv110-05-201909:19:00 PM" : {

      "location" : "",
      "postimg" : {
            "0":"http://something.com"
            "1":"http://something.com"
            "2":"http://something.com"
            },
      "uid" : "4dBtdsgxgMdWahQKLW3dfZ3QYnv1"
    },
    "4dBtdsgxgMdWahQKLW3dfZ3QYnv110-05-201909:28:48 PM" : {
      "location" : "",
      "postimg" : {
            "0":"http://something.com"
            "1":"http://something.com"
            },
      "uid" : "4dBtdsgxgMdWahQKLW3dfZ3QYnv1"
    },

    "jOt0sDoVvwcse3yTbpByxnrX2xy224-05-201912:29:14 AM" : {

      "location" : "",
      "postimg" : {
            "0":"http://something.com"
            "1":"http://something.com"
            "2":"http://something.com"
            "3":"http://something.com"
            },
      "uid" : "jOt0sDoVvwcse3yTbpByxnrX2xy2"
    },
    "jOt0sDoVvwcse3yTbpByxnrX2xy228-05-201902:15:20 AM" : {

      "location" : "",
     "postimg" : {
            "0":"http://something.com"
            "1":"http://something.com"
            },
      "uid" : "jOt0sDoVvwcse3yTbpByxnrX2xy2"
    },
    "jOt0sDoVvwcse3yTbpByxnrX2xy229-05-201912:27:16 AM" : {

      "location" : "",
     "postimg" : {
            "0":"http://something.com"
            "1":"http://something.com"
            },
      "uid" : "jOt0sDoVvwcse3yTbpByxnrX2xy2"
    },

  },
}

Now i want to make arraylist of postimg child of specific uid of Posts node.

Suppose CurrentUserId is jOt0sDoVvwcse3yTbpByxnrX2xy2.

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

    //Returning the layout file after inflating
    //Change R.layout.tab1 in you classes
    View view  =  inflater.inflate(R.layout.photos_user_fragment_tab, null);

    mAuth=FirebaseAuth.getInstance();
    CurrentUserId=mAuth.getCurrentUser().getUid();
    UserRef=FirebaseDatabase.getInstance().getReference().child("Users").child(CurrentUserId);

    PostRef=FirebaseDatabase.getInstance().getReference().child("Posts");
    final List<ImageView> imageViewList = new ArrayList<>();
    imageViewList.add(firstPhoto);
    imageViewList.add(secondPhoto);
    imageViewList.add(thirdPhoto);

    PostRef.orderByChild("uid").equalTo(CurrentUserId).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot)
        {

            ArrayList<String> list = new ArrayList<>();
                for (DataSnapshot ing : dataSnapshot.child("postimg").getChildren())
                {
                    list.add(ing.getValue().toString());
                }

            int index = 0;
            for(ImageView imageView : imageViewList) {
                if (index == list.size()) break;
                Picasso.get().load(list.get(index)).into(imageView);
                index++;
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

    return view;
}

How can I fix this?

Body:
Your app is crashing because if list is empty then there is no position for get() method.

You should either check if list has valid length and then fill the imageViews, but then you can have 1 image, 2 images, 3 or more, so you could think for some workaround, e.g. create list of imageViews to fill into.

List<ImageView> imageViewList = new ArrayList<>();
imageViewList.add(firstPhoto);
imageViewList.add(secondPhoto);
imageViewList.add(thirdPhoto);

for (DataSnapshot childDataSnapshot: dataSnapshot.getChildren()) {
    ArrayList <String> list = new ArrayList<>();
    for (DataSnapshot ing: childDataSnapshot.child("postimg").getChildren()) {
        list.add(ing.getValue().toString());
    }

    int index = 0;
    for(ImageView imageView : imageViewList) {
        if(index == list.size()) break;
        Picasso.get().load(list.get(index)).into(imageView);
        index++;
    }
}

But again, remember that if there will be 4 images and you will have 3 imageViews there will be crash as there won't be fourth item in the imageViewList


问:
What's the prognosis for Bluetooth device support in the emulator?
It's pretty clear that the current emulator does not provide Bluetooth support.  While there appears to be a third-party emulator available that might work it seems to come with warnings about bugs that tend to suggest that I might be better off spending my energies elsewhere.  Does anyone know of progress, and perhaps even a target, for getting Bluetooth support built into the device emulator in the Android SDK Tools?</p>

答:
There is a workaround available though that lets you utilize your computers bluetooth and still have the benefits of debugging on the spot, so to say.

You can install a virtual machine android and have it use your onboard bluetooth. There is a readily installed image for this available, just google it. You can then have adb connect to this device as you would with any other real or virtual device, it is also described if you look it up on the net. I hope this helps.

Still, build in bluetooth support is something I would love the emulator to get enhanced by.

ContentLicense: CC BY-SA 3.0


问:
Global timer for all users
How would you go about creating a global timer all users use? Such as a tournament and every 24 hours the timer resets. How would you make all users see the same time and not base it off the client side?

I'd think to use a service like playfab or app42, but how would this work through them anyway?

Thanks

答:
Since there is no code here im gonna tell you the how to but you will need to do research in order to achieve it probably.

You can have a time span in your server, and every time a user logs in you send the time span since the server started to run minus the time that the server has been running, and the client starts running its own timer taking into account that time span.

Im assuming you are working with a client server model here.

Title: Global timer for all users


问:
How to open a PdfADocument from an existing PdfDocument in itext7?
In order to check uploaded PDF files for basic PDF/A conformance, I need to read them in as PdfADocuments.
But starting with version 7.1.6 this no longer works, but throws a PdfException(PdfException.PdfReaderHasBeenAlreadyUtilized)

```<code>class Controller
...
// get uploaded data into PdfDocument, which is passed
// on to different services.

InputStream filecontent = fileupload.getInputStream();
int read = 0;
byte[] bytes = new byte[1024];
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
while ((read = filecontent.read(bytes,0,bytes.length)) != -1) {
    filesize += read;
    buffer.write(bytes, 0, read);
}

ByteArrayInputStream input = new ByteArrayInputStream(buffer.toByteArray());
PdfReader reader = new PdfReader(input);
PdfWriter writer = new PdfWriter(new ByteArrayOutputStream());

PdfDocument pdf = new PdfDocument(reader, writer);

AnalyzerService analyzer = new AnalyzerService();
if(analyzer.analyze(pdf)) {
    otherService.doSomethingWith(pdf);
}
...
</code>```

```<code>class AnalyzerService
...
public boolean analyze(PdfDocument pdf) {
    PdfADocument pdfa = new PdfADocument(
        pdf.getReader(), pdf.getWriter() <-- PdfException here
    );
...
}
</code>```

Up to and including iText 7.1.5 this worked.

With 7.1.6 I get "com.itextpdf.kernel.PdfException: Given PdfReader instance has already been utilized. The PdfReader cannot be reused, please create a new instance."

It seems that I need to get the Bytes from the PdfDocument as a byte[], then create a new PdfReader from it. I have tried getting them from the pdf.getReader().getOutputStream().toByteArray(), but that doesn't work.

I'm quite lost at the moment on how to create that PdfADocument from the given PdfDocument.

答:
Your approach uses the same PdfReader and (even worse) the same PdfWriter for both a PdfDocument and a PdfADocument instance. As both can manipulate the PdfReader and write to the PdfWriter, that situation is likely to result in garbage in the writer, so you shall not do this.

Simply always consider a document with both a reader and a writer as work-in-progress, something one cannot treat as a finished document file, e.g. extract for intermediary checks.

As you want to check uploaded PDF files, why don't you simply forward the byte[] from buffer.toByteArray() to the analyze method to create a separate reader (and, if need be, a document) from? This indeed exactly would check the uploaded file...

Furthermore, if your input document may be PDF/A conform and is treated specially in that case, shouldn't you also manipulate it as a PdfADocument if it is? I.e. shouldn't you first check in your analyzer for conformance and in the positive case use a PdfADocument for it also in your controller class?

Body:
In order to check uploaded PDF files for basic PDF/A conformance, I need to read them in as PdfADocuments.
But starting with version 7.1.6 this no longer works, but throws a PdfException(PdfException.PdfReaderHasBeenAlreadyUtilized)

class Controller
...
// get uploaded data into PdfDocument, which is passed
// on to different services.

InputStream filecontent = fileupload.getInputStream();
int read = 0;
byte[] bytes = new byte[1024];
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
while ((read = filecontent.read(bytes,0,bytes.length)) != -1) {
    filesize += read;
    buffer.write(bytes, 0, read);
}

ByteArrayInputStream input = new ByteArrayInputStream(buffer.toByteArray());
PdfReader reader = new PdfReader(input);
PdfWriter writer = new PdfWriter(new ByteArrayOutputStream());

PdfDocument pdf = new PdfDocument(reader, writer);

AnalyzerService analyzer = new AnalyzerService();
if(analyzer.analyze(pdf)) {
    otherService.doSomethingWith(pdf);
}
...

class AnalyzerService
...
public boolean analyze(PdfDocument pdf) {
    PdfADocument pdfa = new PdfADocument(
        pdf.getReader(), pdf.getWriter() <-- PdfException here
    );
...
}

Up to and including iText 7.1.5 this worked.

With 7.1.6 I get "com.itextpdf.kernel.PdfException: Given PdfReader instance has already been utilized. The PdfReader cannot be reused, please create a new instance."

It seems that I need to get the Bytes from the PdfDocument as a byte[], then create a new PdfReader from it. I have tried getting them from the pdf.getReader().getOutputStream().toByteArray(), but that doesn't work.

I'm quite lost at the moment on how to create that PdfADocument from the given PdfDocument.


问:
Flex box rendering like a column when it should be a row
I am putting together what should be a simple nav bar and styling with flex box. For some reason, instead of displaying as a row (horizontal), it is showing as a column (vertical).

I can make the links go horizontal using float:left, but then they don't stretch evenly to fill the nav bar.

My understanding is that flex-grow:1 should make each item occupy an equal amount of space. But this is not happening.

There are four declarations that are not working as expected:

flex-direction The links within the nav bar are in a column instead of a row

padding Although the nav bar's padding is set to zero, it still appears to have padding

text-align The text within each
 is not getting horizontally centered

flex-grow The links are not spacing out evenly

I'm not sure if they are all stemming from to one problem, or each separate problems.

Here is a simplified snippet:

<!doctype html>

<meta charset="utf-8">
<title>Curse of the Nav Bar</title>

Once

Upon

A Time

There

Was

A Problematic

Nav Bar

```

I've used flex box plenty of times before, but never seen it behave like this.

答:
You can try giving display: flex to nav ul as well.

```<code>nav ul {
    display: flex;
}
</code>```

Now the Items are appearing in a row instead of a column.
By default, ul is block element so the display will be block for ul.

Body:
I am putting together what should be a simple nav bar and styling with flex box. For some reason, instead of displaying as a row (horizontal), it is showing as a column (vertical).

I can make the links go horizontal using float:left, but then they don't stretch evenly to fill the nav bar.

My understanding is that flex-grow:1 should make each item occupy an equal amount of space. But this is not happening.

There are four declarations that are not working as expected:

flex-direction The links within the nav bar are in a column instead of a row

padding Although the nav bar's padding is set to zero, it still appears to have padding

text-align The text within each
 is not getting horizontally centered

flex-grow The links are not spacing out evenly

I'm not sure if they are all stemming from to one problem, or each separate problems.

Here is a simplified snippet:

<!doctype html>

<meta charset="utf-8">
<title>Curse of the Nav Bar</title>

Once

Upon

A Time

There

Was

A Problematic

Nav Bar

I've used flex box plenty of times before, but never seen it behave like this.

Body:
You can try giving display: flex to nav ul as well.

nav ul {
    display: flex;
}

Now the Items are appearing in a row instead of a column.
By default, ul is block element so the display will be block for ul.


问:
How to check whether tasks in io_service are completed?
I have a question about boost::io_service.

I have a set of tasks that I can run concurrently. After running all of them, I need to run another set of tasks concurrently. However first set has to be completed before starting to run the second set. This means I need to make sure that all the jobs submitted to io_service is completed before starting to schedule to second set.

I can implement it by keeping some kind of counter and add a busy loop but it does not look very efficient. So, I wanted to checked whether someone has a better idea or not. Following is a dummy code that I was using to experiment.

Thank you in advance!

 #include <cstdio>
 #include <iostream>
 #include <unistd.h>
 #include <boost/asio/io_service.hpp>
 #include <boost/bind.hpp>
 #include <boost/thread/thread.hpp>

 const size_t numTasks = 100000;

 void print_counter(const size_t id)
 {
   if (id + 1 == numTasks) {
     printf("sleeping for %ld\n", id);
     sleep(15);
   }
   printf("%ld\n", id);
 }

 int main(int argc, char** argv)
 {
   using namespace std;
   using namespace boost;

   asio::io_service io_service;
   asio::io_service::work work(io_service);

   const size_t numWorker = 4;
   boost::thread_group workers;
   for(size_t i = 0; i < numWorker; ++i) {
     workers.create_thread(boost::bind(&asio::io_service::run, &io_service));
   }

   for(size_t i = 0; i < numTasks; ++i) {
     io_service.post(boost::bind(print_counter, i));
   }

   // TODO: wait until all the tasks are done above

   for(size_t i = 0; i < numTasks; ++i) {
     io_service.post(boost::bind(print_counter, i));
   }

   // TODO: wait until all the tasks are done above

   // ...

   // Finally stop the service
   io_service.stop();
   workers.join_all();
   return 0;
 }
```

答:
Your main problem is that all sets of your tasks are processed by the same instance of io_service. Function io_service::run returns where there is no tasks to be processed. Destructor of io_service::work informs io_service object that run can return where there are no pending tasks in queue to be performed. You can post all tasks from first set, then destroyed work and wait until io_service::run returns, then create again work object, post tasks from the next set and delete work, and so on. To do it just write helper class which may look like something below:

```<code>class TasksWaiter
{
public:
    TasksWaiter(int numOfThreads)
    {
        work = std::make_unique<boost::asio::io_service::work>(io_service);
        for(size_t i = 0; i < numOfThreads; ++i) {
            workers.create_thread(boost::bind(&boost::asio::io_service::run, &io_service));
        }
    }

    ~TasksWaiter() {
        work.reset();
        workers.join_all();
    }

    template<class F>
    void post(F f) {
        io_service.post(f);
    }

    boost::thread_group workers;
    boost::asio::io_service io_service;
    std::unique_ptr<boost::asio::io_service::work> work;
};

int main()
{
    {
        TasksWaiter w1{4};
        for (int i = 0; i < numTasks; ++i)
            w1.post(boost::bind(print_counter,i));
        // work in w1 is destroyed, then io_service::run ends
        // when there are no tasks to be performed
    }
    printf("wait here");
    {
        TasksWaiter w1{4};
        for (int i = 0; i < numTasks; ++i)
            w1.post(boost::bind(print_counter,i));
    }
}
</code>```

a few remarks:

in constructor pool of threads are created

in destructor work is deleted, so io_service::run returns only if there are no pending tasks

functionality of destructor can be wrapped into a member function - e.g. wait, then you don't have to use {} scope to wait for your tasks.

Body:
Your main problem is that all sets of your tasks are processed by the same instance of io_service. Function io_service::run returns where there is no tasks to be processed. Destructor of io_service::work informs io_service object that run can return where there are no pending tasks in queue to be performed. You can post all tasks from first set, then destroyed work and wait until io_service::run returns, then create again work object, post tasks from the next set and delete work, and so on. To do it just write helper class which may look like something below:

class TasksWaiter
{
public:
    TasksWaiter(int numOfThreads)
    {
        work = std::make_unique<boost::asio::io_service::work>(io_service);
        for(size_t i = 0; i < numOfThreads; ++i) {
            workers.create_thread(boost::bind(&boost::asio::io_service::run, &io_service));
        }
    }

    ~TasksWaiter() {
        work.reset();
        workers.join_all();
    }

    template<class F>
    void post(F f) {
        io_service.post(f);
    }

    boost::thread_group workers;
    boost::asio::io_service io_service;
    std::unique_ptr<boost::asio::io_service::work> work;
};

int main()
{
    {
        TasksWaiter w1{4};
        for (int i = 0; i < numTasks; ++i)
            w1.post(boost::bind(print_counter,i));
        // work in w1 is destroyed, then io_service::run ends
        // when there are no tasks to be performed
    }
    printf("wait here");
    {
        TasksWaiter w1{4};
        for (int i = 0; i < numTasks; ++i)
            w1.post(boost::bind(print_counter,i));
    }
}

a few remarks:

in constructor pool of threads are created

in destructor work is deleted, so io_service::run returns only if there are no pending tasks

functionality of destructor can be wrapped into a member function - e.g. wait, then you don't have to use {} scope to wait for your tasks.


问:
How to delete line from CSV as they are read in Bash
I am currently doing this:

```<code>while read l
do
  echo git add $l/
  git add $l/
  # sed -i -e '1,1d' data/commit-folders.csv
  # echo git commit -am "'Autocommit'"
  # git commit -uno -am "'Autocommit'"
  # echo git push origin master
  # git push origin master
done < data/commit-folders.csv
</code>```

Essentially just git add <folder> for a list of folders in a CSV file. I would like for this to be more robust, in that every time it restarts it restarts from where it left off. So I added that commented out line which does an in-place delete sed -i -e '1,1d' data/commit-folders.csv. However, with while read line, it messes up with the current line if they are being deleted. So I'm wondering how to do this properly.

How to iterate through a CSV file with <path> on each line, and delete the path once it is successfully git added. It seems like you need to have a loop that selects the first line from a file, and then deletes it from the file afterwards, rather than using while read line.

答:
Here a solution without sed. </p>

```<code>#!/bin/bash
csv="data/commit-folders.csv"
done="$(mktemp)"

# autoremove tempfile at exit
trap 'rm "$done"' EXIT

# loop over all lines in csv
while read -r file; do
   printf "git add %s\n" "$file"
   git add "$file"

   # write processed files in tempfile
   printf "%s\n" "$file" >> "$done"

   #...
done < "$csv"

# create tempfile for merge result
newfile="$(mktemp)"

# sort: merge and sort $cvs with $done
# uniq -u: write only unique files into tempfile
sort "$csv" "$done" | uniq -u > "$newfile"

# override $csv with tempfile
mv "$newfile" "$csv"
</code>```

Body:
I am currently doing this:

while read l
do
  echo git add $l/
  git add $l/
  # sed -i -e '1,1d' data/commit-folders.csv
  # echo git commit -am "'Autocommit'"
  # git commit -uno -am "'Autocommit'"
  # echo git push origin master
  # git push origin master
done < data/commit-folders.csv

Essentially just git add <folder> for a list of folders in a CSV file. I would like for this to be more robust, in that every time it restarts it restarts from where it left off. So I added that commented out line which does an in-place delete sed -i -e '1,1d' data/commit-folders.csv. However, with while read line, it messes up with the current line if they are being deleted. So I'm wondering how to do this properly.

How to iterate through a CSV file with <path> on each line, and delete the path once it is successfully git added. It seems like you need to have a loop that selects the first line from a file, and then deletes it from the file afterwards, rather than using while read line.

Body:
Here a solution without sed.

#!/bin/bash
csv="data/commit-folders.csv"
done="$(mktemp)"

# autoremove tempfile at exit
trap 'rm "$done"' EXIT

# loop over all lines in csv
while read -r file; do
   printf "git add %s\n" "$file"
   git add "$file"

   # write processed files in tempfile
   printf "%s\n" "$file" >> "$done"

   #...
done < "$csv"

# create tempfile for merge result
newfile="$(mktemp)"

# sort: merge and sort $cvs with $done
# uniq -u: write only unique files into tempfile
sort "$csv" "$done" | uniq -u > "$newfile"

# override $csv with tempfile
mv "$newfile" "$csv"


答:
use the flex to ul not nav(You have to set flex to the wrap DOM of you elements you want them to flex)

I think better to use ul and  immediately li not a(ul li a)

ul {
  display: flex;
  flex-direction: row;
  background-color: #d2d6d6;
  padding: 0;
}

nav li {
  display: flex;
  text-decoration: none;
  list-style: none;
  border: 2px solid #727171;
  color: #727171;
  background-color: #c4c4c4;
  padding: 4px;
  margin: 2px;
  text-align: center;
  flex-grow: 1;
}

nav a:hover,
nav a:active {
  background-color: #aaa;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
  <ul>
    <li>
      Once
    </li>
           <li>
      Once
    </li>
    <li>
      Once
    </li>
    <li>
      Once
    </li>
    <li>
      Once
    </li>
  </ul>
</nav></code>```

Title: Flex box rendering like a column when it should be a row

Body:
use the flex to ul not nav(You have to set flex to the wrap DOM of you elements you want them to flex)

I think better to use ul and  immediately li not a(ul li a)

ul {
  display: flex;
  flex-direction: row;
  background-color: #d2d6d6;
  padding: 0;
}

nav li {
  display: flex;
  text-decoration: none;
  list-style: none;
  border: 2px solid #727171;
  color: #727171;
  background-color: #c4c4c4;
  padding: 4px;
  margin: 2px;
  text-align: center;
  flex-grow: 1;
}

nav a:hover,
nav a:active {
  background-color: #aaa;
}

<nav>
  <ul>
    <li>
      <a href="#">Once</a>
    </li>
           <li>
      <a href="#">Once</a>
    </li>
    <li>
      <a href="#">Once</a>
    </li>
    <li>
      <a href="#">Once</a>
    </li>
    <li>
      <a href="#">Once</a>
    </li>
  </ul>
</nav>


问:
How ASP.NET reports UploadProgress?
Based on this question and answer
ASP.NET Core 2.0 and Angular 4.3 File Upload with progress

ASP.NET returns HTTP events - upload progress and final response:

```<code>[HttpPost, DisableRequestSizeLimit, Route("api/files")]
public async Task UploadFiles()
{
    var files = Request.Form.Files; // now you have them
}
</code>```

And Angular accepts the response(s) and handles that:

```<code>this.http.request(req).subscribe(event => {
            if (event.type === HttpEventType.UploadProgress)
                this.uploadProgress = Math.round(100 * event.loaded / event.total);
            else if (event instanceof HttpResponse)
                console.log('Files uploaded!');
        });
</code>```

My questions:

1) What part of the above ASP.NET code tells that it has to respond UploadProgress until the upload process is done? How does it know that it is a request that needs to respond the UploadProgress? Where is the code in the ASP.NET source code, that return UploadProgress? (https://github.com/aspnet/AspNetCore)

2) Overall flow, is this an HTTP specification? Clearly, there is a rule and I can't find any documentation about it so far.

答:
What part of the above ASP.NET code tells that it has to respond UploadProgress

None of it. ASP.NET Core doesn't do this.

HttpPost indicates that you want to accept data in the form of a POST request.

DisableRequestSizeLimit indicates that you don't want ASP.NET Core to block file uploads over the pre-defined limit (30 MB, I believe).

Route defines the URL for the route.

Overall flow, is this an HTTP specification? Clearly, there is a rule and I can't find any documentation about it so far.

No, it isn't. It's not necessary. The client knows how much data it has successfully sent, and this is where progress comes from.

The Angular HTTP library is built around XMLHttpRequest, which has a Progress event:

The progress event handler, specified by the updateProgress() function in this example, receives the total number of bytes to transfer as well as the number of bytes transferred so far in the event's total and loaded fields. However, if the lengthComputable field is false, the total length is not known and will be zero.

Progress events exist for both download and upload transfers. The download events are fired on the XMLHttpRequest object itself, as shown in the above sample. The upload events are fired on the XMLHttpRequest.upload object...

So the Angular HTTP library just hooks into the progress events of the local request object, and then provides them to you in a neater way.

Title: How ASP.NET reports UploadProgress?

Body:
Based on this question and answer
ASP.NET Core 2.0 and Angular 4.3 File Upload with progress

ASP.NET returns HTTP events - upload progress and final response:

[HttpPost, DisableRequestSizeLimit, Route("api/files")]
public async Task UploadFiles()
{
    var files = Request.Form.Files; // now you have them
}

And Angular accepts the response(s) and handles that:

this.http.request(req).subscribe(event => {
            if (event.type === HttpEventType.UploadProgress)
                this.uploadProgress = Math.round(100 * event.loaded / event.total);
            else if (event instanceof HttpResponse)
                console.log('Files uploaded!');
        });

My questions:

1) What part of the above ASP.NET code tells that it has to respond UploadProgress until the upload process is done? How does it know that it is a request that needs to respond the UploadProgress? Where is the code in the ASP.NET source code, that return UploadProgress? (https://github.com/aspnet/AspNetCore)

2) Overall flow, is this an HTTP specification? Clearly, there is a rule and I can't find any documentation about it so far.


问:
How to fix ' Not all arguments converted during string formatting? '
I am learning python. while doing an exercise, i encountered a problem

Python TypeError: not all arguments converted during string formatting

I tried to refer and change the code but nothing worked well.

```<code>my_list=input(list)
for num in my_list:
    if(num%2==0):
        print(f"{num} is even number")
    else:
        print(f'{num} is odd number')
</code>```

I expected the output should be either num is even number or num is odd number for every number in the list. Unfortunately I get the error message above.

How can I fix this?

答:
```<code>my_list=map(int, input().split())
for num in my_list:
    if(num%2==0):
        print(f"{num} is even number")
    else:
        print(f'{num} is odd number')
</code>```

<p>give the input space seperated integers for eg : "1 2 3 4" without quotes. The output should be as expected.
The error is probably due to the input format which you might be giving in list for mat i.e "[1,2,3,4]" which not implicitly decoded by string formatting in python. To input list of numbers you might want to use the way i have mentioned in the code. </p>

Body:
I am learning python. while doing an exercise, i encountered a problem

Python TypeError: not all arguments converted during string formatting

I tried to refer and change the code but nothing worked well.

my_list=input(list)
for num in my_list:
    if(num%2==0):
        print(f"{num} is even number")
    else:
        print(f'{num} is odd number')

I expected the output should be either num is even number or num is odd number for every number in the list. Unfortunately I get the error message above.

How can I fix this?

Body:
my_list=map(int, input().split())
for num in my_list:
    if(num%2==0):
        print(f"{num} is even number")
    else:
        print(f'{num} is odd number')

give the input space seperated integers for eg : "1 2 3 4" without quotes. The output should be as expected.
The error is probably due to the input format which you might be giving in list for mat i.e "[1,2,3,4]" which not implicitly decoded by string formatting in python. To input list of numbers you might want to use the way i have mentioned in the code.


问:
return data as SqlDataReader
I am working on an ASP.NET project. I have a stored procedure in SQL Server which returns a list of data to show in a chart. This stored procedure works fine. I need the return data to be a SqlDataReader object to pass into the Chart.DataBindTable.

I call the stored procedure like this:

```<code>string spName = "spFetchDetails";
DbCommand dbCommand = this.ObjDatabase.GetStoredProcCommand(spName);
this.ObjDatabase.AddInParameter(dbCommand, "@Company", DbType.Int32, Company);
this.ObjDatabase.AddInParameter(dbCommand, "@Title", DbType.String, Title);
this.ObjDatabase.AddInParameter(dbCommand, "@DateRange", DbType.String, DateRange);

DataTable dt = new DataTable();
dt = this.ObjDatabase.ExecuteDataSet(dbCommand).Tables[0];
</code>```

Here the code is returning the stored procedure result as a DataTable, I want to call ExecuteReader() method, but I am not sure how to do that.

```<code>Chart.DataBindTable(dt, "Example");
</code>```

This is the code to render the chart.

Below is how I do in another chart and it is working.

```<code>SqlCommand cmd = new SqlCommand(
  "Select ai.ItemDescription, ai.ItemRate, los.sellingprice, los.mrp from aitem ai inner join losShopItemShipmentDetail los on los.itemid = ai.itemid", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();

Chart.DataBindTable(rdr, "ItemDescription");
</code>```

How do I call a stored procedure this way? or is there a way to pass the DataTable into DataBindTable function?

```<code>public void DataBindTable (System.Collections.IEnumerable dataSource, string xField);
</code>```

答:
You could try this (sample code to visualise how to use it):</p>

```<code>Chart c = new Chart();
DataTable dt = new DataTable();
c.DataBindTable(dt.AsEnumerable());
</code>```

Title: return data as SqlDataReader

Body:
I am working on an ASP.NET project. I have a stored procedure in SQL Server which returns a list of data to show in a chart. This stored procedure works fine. I need the return data to be a SqlDataReader object to pass into the Chart.DataBindTable.

I call the stored procedure like this:

string spName = "spFetchDetails";
DbCommand dbCommand = this.ObjDatabase.GetStoredProcCommand(spName);
this.ObjDatabase.AddInParameter(dbCommand, "@Company", DbType.Int32, Company);
this.ObjDatabase.AddInParameter(dbCommand, "@Title", DbType.String, Title);
this.ObjDatabase.AddInParameter(dbCommand, "@DateRange", DbType.String, DateRange);

DataTable dt = new DataTable();
dt = this.ObjDatabase.ExecuteDataSet(dbCommand).Tables[0];

Here the code is returning the stored procedure result as a DataTable, I want to call ExecuteReader() method, but I am not sure how to do that.

Chart.DataBindTable(dt, "Example");

This is the code to render the chart.

Below is how I do in another chart and it is working.

SqlCommand cmd = new SqlCommand(
  "Select ai.ItemDescription, ai.ItemRate, los.sellingprice, los.mrp from aitem ai inner join losShopItemShipmentDetail los on los.itemid = ai.itemid", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();

Chart.DataBindTable(rdr, "ItemDescription");

How do I call a stored procedure this way? or is there a way to pass the DataTable into DataBindTable function?

public void DataBindTable (System.Collections.IEnumerable dataSource, string xField);

Body:
You could try this (sample code to visualise how to use it):

Chart c = new Chart();
DataTable dt = new DataTable();
c.DataBindTable(dt.AsEnumerable());


问:
I am making a game like Crossy Roads on Unity, the problem is, why the player fly away
Basically, when the player hit an obstacle going up, the game generates a lane, its ok, the problem is: if he hit the obstacle 3 times, go to the side and jump up without hitting an obstacle, the player will jump 4 lanes instead of 1...

I tried to destroy the next lane when the player hit an obstacle and tried to cancel the movement, but its sens to crash or bug the game.

internal void SpawnNewStrip()
{
    int stripsPrefabCount = poolOfStripsPrefabs.Length;
    int randomNumber = Random.Range (0, stripsPrefabCount);

    GameObject item = poolOfStripsPrefabs [randomNumber] as GameObject;

    Transform itemChildTransform = item.transform.GetChild(0) as Transform;
    Transform itemChildOfChildTranform = itemChildTransform.GetChild (0) as Transform;

    float itemWidth = itemChildOfChildTranform.gameObject.GetComponent<Renderer> ().bounds.size.x;

    GameObject lastStrip = strips [strips.Count - 1] as GameObject;

    GameObject newStrip = Instantiate (item, lastStrip.transform.position, lastStrip.transform.rotation) as GameObject;
    newStrip.transform.position = new Vector3 (newStrip.transform.position.x -  itemWidth, newStrip.transform.position.y, newStrip.transform.position.z);
        strips.Add (newStrip);
}

internal void JumpUp()
{
    if(gameIsPlaying == false)
            return;

    stripsCurrentIndex += 1;

    if (stripsCurrentIndex > indexOfTheHighestRoadStrip)
    {
        Score += 1;
        scoreText.text = "Score: " + Score.ToString();
        indexOfTheHighestRoadStrip = stripsCurrentIndex;
        Debug.Log("new  score: " + indexOfTheHighestRoadStrip.ToString());
    }

    GameObject nextStrip = strips [stripsCurrentIndex] as GameObject;

    JumpTargetLocation = new Vector3 (nextStrip.transform.position.x - jumpOffsetX, transform.position.y, transform.position.z);
    midWayPointX = JumpTargetLocation.x + ((this.transform.position.x - JumpTargetLocation.x) / 2);

    mesh.transform.localEulerAngles = new Vector3 (0, 180, 0);

    SpawnNewStrip();

    float distanceX = this.transform.position.x - JumpTargetLocation.x;
    BoundaryLeft.transform.position -= new Vector3 (distanceX, 0, 0);
    BoundaryRight.transform.position -= new Vector3 (distanceX, 0, 0);
}

internal void JumpDown()
{
    if(gameIsPlaying == false)
        return;

    stripsCurrentIndex -= 1;

    if (stripsCurrentIndex < 0)
    {
        stripsCurrentIndex = 0;
        return;
    }

    GameObject previousStrip = strips [stripsCurrentIndex] as GameObject;

    JumpTargetLocation = new Vector3 (previousStrip.transform.position.x - jumpOffsetX, transform.position.y, transform.position.z);
    midWayPointX = JumpTargetLocation.x - ((JumpTargetLocation.x - this.transform.position.x) / 2);

    mesh.transform.localEulerAngles = new Vector3 (0, 0, 0);

    float distanceX = JumpTargetLocation.x - this.transform.position.x;
    BoundaryLeft.transform.position += new Vector3 (distanceX, 0, 0);
    BoundaryRight.transform.position += new Vector3 (distanceX, 0, 0);
}
```

Just want the player to jump normally after hitting an obstacle.

答:
So when jumping you increment stripsCurrentIndex with one. This however isn't decremented if you hit an obstacle. Meaning that if you are at a stripCurrentIndex = 0 and jump into an obstacle three times, it will set stripCurrentIndex = 3. Even though your position haven't changed. Then when you jump to the side and jump up you retrieve the strip from stripCurrentIndex = 4. Thus you will jump four spaces.

So you will have to either decrement the index when hitting an obstacle, like so.

```<code>if (isJumpingUp)
{
    offsetUpDown = 2.5f;
    stripCurrentIndex -= 1;
}

else if (isJumpingDown)
{
    offsetUpDown = -2.5f;
    stripsCurrentIndex += 1;
}
</code>```

Alternately refactor your code so that the index is incremented only after you've actually reached the position. In a "Set target" - "Do actual movement" - "Increment index" fashion.

Body:
Basically, when the player hit an obstacle going up, the game generates a lane, its ok, the problem is: if he hit the obstacle 3 times, go to the side and jump up without hitting an obstacle, the player will jump 4 lanes instead of 1...

I tried to destroy the next lane when the player hit an obstacle and tried to cancel the movement, but its sens to crash or bug the game.

internal void SpawnNewStrip()
{
    int stripsPrefabCount = poolOfStripsPrefabs.Length;
    int randomNumber = Random.Range (0, stripsPrefabCount);

    GameObject item = poolOfStripsPrefabs [randomNumber] as GameObject;

    Transform itemChildTransform = item.transform.GetChild(0) as Transform;
    Transform itemChildOfChildTranform = itemChildTransform.GetChild (0) as Transform;

    float itemWidth = itemChildOfChildTranform.gameObject.GetComponent<Renderer> ().bounds.size.x;

    GameObject lastStrip = strips [strips.Count - 1] as GameObject;

    GameObject newStrip = Instantiate (item, lastStrip.transform.position, lastStrip.transform.rotation) as GameObject;
    newStrip.transform.position = new Vector3 (newStrip.transform.position.x -  itemWidth, newStrip.transform.position.y, newStrip.transform.position.z);
        strips.Add (newStrip);
}

internal void JumpUp()
{
    if(gameIsPlaying == false)
            return;

    stripsCurrentIndex += 1;

    if (stripsCurrentIndex > indexOfTheHighestRoadStrip)
    {
        Score += 1;
        scoreText.text = "Score: " + Score.ToString();
        indexOfTheHighestRoadStrip = stripsCurrentIndex;
        Debug.Log("new  score: " + indexOfTheHighestRoadStrip.ToString());
    }

    GameObject nextStrip = strips [stripsCurrentIndex] as GameObject;

    JumpTargetLocation = new Vector3 (nextStrip.transform.position.x - jumpOffsetX, transform.position.y, transform.position.z);
    midWayPointX = JumpTargetLocation.x + ((this.transform.position.x - JumpTargetLocation.x) / 2);

    mesh.transform.localEulerAngles = new Vector3 (0, 180, 0);

    SpawnNewStrip();

    float distanceX = this.transform.position.x - JumpTargetLocation.x;
    BoundaryLeft.transform.position -= new Vector3 (distanceX, 0, 0);
    BoundaryRight.transform.position -= new Vector3 (distanceX, 0, 0);
}

internal void JumpDown()
{
    if(gameIsPlaying == false)
        return;

    stripsCurrentIndex -= 1;

    if (stripsCurrentIndex < 0)
    {
        stripsCurrentIndex = 0;
        return;
    }

    GameObject previousStrip = strips [stripsCurrentIndex] as GameObject;

    JumpTargetLocation = new Vector3 (previousStrip.transform.position.x - jumpOffsetX, transform.position.y, transform.position.z);
    midWayPointX = JumpTargetLocation.x - ((JumpTargetLocation.x - this.transform.position.x) / 2);

    mesh.transform.localEulerAngles = new Vector3 (0, 0, 0);

    float distanceX = JumpTargetLocation.x - this.transform.position.x;
    BoundaryLeft.transform.position += new Vector3 (distanceX, 0, 0);
    BoundaryRight.transform.position += new Vector3 (distanceX, 0, 0);
}

Just want the player to jump normally after hitting an obstacle.

Body:
So when jumping you increment stripsCurrentIndex with one. This however isn't decremented if you hit an obstacle. Meaning that if you are at a stripCurrentIndex = 0 and jump into an obstacle three times, it will set stripCurrentIndex = 3. Even though your position haven't changed. Then when you jump to the side and jump up you retrieve the strip from stripCurrentIndex = 4. Thus you will jump four spaces.

So you will have to either decrement the index when hitting an obstacle, like so.

if (isJumpingUp)
{
    offsetUpDown = 2.5f;
    stripCurrentIndex -= 1;
}

else if (isJumpingDown)
{
    offsetUpDown = -2.5f;
    stripsCurrentIndex += 1;
}

Alternately refactor your code so that the index is incremented only after you've actually reached the position. In a "Set target" - "Do actual movement" - "Increment index" fashion.


问:
Dictionary type in TypeScript
In a few places in my application, I'm declaring a dictionary types, like:

```<code>interface MyInterface {
    data: { [key: string]: Item };
}
</code>```

Is there in TypeScript any built-in shorthand for the dictionaries/maps, to get something similar to:

```<code>interface MyInterface {
    data: Dict<Item>;
}
</code>```

答:
We can try with built-in typescript advanced type called Record<K, T>. Here is official documentation https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type

```<code>interface MyInterface {
    data: Record<string, Item>;
}
</code>```

Put everything together here

```<code>interface Item {
    id: string;
    name: string;
}

interface MyInterface {
    data: Record<string, Item>;
}

const obj: MyInterface = {
    data: {
        "123": { id: "123", name: "something" }
    }
};
</code>```

Title: Dictionary type in TypeScript

Body:
In a few places in my application, I'm declaring a dictionary types, like:

interface MyInterface {
    data: { [key: string]: Item };
}

Is there in TypeScript any built-in shorthand for the dictionaries/maps, to get something similar to:

interface MyInterface {
    data: Dict<Item>;
}

Body:
We can try with built-in typescript advanced type called Record<K, T>. Here is official documentation https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type

interface MyInterface {
    data: Record<string, Item>;
}

Put everything together here

interface Item {
    id: string;
    name: string;
}

interface MyInterface {
    data: Record<string, Item>;
}

const obj: MyInterface = {
    data: {
        "123": { id: "123", name: "something" }
    }
};


问:
How to use jQuery Template to select option?
I'm working with form that contain select element. I need to fill select with the data coming via json format. How to use jquery template to fill the select element?

I read about jquery template, it's documentation. But still can't get right result.

2 question: Is it good way to use jQuery Template for big data, for example: 4000 columns?

    <select id="sel"></select>

```

```    var options = [
    { code: "1", title: "A" },
    { code: "2", title: "B" },
    { code: "3", title: "C" },
    { code: "4", title: "D" },
    { code: "5", title: "E" },
    ];
    $('#optionTmpl').tmpl(options).appendTo('#sel');
```

答:
If your json format is fixed from server side then you can try this.

```<code>var options = [
{ code: "1", title: "A" },
{ code: "2", title: "B" },
{ code: "3", title: "C" },
{ code: "4", title: "D" },
{ code: "5", title: "E" },
];
$.each(options , function(i, obj){
   $('#select').append($('<option>').text(obj.title).attr('value', obj.code));
});
</code>```

we can also append the json to the input type select field if the key and value are same like this.

Reference : https://jocapc.github.io/jquery-view-engine/

```<code> var options = [ "A" ,"B" ,"C" ,"D"];
          $('#myselect').view(json);
</code>```

Body:
I'm working with form that contain select element. I need to fill select with the data coming via json format. How to use jquery template to fill the select element?

I read about jquery template, it's documentation. But still can't get right result.

2 question: Is it good way to use jQuery Template for big data, for example: 4000 columns?

    <select id="sel"></select>

    var options = [
    { code: "1", title: "A" },
    { code: "2", title: "B" },
    { code: "3", title: "C" },
    { code: "4", title: "D" },
    { code: "5", title: "E" },
    ];
    $('#optionTmpl').tmpl(options).appendTo('#sel');

Body:
If your json format is fixed from server side then you can try this.

var options = [
{ code: "1", title: "A" },
{ code: "2", title: "B" },
{ code: "3", title: "C" },
{ code: "4", title: "D" },
{ code: "5", title: "E" },
];
$.each(options , function(i, obj){
   $('#select').append($('<option>').text(obj.title).attr('value', obj.code));
});

we can also append the json to the input type select field if the key and value are same like this.

Reference : https://jocapc.github.io/jquery-view-engine/

 var options = [ "A" ,"B" ,"C" ,"D"];
          $('#myselect').view(json);


问:
Custom Pipe failing conditionals that work fine in a method
I have a custom pipe that returns a string based on a few conditions but for some reason it is always returning the first even if the conditional is not met in the component.

I have made a method with the identical if/else statements and it works find there

```<code>  transform(orderType: String, completed: Boolean, requestType: String): any{
    if (completed && orderType !== 'web') {
      console.log('1');
      return 'not web';
    } else if (completed && orderType === 'web')  {
      console.log('2');
      return 'web';
    } else {
      return 'N/A';
    }
  }
</code>```

Below is where I am calling it:

```<code>     {{ this.orderType| getOrderType: this.order.requestType: this.completed}} {{this.order.requestType}}
</code>```

I have the requestType and completed console.logging in the console and it is logging what it should be.

So it is passing if even though it is equal to web and returning not web

答:
The order of parameter or wrong,pass the completed before requestType as you are capturing in this order in class</p>

```<code>{{ this.orderType| getOrderType: this.completed:this.order.requestType}} {{this.order.requestType}}
</code>```

Body:
I have a custom pipe that returns a string based on a few conditions but for some reason it is always returning the first even if the conditional is not met in the component.

I have made a method with the identical if/else statements and it works find there

  transform(orderType: String, completed: Boolean, requestType: String): any{
    if (completed && orderType !== 'web') {
      console.log('1');
      return 'not web';
    } else if (completed && orderType === 'web')  {
      console.log('2');
      return 'web';
    } else {
      return 'N/A';
    }
  }

Below is where I am calling it:

     {{ this.orderType| getOrderType: this.order.requestType: this.completed}} {{this.order.requestType}}

I have the requestType and completed console.logging in the console and it is logging what it should be.

So it is passing if even though it is equal to web and returning not web

Body:
The order of parameter or wrong,pass the completed before requestType as you are capturing in this order in class

{{ this.orderType| getOrderType: this.completed:this.order.requestType}} {{this.order.requestType}}


问:
Handle exceptions caused by parsing nullable parameters in controller action
I have an endpoint

```<code>[HttpGet]
public async Task<ActionResult> GetNodes([FromQuery] Guid? parentId)
</code>```

And call it like that
GET .../api/nodes?parentId=null

Asp.net throws an exception when parsing parameter "The value 'null' is not valid."

How to override that behaviour to make it parse nullable types to null if an exception occurs?

I expect:

GET .../api/nodes?parentId=null should call action with parentId == null

GET .../api/nodes?parentId=50d21ddd-6a95-46db-bff9-c943cf5b0df1 should call action with parentId = "50d21ddd-6a95-46db-bff9-c943cf5b0df1"

GET .../api/nodes?parentId=something_not_parsable_to_guid should call action with parentId = null

答:
Convert you Guid parameter to string and then try with Guid.TryParse

```<code>[HttpGet]
public async Task<ActionResult> GetNodes([FromQuery] string parentId)
{
        Guid guid;
        if (Guid.TryParse(parentId, out guid))
        {
            // code when guid is not null.
            // use guid object.
        }
        else
        {
            // code when guid is null.
        }
}
</code>```

Body:
I have an endpoint

[HttpGet]
public async Task<ActionResult> GetNodes([FromQuery] Guid? parentId)

And call it like that
GET .../api/nodes?parentId=null

Asp.net throws an exception when parsing parameter "The value 'null' is not valid."

How to override that behaviour to make it parse nullable types to null if an exception occurs?

I expect:

GET .../api/nodes?parentId=null should call action with parentId == null

GET .../api/nodes?parentId=50d21ddd-6a95-46db-bff9-c943cf5b0df1 should call action with parentId = "50d21ddd-6a95-46db-bff9-c943cf5b0df1"

GET .../api/nodes?parentId=something_not_parsable_to_guid should call action with parentId = null

Body:
Convert you Guid parameter to string and then try with Guid.TryParse

[HttpGet]
public async Task<ActionResult> GetNodes([FromQuery] string parentId)
{
        Guid guid;
        if (Guid.TryParse(parentId, out guid))
        {
            // code when guid is not null.
            // use guid object.
        }
        else
        {
            // code when guid is null.
        }
}


问:
How to setup maven for two different projects with different profile
I have a Maven project setup successfully and executing as per requirement using eclipse.

Now I want to setup and execute another maven project with different profile from a different IDE(IntelliJ).

but as soon as I had added second project i started getting conflicts and errors in second project's pom.And I am not able to setup the second project.I tried multiple solutions and tricks, even deleted .m2 folder and then rebuilt the project but nothing works.

All these solutions only impacted 1st project (which I setup and built again and it is now working fine).

What should I do to get both projects work simultaneously?

Errors getting while trying to setup second project:

Failure to find com.WOW:parent:pom:2.0.0 in https://repo.maven.apache.org/maven2 was cached in the
local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced and 'parent.relativePath' points at wrong local POM

Note:

There is no problem with WOW, it is present on remote location.Same project has been successfully setup on another machine where it is the only project and no other maven project is present there.

答:
The normal layout for a maven multi module project is:

```<code>parent
├── pom.xml
├── module
    ├── pom.xml
</code>```

Check that you use this layout.

Additionally:

the relativePath looks strange. Instead of '..'

```<code><relativePath>..</relativePath>
</code>```

try '../' instead:

```<code><relativePath>../</relativePath>
</code>```

You can also remove relativePath if you use the standard layout. This is what I always do, and on the command line I can build as well the parent (and all modules) or only a single module.

The module path may be wrong. In the parent you define the module as:

```<code><module>junitcategorizer.cutdetection</module>
</code>```

You must specify the name of the folder of the child module, not an artifact identifier. If junitcategorizer.cutdetection is not the name of the folder than change it accordingly.

Hope that helps..

Body:
The normal layout for a maven multi module project is:

parent
├── pom.xml
├── module
    ├── pom.xml

Check that you use this layout.

Additionally:

the relativePath looks strange. Instead of '..'

<relativePath>..</relativePath>

try '../' instead:

<relativePath>../</relativePath>

You can also remove relativePath if you use the standard layout. This is what I always do, and on the command line I can build as well the parent (and all modules) or only a single module.

The module path may be wrong. In the parent you define the module as:

<module>junitcategorizer.cutdetection</module>

You must specify the name of the folder of the child module, not an artifact identifier. If junitcategorizer.cutdetection is not the name of the folder than change it accordingly.

Hope that helps..


问:
Getting started with WSO2 Enterprise Integrator
Our company(Enterprise) have planned to use WSO2(EI/ESB) products for our systems that connects with each other by P2P.
So we needed integration solution and chose WSO2.
I am asking that Is it good to use WSO2 for huge systems (Middlewares, Web services, Gateway etc).

Is WSO2 OK if there are a tons of request to handle?

Is there any WSO2 Training Course (On-Site and Online)

答:
Yes, you could use WSO2 EI to achieve your need. Currently all WSO2 products are proven to build large scale platforms. You can visit [1] and find out large scale users and their stories.

Is WSO2 OK if there are a tons of request to handle?

Yes, EI (ESB profile) capable of handling huge request load and it is proven for example in ebay "WSO2 ESB to Process More Than 1 Billion Transactions Per Day" and many more.

Is there any WSO2 Training Course (On-Site and Online)

Of cource, WSO2 provide online certification, onsite/online product training and self learning materials. Please find more information at [2]

[1] https://wso2.com/about/customers/

[2] https://wso2.com/training

Thanks,
Milinda


问:
macOS notarization error: "The signature algorithm used is too weak"
I wonder if anyone's familiar with this error which only happens when I upload my apps to Apple for notarization:

```<code>"AppName.zip/AppName.app/Contents/Resources/EWSMacCompress.tar.gz/EWSMacCompress.tar/EWSMac.framework/Versions/A/EWSMac83886082"
"The signature algorithm used is too weak."
</code>```

Additional info:

-I've been signing my apps for years with no issues. The error only happens when sending the apps for notarization.

-I submitted a bug back in November 2018, provided Apple all the info they asked for - but it was never addressed further.

-I recently contacted Apple again and they pointed me to some resource page that was last updated back in 2016. It briefly mentions a similar error - but still without any info on how to solve it:
https://developer.apple.com/library/archive/technotes/tn2206/_index.html#//apple_ref/doc/uid/DTS40007919-CH1-TNTAG301

-A search on this error didn't produce anything useful.

-The tar.gz file in question is an eSellerate licensing framework. As many people may know, it's been a popular licensing platform for Mac software for over a decade. While I switched to a different licensing platform some time ago, I still have thousands of customers with eSellerate licenses (as I'm sure is the situation with many other Mac developers).

As far as I understand, this whole situation has to do something with signing files inside tar.gz archives - on which I couldn't find any info either

Any help will be appreciated!

Thanks,
Leo

答:
You have to unpack your tar, zip or jar file, codesign all the files that have errors and repackage them.

Just go through the logs and codesign all of them with errors, and then sign the app as a whole.
For me, I use the following two commands.

```<code>find ./MyApp -type f \
 -exec codesign --timestamp \
 --keychain /Users/builduser/Library/Keychains/login.keychain-db \
 -s 'Developer ID Application: XXXXXXXX' -f --verbose=9 --deep \
 --options=runtime --entitlements entitlements.xml {} +
</code>```

and then sign the app

```<code>codesign --timestamp \
 --keychain /Users/builduser/Library/Keychains/login.keychain-db \
 -s 'Developer ID Application: XXXXXXXX' -f --verbose=9 --deep \
 --options=runtime --entitlements entitlements.xml MyApp
</code>```

You must run codesign with --options=runtime.
Here's a guide to notorization.

If you are building Java apps, these links might also be helpful:
How to build MacOS app with hardened runtime in AppBundler

https://bitbucket.org/infinitekind/appbundler/issues/39/build-with-hardened-runtime

Body:
I wonder if anyone's familiar with this error which only happens when I upload my apps to Apple for notarization:

"AppName.zip/AppName.app/Contents/Resources/EWSMacCompress.tar.gz/EWSMacCompress.tar/EWSMac.framework/Versions/A/EWSMac83886082"
"The signature algorithm used is too weak."

Additional info:

-I've been signing my apps for years with no issues. The error only happens when sending the apps for notarization.

-I submitted a bug back in November 2018, provided Apple all the info they asked for - but it was never addressed further.

-I recently contacted Apple again and they pointed me to some resource page that was last updated back in 2016. It briefly mentions a similar error - but still without any info on how to solve it:
https://developer.apple.com/library/archive/technotes/tn2206/_index.html#//apple_ref/doc/uid/DTS40007919-CH1-TNTAG301

-A search on this error didn't produce anything useful.

-The tar.gz file in question is an eSellerate licensing framework. As many people may know, it's been a popular licensing platform for Mac software for over a decade. While I switched to a different licensing platform some time ago, I still have thousands of customers with eSellerate licenses (as I'm sure is the situation with many other Mac developers).

As far as I understand, this whole situation has to do something with signing files inside tar.gz archives - on which I couldn't find any info either

Any help will be appreciated!

Thanks,
Leo

Body:
You have to unpack your tar, zip or jar file, codesign all the files that have errors and repackage them.

Just go through the logs and codesign all of them with errors, and then sign the app as a whole.
For me, I use the following two commands.

find ./MyApp -type f \
 -exec codesign --timestamp \
 --keychain /Users/builduser/Library/Keychains/login.keychain-db \
 -s 'Developer ID Application: XXXXXXXX' -f --verbose=9 --deep \
 --options=runtime --entitlements entitlements.xml {} +

and then sign the app

codesign --timestamp \
 --keychain /Users/builduser/Library/Keychains/login.keychain-db \
 -s 'Developer ID Application: XXXXXXXX' -f --verbose=9 --deep \
 --options=runtime --entitlements entitlements.xml MyApp

You must run codesign with --options=runtime.
Here's a guide to notorization.

If you are building Java apps, these links might also be helpful:
How to build MacOS app with hardened runtime in AppBundler

https://bitbucket.org/infinitekind/appbundler/issues/39/build-with-hardened-runtime


问:
Can Hive Joins be implemented in Apache Nifi?
I need to implement Hive Joins from Apache Nifi.

I found PutHiveQL, PutHiveStreaming and SelectHiveQL processors in Apache nifi, but was not able to find any use case regarding the Hive Joins implementation.

答:
If you are looking to join queries in Hive, you can just use those processors as usual with your join query statements.

However, if you are looking to use different regular queries and then join them inside NiFi, I would find it rather difficult(but possible with MergeRecord or MergeContent) because NiFi is not exactly built for joining queries.


问:
Is there any method to make ckedit read odf file directly?
I want to build an webOffice platform, which can read odf and save odf.
I found ckeditor is really good, however it save files in html, is there any way to let ckeditor read odf and edit odf file directly?

Many thanks!

答: No, you'll have to create something that transforms odf <-> html</p>


问:
Ho to use ftp_put for file upload in PHP?
I try to upload a file using ftp_put after submitting a form. However my code does not work as expected:

$ftpHost   = '192.168.180.36';
$ftpUsername = 'userdownload';
$ftpPassword = 'Toms!';
$filepath = "C://xampp/htdocs/Helpdesk/fmt/download";
$connId = ftp_connect($ftpHost,21) or die("Couldn't connect to $ftpHost");
$ftpLogin = ftp_login($connId, $ftpUsername, $ftpPassword);

$file_name = $_FILES['file']['name'][$i];
$tmp_name = $_FILES['file']['tmp_name'][$i];
// try to upload file
if(ftp_put($connId, $file_name, $filepath.'/'.$file_name, FTP_BINARY)){
    echo "File transfer successful - $file_name";
}else{
    echo "There was an error while uploading $file_name";
}
```

And I get this error message:

There was an error while uploading $file_name

答:
There are two thing i noticed in your code. the first one is the mode of transfer depends upon your file type.Files that are in the ascii/text file extension list are transferred as ascii, all other files are transferred as binary.The second one is may be there is a problem in your file which you received may be it is black first check that. You can try this code it is working for me.</p>

```<code>  <?php
    // connect and login to FTP server
    $ftp_server = "ftp.example.com";
    $ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
    $login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);

    $file = "localfile.txt";

    // upload file
    if (ftp_put($ftp_conn, "serverfile.txt", $file, FTP_ASCII))
      {
      echo "Successfully uploaded $file.";
      }
    else
      {
      echo "Error uploading $file.";
      }
    // close connection
    ftp_close($ftp_conn);
    ?>
</code>```

Body:
I try to upload a file using ftp_put after submitting a form. However my code does not work as expected:

$ftpHost   = '192.168.180.36';
$ftpUsername = 'userdownload';
$ftpPassword = 'Toms!';
$filepath = "C://xampp/htdocs/Helpdesk/fmt/download";
$connId = ftp_connect($ftpHost,21) or die("Couldn't connect to $ftpHost");
$ftpLogin = ftp_login($connId, $ftpUsername, $ftpPassword);

$file_name = $_FILES['file']['name'][$i];
$tmp_name = $_FILES['file']['tmp_name'][$i];
// try to upload file
if(ftp_put($connId, $file_name, $filepath.'/'.$file_name, FTP_BINARY)){
    echo "File transfer successful - $file_name";
}else{
    echo "There was an error while uploading $file_name";
}

And I get this error message:

There was an error while uploading $file_name

Body:
There are two thing i noticed in your code. the first one is the mode of transfer depends upon your file type.Files that are in the ascii/text file extension list are transferred as ascii, all other files are transferred as binary.The second one is may be there is a problem in your file which you received may be it is black first check that. You can try this code it is working for me.

  <?php
    // connect and login to FTP server
    $ftp_server = "ftp.example.com";
    $ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
    $login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);

    $file = "localfile.txt";

    // upload file
    if (ftp_put($ftp_conn, "serverfile.txt", $file, FTP_ASCII))
      {
      echo "Successfully uploaded $file.";
      }
    else
      {
      echo "Error uploading $file.";
      }
    // close connection
    ftp_close($ftp_conn);
    ?>


问:
IBM Watson Assistant: user input time frame validation
I am using IBM Watson Assistant and try to validate user input against time frames / spans. What function should I use?

I was using  @sys-date.before(now()) method to validate the time frame between past and present of a user input, but it does now work for me. If I input now or today Watson Assistant still thinks it is a past...

@sys-date.before(now()):

Looks "like you're trying to make a reservation in the past. Try again."
  true $day it is

I expect if user inputs now or today to make reservations work, and if user inputs time in the past to response as

"like you're trying to make a reservation in the past. Try again."

The code snippet in question looks like this:

```<code>{ "context":
    { "day": "@sys-date" } }
{ "context":
    { "time": "<? @sys-time.reformatDateTime('h:mm a') ?>" } }
</code>```

答:
With IBM Watson Assistant you can use systen entities @sys-date and @sys-time to turn user input into data / time values. And you can use expression language functions for date and time to evaluate and transform those values. It seems that you are already using both. Now it is up to the logic...

There are functions before and after, but also sameMoment or sameOrAfter and more for comparisons. If the user inputs today, it is not before now because both would refer to the same day and date. Are you looking for the time value to be before the current timestamp or before the current date? You would need to compare time to time or date to date. You can reformat the values to snip off the time component and turn them into dates.

For more fancy validations you could even use java.util.Date functionality.

This should be true if it is a past moment:

```<code>now.after(yourInput)
</code>```

Body:
I am using IBM Watson Assistant and try to validate user input against time frames / spans. What function should I use?

I was using  @sys-date.before(now()) method to validate the time frame between past and present of a user input, but it does now work for me. If I input now or today Watson Assistant still thinks it is a past...

@sys-date.before(now()):

Looks "like you're trying to make a reservation in the past. Try again."
  true $day it is

I expect if user inputs now or today to make reservations work, and if user inputs time in the past to response as

"like you're trying to make a reservation in the past. Try again."

The code snippet in question looks like this:

{ "context":
    { "day": "@sys-date" } }
{ "context":
    { "time": "<? @sys-time.reformatDateTime('h:mm a') ?>" } }

Body:
With IBM Watson Assistant you can use systen entities @sys-date and @sys-time to turn user input into data / time values. And you can use expression language functions for date and time to evaluate and transform those values. It seems that you are already using both. Now it is up to the logic...

There are functions before and after, but also sameMoment or sameOrAfter and more for comparisons. If the user inputs today, it is not before now because both would refer to the same day and date. Are you looking for the time value to be before the current timestamp or before the current date? You would need to compare time to time or date to date. You can reformat the values to snip off the time component and turn them into dates.

For more fancy validations you could even use java.util.Date functionality.

This should be true if it is a past moment:

now.after(yourInput)


问:
Volley bad URL - how to fix that?
I'm having a problem with java volley when I click login

```<code>  private void Login(){

    String url = "api.matraindonesia.com/login";
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            if (response.trim().equals("success")){
                Toast.makeText(getApplicationContext(),"Login Successfully!",Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(getApplicationContext(),"Login Failed!",Toast.LENGTH_LONG).show();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(getApplicationContext(),"this error:"+ error.toString(),Toast.LENGTH_LONG).show();
        }
    }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {

            Map<String, String> params = new HashMap<>();
            params.put("email",etEmail.getText().toString().trim());
            params.put("password",etPassword.getText().toString().trim());

            return super.getParams();
        }
    };
    requestQueue.add(stringRequest);
}
</code>```

com.android.volley.VolleyError: java.lang.RuntimeException: Bad URL

答:
you need to use http:// or https:// at the beginning or the url

```<code>String url = "http://api.matraindonesia.com/login";
</code>```

or  if your server is on SSL

```<code>String url = "https://api.matraindonesia.com/login";
</code>```

Edit (after your comment) :

typically MethodNotAllowedHttpException happen when, route method is not match.

Suppose you define POST request route file, but you sending GET Request to the route.

Title: Volley bad URL - how to fix that?

Body:
I'm having a problem with java volley when I click login

  private void Login(){

    String url = "api.matraindonesia.com/login";
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            if (response.trim().equals("success")){
                Toast.makeText(getApplicationContext(),"Login Successfully!",Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(getApplicationContext(),"Login Failed!",Toast.LENGTH_LONG).show();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(getApplicationContext(),"this error:"+ error.toString(),Toast.LENGTH_LONG).show();
        }
    }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {

            Map<String, String> params = new HashMap<>();
            params.put("email",etEmail.getText().toString().trim());
            params.put("password",etPassword.getText().toString().trim());

            return super.getParams();
        }
    };
    requestQueue.add(stringRequest);
}

com.android.volley.VolleyError: java.lang.RuntimeException: Bad URL

Body:
you need to use http:// or https:// at the beginning or the url

String url = "http://api.matraindonesia.com/login";

or  if your server is on SSL

String url = "https://api.matraindonesia.com/login";

Edit (after your comment) :

typically MethodNotAllowedHttpException happen when, route method is not match.

Suppose you define POST request route file, but you sending GET Request to the route.


问:
Sed - replace a part of line - a word in quotes
what I have:

```<code>property = "value"
</code>```

where value is a random string that I don't know the value of. What I want:

```<code>property = "new_value"
</code>```

Following dooes not work for me:

```<code>"s|property = \"*\"|property = \"new_value\"|g
</code>```

答:
The following replacement seems to work in Sed:

```<code>echo "property = \"value\"" | sed 's/"[^"]\+"/"new_value"/';
</code>```

This outputs:

```<code>property = "new_value"
</code>```

We match on the pattern "[^"]\+", and then replace with "new_value".

Body:
what I have:

property = "value"

where value is a random string that I don't know the value of. What I want:

property = "new_value"

Following dooes not work for me:

"s|property = \"*\"|property = \"new_value\"|g

Body:
The following replacement seems to work in Sed:

echo "property = \"value\"" | sed 's/"[^"]\+"/"new_value"/';

This outputs:

property = "new_value"

We match on the pattern "[^"]\+", and then replace with "new_value".


问:
logical problem for finding the probability
hi to all

 I want to know how to find the solution for this problem. consider in a Jar there are 10 papers numbered 1 to 10. we have to take 2 papers from that. what is the probability that 2 numbers are consecutive numbers.

答:
Your first choice has ten possible numbers.  8 of those 10 will have two consecutive numbers, while the other two only have 1.  Your second choice will be out of nine numbers.  So

(8/10 * 2/9) + (2/10 * 1/9) = 9/45 = 1/5


问:
Reading data form Elasticsearch into Flink aggregation?
I'm trying to update documents in Elasticsearch using Kafka messages (as a StreamSource). Writing to Elasticsearch in bulks using windows and the Elasticsearch connector as a sink is fine, however, we need to update existing data in the documents and read that in a bulk-performant manner (not for every tuple but for e.g. the whole window after a byKey() split that we want to aggregate over)

We are using Storm Trident right now which is performing bulk reads before a persistentAggregate and writes the updated aggregations back after, minimizing interaction with the backend. I just can't find something similar in Flink - any hints?

答:
How about running two window call on stream -

window1 - To bulk read from elasticsearch

window2 - To bulk into elasticsearch.

```<code>streamData
  .window1(bulkRead and update/join)
  .processFunction(...)
  .window2(BulkPush)
</code>```

You can use any suitable method for bulk-read like Storm Trident.

use BulkProcessor in window2 link

Body:
How about running two window call on stream -

window1 - To bulk read from elasticsearch

window2 - To bulk into elasticsearch.

streamData
  .window1(bulkRead and update/join)
  .processFunction(...)
  .window2(BulkPush)

You can use any suitable method for bulk-read like Storm Trident.

use BulkProcessor in window2 link