问:
XMPPFramework server feature
I'm trying to get server feature and XMPP configuration is:

```<code> _xmppCapabilitiesStorage = [XMPPCapabilitiesCoreDataStorage sharedInstance];
_xmppCapabilities = [[XMPPCapabilities alloc] initWithCapabilitiesStorage:_xmppCapabilitiesStorage];
_xmppCapabilities.autoFetchMyServerCapabilities = YES;
</code>```

the log says:

```<code>SEND:
<?xml version="1.0" encoding="utf-8"?>
<iq type="get" to="myserver.im" id="4FE37B35-8078-41B0-BCAF-DC6CFF04DD33">
    <query xmlns="http://jabber.org/protocol/disco#info"/>
</iq>
</code>```

RECV:

```<code><?xml version="1.0" encoding="utf-8"?>
<iq xmlns="jabber:client" type="result" id="4FE37B35-8078-41B0-BCAF-DC6CFF04DD33" from="myserver.im" to="3471@myserver.im/MyChatClient">
    <query xmlns="http://jabber.org/protocol/disco#info">
        <identity category="account" type="registered"/>
        <identity category="pubsub" type="pep"/>
        <feature var="http://jabber.org/protocol/pubsub#retrieve-default"/>
        <feature var="urn:myserver:im:groupchat#sync"/>
        <feature var="http://jabber.org/protocol/pubsub#purge-nodes"/>
        <feature var="vcard-temp"/>
        <feature var="http://jabber.org/protocol/pubsub#subscribe"/>
        <feature var="http://jabber.org/protocol/pubsub#subscription-options"/>
        <feature var="http://jabber.org/protocol/pubsub#create-nodes"/>
        <feature var="http://jabber.org/protocol/pubsub#outcast-affiliation"/>
        <feature var="http://jabber.org/protocol/pubsub#get-pending"/>
        <feature var="http://jabber.org/protocol/pubsub#multi-subscribe"/>
        <feature var="http://jabber.org/protocol/pubsub#presence-notifications"/>
        <feature var="urn:myserver:im:groupchat"/>
        <feature var="urn:xmpp:ping"/>
        <feature var="jabber:iq:register"/>
        <feature var="http://jabber.org/protocol/pubsub#delete-nodes"/>
        <feature var="urn:myserver:im:filetransfer"/>
        <feature var="http://jabber.org/protocol/pubsub#config-node"/>
        <feature var="http://jabber.org/protocol/pubsub#retrieve-items"/>
        <feature var="http://jabber.org/protocol/pubsub#auto-create"/>
        <feature var="http://jabber.org/protocol/disco#items"/>
        <feature var="http://jabber.org/protocol/pubsub#item-ids"/>
        <feature var="http://jabber.org/protocol/pubsub#meta-data"/>
        <feature var="jabber:iq:roster"/>
        <feature var="urn:xmpp:mam:1"/>
        <feature var="http://jabber.org/protocol/pubsub#instant-nodes"/>
        <feature var="http://jabber.org/protocol/pubsub#modify-affiliations"/>
        <feature var="http://jabber.org/protocol/pubsub#persistent-items"/>
        <feature var="http://jabber.org/protocol/pubsub#create-and-configure"/>
        <feature var="http://jabber.org/protocol/pubsub"/>
        <feature var="http://jabber.org/protocol/pubsub#publisher-affiliation"/>
        <feature var="http://jabber.org/protocol/pubsub#access-open"/>
        <feature var="http://jabber.org/protocol/pubsub#retrieve-affiliations"/>
        <feature var="jabber:iq:version"/>
        <feature var="http://jabber.org/protocol/pubsub#retract-items"/>
        <feature var="urn:xmpp:time"/>
        <feature var="http://jabber.org/protocol/pubsub#manage-subscriptions"/>
        <feature var="jabber:iq:privacy"/>
        <feature var="jabber:iq:last"/>
        <feature var="http://jabber.org/protocol/commands"/>
        <feature var="http://jabber.org/protocol/offline"/>
        <feature var="urn:xmpp:carbons:2"/>
        <feature var="http://jabber.org/protocol/address"/>
        <feature var="http://jabber.org/protocol/pubsub#publish"/>
        <feature var="http://jabber.org/protocol/pubsub#collections"/>
        <feature var="http://jabber.org/protocol/pubsub#retrieve-subscriptions"/>
        <feature var="http://jabber.org/protocol/disco#info"/>
        <feature var="jabber:iq:private"/>
        <feature var="http://jabber.org/protocol/rsm"/>
    </query>
</iq>
</code>```

how to check later on which feature does exist? I don't see any feature list in the XMPPCapabilities or XMPPCapabilitiesCoreDataStorage. Am I missing something? For example, I want to check whether <feature var="urn:myserver:im:filetransfer"/> does exist. Where does XMPPFramework save and hold list of features? any hint is much appreciated.

答:
Ok i have found out where the information are stored:</p>

```<code>NSManagedObjectContext *moc = [[XMPPCapabilitiesCoreDataStorage sharedInstance] mainThreadManagedObjectContext];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"XMPPCapsResourceCoreDataStorageObject"
                                                     inManagedObjectContext:moc];
NSFetchRequest *fetchRequest = [NSFetchRequest new];
[fetchRequest setEntity:entityDescription];
fetchRequest.fetchBatchSize = 30;
NSPredicate *filter = [NSPredicate predicateWithFormat:@"jidStr == %@", _domain];
fetchRequest.predicate = filter;
NSError *error = nil;
NSArray *features = [moc executeFetchRequest:fetchRequest error:&error];
NSArray *ch = [[[[features firstObject] caps] capabilities] children];
</code>```

Title: XMPPFramework server feature

Body:
I'm trying to get server feature and XMPP configuration is:

 _xmppCapabilitiesStorage = [XMPPCapabilitiesCoreDataStorage sharedInstance];
_xmppCapabilities = [[XMPPCapabilities alloc] initWithCapabilitiesStorage:_xmppCapabilitiesStorage];
_xmppCapabilities.autoFetchMyServerCapabilities = YES;

the log says:

SEND:
<?xml version="1.0" encoding="utf-8"?>
<iq type="get" to="myserver.im" id="4FE37B35-8078-41B0-BCAF-DC6CFF04DD33">
    <query xmlns="http://jabber.org/protocol/disco#info"/>
</iq>

RECV:

<?xml version="1.0" encoding="utf-8"?>
<iq xmlns="jabber:client" type="result" id="4FE37B35-8078-41B0-BCAF-DC6CFF04DD33" from="myserver.im" to="3471@myserver.im/MyChatClient">
    <query xmlns="http://jabber.org/protocol/disco#info">
        <identity category="account" type="registered"/>
        <identity category="pubsub" type="pep"/>
        <feature var="http://jabber.org/protocol/pubsub#retrieve-default"/>
        <feature var="urn:myserver:im:groupchat#sync"/>
        <feature var="http://jabber.org/protocol/pubsub#purge-nodes"/>
        <feature var="vcard-temp"/>
        <feature var="http://jabber.org/protocol/pubsub#subscribe"/>
        <feature var="http://jabber.org/protocol/pubsub#subscription-options"/>
        <feature var="http://jabber.org/protocol/pubsub#create-nodes"/>
        <feature var="http://jabber.org/protocol/pubsub#outcast-affiliation"/>
        <feature var="http://jabber.org/protocol/pubsub#get-pending"/>
        <feature var="http://jabber.org/protocol/pubsub#multi-subscribe"/>
        <feature var="http://jabber.org/protocol/pubsub#presence-notifications"/>
        <feature var="urn:myserver:im:groupchat"/>
        <feature var="urn:xmpp:ping"/>
        <feature var="jabber:iq:register"/>
        <feature var="http://jabber.org/protocol/pubsub#delete-nodes"/>
        <feature var="urn:myserver:im:filetransfer"/>
        <feature var="http://jabber.org/protocol/pubsub#config-node"/>
        <feature var="http://jabber.org/protocol/pubsub#retrieve-items"/>
        <feature var="http://jabber.org/protocol/pubsub#auto-create"/>
        <feature var="http://jabber.org/protocol/disco#items"/>
        <feature var="http://jabber.org/protocol/pubsub#item-ids"/>
        <feature var="http://jabber.org/protocol/pubsub#meta-data"/>
        <feature var="jabber:iq:roster"/>
        <feature var="urn:xmpp:mam:1"/>
        <feature var="http://jabber.org/protocol/pubsub#instant-nodes"/>
        <feature var="http://jabber.org/protocol/pubsub#modify-affiliations"/>
        <feature var="http://jabber.org/protocol/pubsub#persistent-items"/>
        <feature var="http://jabber.org/protocol/pubsub#create-and-configure"/>
        <feature var="http://jabber.org/protocol/pubsub"/>
        <feature var="http://jabber.org/protocol/pubsub#publisher-affiliation"/>
        <feature var="http://jabber.org/protocol/pubsub#access-open"/>
        <feature var="http://jabber.org/protocol/pubsub#retrieve-affiliations"/>
        <feature var="jabber:iq:version"/>
        <feature var="http://jabber.org/protocol/pubsub#retract-items"/>
        <feature var="urn:xmpp:time"/>
        <feature var="http://jabber.org/protocol/pubsub#manage-subscriptions"/>
        <feature var="jabber:iq:privacy"/>
        <feature var="jabber:iq:last"/>
        <feature var="http://jabber.org/protocol/commands"/>
        <feature var="http://jabber.org/protocol/offline"/>
        <feature var="urn:xmpp:carbons:2"/>
        <feature var="http://jabber.org/protocol/address"/>
        <feature var="http://jabber.org/protocol/pubsub#publish"/>
        <feature var="http://jabber.org/protocol/pubsub#collections"/>
        <feature var="http://jabber.org/protocol/pubsub#retrieve-subscriptions"/>
        <feature var="http://jabber.org/protocol/disco#info"/>
        <feature var="jabber:iq:private"/>
        <feature var="http://jabber.org/protocol/rsm"/>
    </query>
</iq>

how to check later on which feature does exist? I don't see any feature list in the XMPPCapabilities or XMPPCapabilitiesCoreDataStorage. Am I missing something? For example, I want to check whether <feature var="urn:myserver:im:filetransfer"/> does exist. Where does XMPPFramework save and hold list of features? any hint is much appreciated.

Body:
Ok i have found out where the information are stored:

NSManagedObjectContext *moc = [[XMPPCapabilitiesCoreDataStorage sharedInstance] mainThreadManagedObjectContext];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"XMPPCapsResourceCoreDataStorageObject"
                                                     inManagedObjectContext:moc];
NSFetchRequest *fetchRequest = [NSFetchRequest new];
[fetchRequest setEntity:entityDescription];
fetchRequest.fetchBatchSize = 30;
NSPredicate *filter = [NSPredicate predicateWithFormat:@"jidStr == %@", _domain];
fetchRequest.predicate = filter;
NSError *error = nil;
NSArray *features = [moc executeFetchRequest:fetchRequest error:&error];
NSArray *ch = [[[[features firstObject] caps] capabilities] children];


来源: stackexchange

问:
Parallel.Foreach + BackgroundWorker.ReportProgress
I am looking for feedback in case there are any known reasons I shouldn't do something like this: putting a ReportProgress within a Parallel foreach statement.  Are there any similar ways to achieve the same thing but are considered safer or better?

Code example:

```<code>        int iterations = 0;
        int count = items.Count;
        Parallel.ForEach(items, new ParallelOptions() { MaxDegreeOfParallelism = 5 }, item =>
        {
            iterations++;
            int percentComplete = (iterations/count) * 100;
            backgroundWorker.ReportProgress(percentComplete);
        };
</code>```

Additional info:

I have a Windows Form program that needs to do a specific task of managing items. Utilizing multi threading has made it much faster. However it needs to report to a progress bar on the form the overall progress completed so the end user doesn't wonder if the program frozen up. The overall job can take hours in some cases. So, having a progress bar is mandatory.

答:
I think it is not wise, and possibly not even allowed to let several threads communicate with the same BackGroundWorker.

If you have only a limited amount of threads, like 5 in your example, consider having each thread use its own BackgroundWorker that reports its own progress.

The receiver of all progress reports should upon receipt of a report decide about the actual progress and report it to those who are interested.

```<code>class MyLongProgress : IDisposable
{
     public MyLongProgress()
     {
         for (int i=0; i<maxNrOfParallelProcesses; ++i)
         {
             var createdBackGroundWorker = this.CreateBackGroundWorker();
             createdBackGroundWorker.ReportProgress += this.OnProgressReport;
             backGroundWorkers.Add(createdBackGroundWorker);
         }
     }
     // TODO: implement Disposable pattern that Disposes the background workers
     private readonly List<BackGroundWorker> backGroundWorkers = new List<BackGroundWorker>();

     public void StartLongProcess()
     {
         // start your long progress, which involves starting the backGroundWorkers
         // These backGroundWorkers will report progress via OnProgressReport
     }

     private void OnProgressReport(object sender, ...)
     {
         var myBackGroundWorker = (BackGroundWorker)sender;
         // calculate the actual progress using earlier received progress reports
         MyProgressReport report = ...
         OnReportProgress(report);
     }

     public event EventHandler<MyprogressReport> ReportProgrogress;

     protected virtual void OnReportProgress(MyProgressReport report)
     {
         this.ReportProgress?.Invoke(this, report);
     }
}
</code>```

Alternatively: create and dispose the BackGroundWorkers only during StartLongProcess. In that case you don't need IDisposable.

ContentLicense: CC BY-SA 3.0

Body:
I am looking for feedback in case there are any known reasons I shouldn't do something like this: putting a ReportProgress within a Parallel foreach statement.  Are there any similar ways to achieve the same thing but are considered safer or better?

Code example:

        int iterations = 0;
        int count = items.Count;
        Parallel.ForEach(items, new ParallelOptions() { MaxDegreeOfParallelism = 5 }, item =>
        {
            iterations++;
            int percentComplete = (iterations/count) * 100;
            backgroundWorker.ReportProgress(percentComplete);
        };

Additional info:

I have a Windows Form program that needs to do a specific task of managing items. Utilizing multi threading has made it much faster. However it needs to report to a progress bar on the form the overall progress completed so the end user doesn't wonder if the program frozen up. The overall job can take hours in some cases. So, having a progress bar is mandatory.

Body:
I think it is not wise, and possibly not even allowed to let several threads communicate with the same BackGroundWorker.

If you have only a limited amount of threads, like 5 in your example, consider having each thread use its own BackgroundWorker that reports its own progress.

The receiver of all progress reports should upon receipt of a report decide about the actual progress and report it to those who are interested.

class MyLongProgress : IDisposable
{
     public MyLongProgress()
     {
         for (int i=0; i<maxNrOfParallelProcesses; ++i)
         {
             var createdBackGroundWorker = this.CreateBackGroundWorker();
             createdBackGroundWorker.ReportProgress += this.OnProgressReport;
             backGroundWorkers.Add(createdBackGroundWorker);
         }
     }
     // TODO: implement Disposable pattern that Disposes the background workers
     private readonly List<BackGroundWorker> backGroundWorkers = new List<BackGroundWorker>();

     public void StartLongProcess()
     {
         // start your long progress, which involves starting the backGroundWorkers
         // These backGroundWorkers will report progress via OnProgressReport
     }

     private void OnProgressReport(object sender, ...)
     {
         var myBackGroundWorker = (BackGroundWorker)sender;
         // calculate the actual progress using earlier received progress reports
         MyProgressReport report = ...
         OnReportProgress(report);
     }

     public event EventHandler<MyprogressReport> ReportProgrogress;

     protected virtual void OnReportProgress(MyProgressReport report)
     {
         this.ReportProgress?.Invoke(this, report);
     }
}

Alternatively: create and dispose the BackGroundWorkers only during StartLongProcess. In that case you don't need IDisposable.


问:
Would this union work if char had stricter alignment requirements than int?
Recently I came across the following snippet, which is an attempt to ensure all bytes of i (nad no more) are accessible as individual elements of c:

```<code>union {
  int i;
  char c[sizeof(int)];
};
</code>```

Now this seems a good idea, but I wonder if the standard allows for the case where the alignment requirements for char are more restrictive than that for int.

In other words, is it possible to have a four-byte int which is required to be aligned on a four-byte boundary with a one-byte char (it is one byte, by definition, see below) required to be aligned on a sixteen-byte boundary?

And would this stuff up the use of the union above?

Two things to note.

I'm talking specifically about what the standard allows here, not what a sane implementor/architecture would provide.

I'm using the term "byte" in the ISO C sense, where it's the width of a char, not necessarily 8 bits.

答:
No type can ever have stricter alignment requirements than its size (because of how arrays work), and sizeof(char) is 1.

In case it's not obvious:

sizeof(T [N]) is sizeof(T)*N.

sizeof is in units of char; all types are represented as a fixed number of bytes (char), that number being their size. See 6.2.6 (Representation of Types) for details.

Given T A[2];, (char *)&A[1] - (char *)&A[0] is equal to sizeof A[0].

Therefore the alignment requirement for T is no greater than sizeof(T) (in fact it divides sizeof(T))

ContentLicense: CC BY-SA 2.5

Body:
Recently I came across the following snippet, which is an attempt to ensure all bytes of i (nad no more) are accessible as individual elements of c:

union {
  int i;
  char c[sizeof(int)];
};

Now this seems a good idea, but I wonder if the standard allows for the case where the alignment requirements for char are more restrictive than that for int.

In other words, is it possible to have a four-byte int which is required to be aligned on a four-byte boundary with a one-byte char (it is one byte, by definition, see below) required to be aligned on a sixteen-byte boundary?

And would this stuff up the use of the union above?

Two things to note.

I'm talking specifically about what the standard allows here, not what a sane implementor/architecture would provide.

I'm using the term "byte" in the ISO C sense, where it's the width of a char, not necessarily 8 bits.


问:
Sklearn parallel processing not working in docker container
I'm building and training some RandomForestClassifier models in sklearn. I recently found out about the n_jobs variable to use parallel processing for training and predicting.  However, it seems to have the opposite effect that I'm looking for.

When n_jobs is unassigned (defaults to 1) the training/predicting will entirely use 1 core. I can see 100% CPU usage when running "top".  However, when I bump it to 4, or -1 (number of cores, which is 4) the CPU usage drops to 25%.

Has anyone else run into this before and/or know of a solution?

答:
In general, with n_jobs=1 it uses 100% of the cpu of one of the cores. Each process is run in a different core. In windows with 4 cores I can clearly see the cpu usage:(100%,~5%, ~5%, ~5%) when I run n_jobs = 1 and (100%, 100%, 100%, 100%) when running with n_jobs = -1.Also, the laptop freezes in the last case. Each process takes the 100% usage of a given core, but if you have n_jobs = 1 only one core is used.

You can also try to add if__name__==="__main__": and n_jobs =-1

Example 1:

```<code>from sklearn.ensemble import RandomForestClassifier

if __name__ == '__main__':
    clf = RandomForestClassifier( n_jobs = -1 )
    #more code
</code>```

or
Example 2:

```<code>Class Test(object):
    def __init__(self):
        clf = RandomForestClassifier( n_jobs = -1 )
        ###code here

if __name__ == '__main__':
    Test()
</code>```

Body:
In general, with n_jobs=1 it uses 100% of the cpu of one of the cores. Each process is run in a different core. In windows with 4 cores I can clearly see the cpu usage:(100%,~5%, ~5%, ~5%) when I run n_jobs = 1 and (100%, 100%, 100%, 100%) when running with n_jobs = -1.Also, the laptop freezes in the last case. Each process takes the 100% usage of a given core, but if you have n_jobs = 1 only one core is used.

You can also try to add if__name__==="__main__": and n_jobs =-1

Example 1:

from sklearn.ensemble import RandomForestClassifier

if __name__ == '__main__':
    clf = RandomForestClassifier( n_jobs = -1 )
    #more code

or
Example 2:

Class Test(object):
    def __init__(self):
        clf = RandomForestClassifier( n_jobs = -1 )
        ###code here

if __name__ == '__main__':
    Test()


问:
Java ee agent for ODI
I've created a domain for my java ee agent using : https://docs.oracle.com/middleware/1221/core/ODING/GUID-3F74BFAB-99E9-4060-86E8-F70A8352A701.htm#ODING292

I've also created an agent in odi studio, but when i try to test it it gives me the error:

oracle.odi.runtime.agent.invocation.InvocationException: ODI-1425: Agent application cannot be reached using http.

```<code>at oracle.odi.runtime.agent.invocation.RemoteRuntimeAgentInvoker.reThrowAgentErrorAsInvocation(RemoteRuntimeAgentInvoker.java:1716)

at oracle.odi.runtime.agent.invocation.RemoteRuntimeAgentInvoker.invoke(RemoteRuntimeAgentInvoker.java:401)

at oracle.odi.runtime.agent.invocation.support.InternalRemoteRuntimeAgentInvoker.invoke(InternalRemoteRuntimeAgentInvoker.java:162)

at oracle.odi.runtime.agent.invocation.RemoteRuntimeAgentInvoker.invokeIsAlive(RemoteRuntimeAgentInvoker.java:614)

at oracle.odi.runtime.agent.invocation.RemoteRuntimeAgentInvoker.invokeIsAlive(RemoteRuntimeAgentInvoker.java:592)

at oracle.odi.ui.action.SnpsPopupActionTestAgentHandler.testOdiAgent(SnpsPopupActionTestAgentHandler.java:85)

at oracle.odi.ui.action.SnpsPopupActionTestAgentHandler.actionPerformed(SnpsPopupActionTestAgentHandler.java:76)

at com.sunopsis.graphical.frame.edit.EditFrameSnpAgent$5.performAction(EditFrameSnpAgent.java:637)

at oracle.odi.ui.framework.event.OdiActionListener.actionPerformed(OdiActionListener.java:69)

at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)

at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)

at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)

at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)

at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)

at java.awt.Component.processMouseEvent(Component.java:6533)

at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)

at java.awt.Component.processEvent(Component.java:6298)

at java.awt.Container.processEvent(Container.java:2236)

at java.awt.Component.dispatchEventImpl(Component.java:4889)

at java.awt.Container.dispatchEventImpl(Container.java:2294)

at java.awt.Component.dispatchEvent(Component.java:4711)

at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)

at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)

at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)

at java.awt.Container.dispatchEventImpl(Container.java:2280)

at java.awt.Window.dispatchEventImpl(Window.java:2746)

at java.awt.Component.dispatchEvent(Component.java:4711)

at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)

at java.awt.EventQueue.access$500(EventQueue.java:97)

at java.awt.EventQueue$3.run(EventQueue.java:709)

at java.awt.EventQueue$3.run(EventQueue.java:703)

at java.security.AccessController.doPrivileged(Native Method)

at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)

at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)

at java.awt.EventQueue$4.run(EventQueue.java:731)

at java.awt.EventQueue$4.run(EventQueue.java:729)

at java.security.AccessController.doPrivileged(Native Method)

at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)

at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)

at oracle.javatools.internal.ui.EventQueueWrapper._dispatchEvent(EventQueueWrapper.java:169)

at oracle.javatools.internal.ui.EventQueueWrapper.dispatchEvent(EventQueueWrapper.java:151)

at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)

at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)

at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)

at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)

at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)

at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
</code>```

Caused by: ODI-1425: Agent application cannot be reached using http.

```<code>at oracle.odi.runtime.agent.invocation.RemoteRuntimeAgentInvoker.invoke(RemoteRuntimeAgentInvoker.java:403)

... 45 more
</code>```

Things I've done:

Telnet to the port 15101 and it's working fine.

Firewall is off

Made sure that my node manager and weblogic server are up and running.

Managed server for odi is up and running.

Have even tried to delete and recreate the deployment for the odiagent (http://www.redstk.com/odi-12c-agent-not-running-odi-1425/)

Nothing seems to be working and I'm at my wits end..any help will be highly appreciated.

I'm trying this on windows 10, with odi 12c

答:
Windows 10 is not a server Edition of Windows so it's very unlikely that any server-side component (like the JEE agent) of any enterprise tool would support it.
If you look at the certification matrix, you can see that only the Server 2012 versions of Windows are supported.</p>

Title: Java ee agent for ODI

Body:
I've created a domain for my java ee agent using : https://docs.oracle.com/middleware/1221/core/ODING/GUID-3F74BFAB-99E9-4060-86E8-F70A8352A701.htm#ODING292

I've also created an agent in odi studio, but when i try to test it it gives me the error:

oracle.odi.runtime.agent.invocation.InvocationException: ODI-1425: Agent application cannot be reached using http.

at oracle.odi.runtime.agent.invocation.RemoteRuntimeAgentInvoker.reThrowAgentErrorAsInvocation(RemoteRuntimeAgentInvoker.java:1716)

at oracle.odi.runtime.agent.invocation.RemoteRuntimeAgentInvoker.invoke(RemoteRuntimeAgentInvoker.java:401)

at oracle.odi.runtime.agent.invocation.support.InternalRemoteRuntimeAgentInvoker.invoke(InternalRemoteRuntimeAgentInvoker.java:162)

at oracle.odi.runtime.agent.invocation.RemoteRuntimeAgentInvoker.invokeIsAlive(RemoteRuntimeAgentInvoker.java:614)

at oracle.odi.runtime.agent.invocation.RemoteRuntimeAgentInvoker.invokeIsAlive(RemoteRuntimeAgentInvoker.java:592)

at oracle.odi.ui.action.SnpsPopupActionTestAgentHandler.testOdiAgent(SnpsPopupActionTestAgentHandler.java:85)

at oracle.odi.ui.action.SnpsPopupActionTestAgentHandler.actionPerformed(SnpsPopupActionTestAgentHandler.java:76)

at com.sunopsis.graphical.frame.edit.EditFrameSnpAgent$5.performAction(EditFrameSnpAgent.java:637)

at oracle.odi.ui.framework.event.OdiActionListener.actionPerformed(OdiActionListener.java:69)

at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)

at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)

at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)

at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)

at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)

at java.awt.Component.processMouseEvent(Component.java:6533)

at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)

at java.awt.Component.processEvent(Component.java:6298)

at java.awt.Container.processEvent(Container.java:2236)

at java.awt.Component.dispatchEventImpl(Component.java:4889)

at java.awt.Container.dispatchEventImpl(Container.java:2294)

at java.awt.Component.dispatchEvent(Component.java:4711)

at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)

at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)

at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)

at java.awt.Container.dispatchEventImpl(Container.java:2280)

at java.awt.Window.dispatchEventImpl(Window.java:2746)

at java.awt.Component.dispatchEvent(Component.java:4711)

at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)

at java.awt.EventQueue.access$500(EventQueue.java:97)

at java.awt.EventQueue$3.run(EventQueue.java:709)

at java.awt.EventQueue$3.run(EventQueue.java:703)

at java.security.AccessController.doPrivileged(Native Method)

at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)

at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)

at java.awt.EventQueue$4.run(EventQueue.java:731)

at java.awt.EventQueue$4.run(EventQueue.java:729)

at java.security.AccessController.doPrivileged(Native Method)

at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)

at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)

at oracle.javatools.internal.ui.EventQueueWrapper._dispatchEvent(EventQueueWrapper.java:169)

at oracle.javatools.internal.ui.EventQueueWrapper.dispatchEvent(EventQueueWrapper.java:151)

at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)

at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)

at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)

at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)

at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)

at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

Caused by: ODI-1425: Agent application cannot be reached using http.

at oracle.odi.runtime.agent.invocation.RemoteRuntimeAgentInvoker.invoke(RemoteRuntimeAgentInvoker.java:403)

... 45 more

Things I've done:

Telnet to the port 15101 and it's working fine.

Firewall is off

Made sure that my node manager and weblogic server are up and running.

Managed server for odi is up and running.

Have even tried to delete and recreate the deployment for the odiagent (http://www.redstk.com/odi-12c-agent-not-running-odi-1425/)

Nothing seems to be working and I'm at my wits end..any help will be highly appreciated.

I'm trying this on windows 10, with odi 12c


问:
StartActivity for result inside frgament handlr onactivityresult
I have Activity-->FragmentA-->FragmentB1 & FRagmentB2. When I call startActivityForResult() in FragmentB, how to handle the return data.
Fragment A has a ViewPager with FragmentB1 and FragmentB2

In side a recyclerview .,,,i will be writing a onactivityresult inside the recycler adapter..how to handle it on onactivityresult inside FragmentB1

I have added the image of fragmentB1

答:
Directly Call like below from your fragment, you will get onActivityResult in that fragment itself

```<code>startActivityForResult(new Intent(getActivity(), AnotherActivity.class), 1);
</code>```

dont call with getActivity like below it will return the onActivityResult to the activity.

```<code>getActivity().startActivityForResult(new Intent(getActivity(), AnotherActivity.class), 1);
</code>```

Body:
Directly Call like below from your fragment, you will get onActivityResult in that fragment itself

startActivityForResult(new Intent(getActivity(), AnotherActivity.class), 1);

dont call with getActivity like below it will return the onActivityResult to the activity.

getActivity().startActivityForResult(new Intent(getActivity(), AnotherActivity.class), 1);


问:
How to add the objects into an array stored in local storage using angular js?
I am trying to do use the angular push function but it is not working.

i am storing form values into local storage every time it will be replacing the old object with new object...

I want to add strings (or objects) into an array.

Below is my HTML code:

```<code><form name="myForm" novalidate>
    <p> Username:<br>
        <input type="text" name="user" ng-model="user.user" required>
        <span ng-show="myForm.user.$pristine"/>
    </p>
        <p>Email:<br>
            <input type="email" name="email" ng-model="user.email" required>
            <span style="color:red" ng-show="myForm.email.$dirty && myForm.email.$invalid">
                <span ng-show="myForm.email.$error.required">Email is required.</span>
                <span ng-show="myForm.email.$error.email">Invalid email address.</span>
            </span>
        </p>

            <p> PhoneNum:<br>
                <input type="number" name="PhoneNum" ng-model="user.PhoneNum" required>
                <span ng-show="myForm.PhoneNum.$pristine"></span>
            </p>
                <p>Address:<br>
                    <input type="text" name="address" ng-model="user.address" required>
                    <span ng-show="myForm.address.$pristine"></span>
                </p>
                    <p>Password:<br>
                        <input type="Password" name="pass" ng-model="user.pass" required>
                        <span ng-show="myForm.pass.$pristine"  />
                    </p>
                        <p>
                            <input type="submit" ng-click="addItem(user)" ng-disabled="myForm.$invalid">
                        </p>

</form>
```user = {{user | json}}```
<table>
{{userdata}}
    <tr>
        <td>user</td>
        <td>Email</td>
        <td>Phone</td>
        <td>Address</td>
        <td>Password</td>
    </tr>
    <tr ng-repeat="x in userArray">
        <td>{{x.user}}</td>
        <td>{{x.email}}</td>
        <td>{{x.PhoneNum}}</td>
        <td>{{x.address}}</td>
        <td>{{x.pass}}</td>
    </tr>
</table>
</code>```

Below is my js code:

```<code>var app = angular.module("myApp", ['ngRoute','ngStorage']);
app.controller("userCtrl",['$scope','$localStorage','$log',function($scope,$localStorage,$log){
    $scope.userArray=[];
    $scope.userdata=$localStorage.data;

    $scope.addItem=function(user){
        //var current=$localStorage.data;
        //$scope.userArray=userArray.concat(user);
        $log.log($scope.userArray);
        $scope.userArray.push(user);
        $localStorage.data=$scope.userArray;
        $scope.userdata=$localStorage.data;
    }

}]);
</code>```

The data will stored local storage

But everytime I click the button it overwrites the data in my localstorage.

Does anybody know how to do this?

答:
You have to clear user object first after push in userArray as

```<code>$scope. user = {};
</code>```

Here is the link Jsfiddle demo

```<code>$scope.addItem = function(user) {
  $scope.userArray.push(user);
  $scope.user = {};
  $localStorage.data = $scope.userArray;
  $scope.userdata = $localStorage.data;
}
</code>```

Body:
I am trying to do use the angular push function but it is not working.

i am storing form values into local storage every time it will be replacing the old object with new object...

I want to add strings (or objects) into an array.

Below is my HTML code:

<form name="myForm" novalidate>

 Username:

        <input type="text" name="user" ng-model="user.user" required>

Email:

            <input type="email" name="email" ng-model="user.email" required>

                Email is required.
                Invalid email address.

 PhoneNum:

                <input type="number" name="PhoneNum" ng-model="user.PhoneNum" required>

Address:

                    <input type="text" name="address" ng-model="user.address" required>

Password:

                        <input type="Password" name="pass" ng-model="user.pass" required>

                            <input type="submit" ng-click="addItem(user)" ng-disabled="myForm.$invalid">

</form>

user = {{user | json}}

{{userdata}}

        user
        Email
        Phone
        Address
        Password

        {{x.user}}
        {{x.email}}
        {{x.PhoneNum}}
        {{x.address}}
        {{x.pass}}

Below is my js code:

var app = angular.module("myApp", ['ngRoute','ngStorage']);
app.controller("userCtrl",['$scope','$localStorage','$log',function($scope,$localStorage,$log){
    $scope.userArray=[];
    $scope.userdata=$localStorage.data;

    $scope.addItem=function(user){
        //var current=$localStorage.data;
        //$scope.userArray=userArray.concat(user);
        $log.log($scope.userArray);
        $scope.userArray.push(user);
        $localStorage.data=$scope.userArray;
        $scope.userdata=$localStorage.data;
    }

}]);

The data will stored local storage

But everytime I click the button it overwrites the data in my localstorage.

Does anybody know how to do this?

Body:
You have to clear user object first after push in userArray as

$scope. user = {};

Here is the link Jsfiddle demo

$scope.addItem = function(user) {
  $scope.userArray.push(user);
  $scope.user = {};
  $localStorage.data = $scope.userArray;
  $scope.userdata = $localStorage.data;
}


问:
CloudKit CKdatabaseOperation does not throw error in simulator depending on .qualityOfService setting
I am basically messing around with CloudKit. I have 2 questions that I would like some help/education with.

(1) When I try to run the following code in the simulator with WiFi Turned off (To simulate network unavailability), I expect it to throw network unavailable error. However, cloudKit does not throw any error and the function does not do anything either i.e. does not execute either of the print statements inside the modifyRecordZonesCompletionBlock

```<code>self.container = CKContainer.default()
self.privateDB = self.container.privateCloudDatabase
let createZoneGroup = DispatchGroup()

createZoneGroup.enter()

let createZoneOperation = CKModifyRecordZonesOperation(recordZonesToSave: [customZone], recordZoneIDsToDelete: [])

createZoneOperation.modifyRecordZonesCompletionBlock = { (saved, deleted, error) in
if let theerror = error {
// Need to handle error
    print("Create Custom zone error \(theerror)")
} else {
    print("Custom Zone created")
}
    createZoneGroup.leave()
}

createZoneOperation.qualityOfService = .background
self.privateDB.add(createZoneOperation)
</code>```

However, when I change the createZoneOperation.qualityOfService to default or userInitiated, it then throws an Error (below) as which is the expected behaviour. Why is this? Is it just a simulator anomaly or is the throwing of cloud kit errors tied to the operation quality of service and why? I cannot find any info in the cloudkit API reference for this behavior.

```<code>Create Custom zone error <CKError 0x60800005a2e0: "Partial Failure" (2/1011); "Failed to modify some record zones"; partial errors: {
    Main:__defaultOwner__ = <CKError 0x610000242910: "Network Unavailable" (3/NSURLErrorDomain:-1009); "The Internet connection appears to be offline.">
}>
</code>```

(2) Also, I expected it to throw a straight up Network Unavailableerror rather than a Partial Failurefailure error with the Network Unavailable error wrapped inside it. Is this the expected behaviour? Does it always throw a Partial Failure error and then has to be unwrapped to find the containing error messages?The documentation appears to be incredibly lacking any explanation, unless I failed to look in the right place.

Any help would be very much appreciated. Thank you.

答:
I'try to answer both questions...

Network

There's no simulator error or issue, you don't receive an error connection because .background quality of service means...

The system performs work initiated by a user sooner than background
work that can be deferred until a more optimal time.

Maybe that's the reason why you don't receive the error, it's because system is waiting for a better network condition, while you set .default or .userInitiate the system expect a "real time" response.

Quote from the Energy Efficiency Guide for iOS Apps

To simulate network conditions better use Network Link Conditioner tool by Apple. Here you could find more info about it.

Partial Error

I'm not sure about it but I think that Partial Failure is the common wrapper for all the CKxxxxxOperation error results.

It has sense because those operations involves 1..N CKRecords and some of them could finish ok, and others could finish with error

Body:
I am basically messing around with CloudKit. I have 2 questions that I would like some help/education with.

(1) When I try to run the following code in the simulator with WiFi Turned off (To simulate network unavailability), I expect it to throw network unavailable error. However, cloudKit does not throw any error and the function does not do anything either i.e. does not execute either of the print statements inside the modifyRecordZonesCompletionBlock

self.container = CKContainer.default()
self.privateDB = self.container.privateCloudDatabase
let createZoneGroup = DispatchGroup()

createZoneGroup.enter()

let createZoneOperation = CKModifyRecordZonesOperation(recordZonesToSave: [customZone], recordZoneIDsToDelete: [])

createZoneOperation.modifyRecordZonesCompletionBlock = { (saved, deleted, error) in
if let theerror = error {
// Need to handle error
    print("Create Custom zone error \(theerror)")
} else {
    print("Custom Zone created")
}
    createZoneGroup.leave()
}

createZoneOperation.qualityOfService = .background
self.privateDB.add(createZoneOperation)

However, when I change the createZoneOperation.qualityOfService to default or userInitiated, it then throws an Error (below) as which is the expected behaviour. Why is this? Is it just a simulator anomaly or is the throwing of cloud kit errors tied to the operation quality of service and why? I cannot find any info in the cloudkit API reference for this behavior.

Create Custom zone error <CKError 0x60800005a2e0: "Partial Failure" (2/1011); "Failed to modify some record zones"; partial errors: {
    Main:__defaultOwner__ = <CKError 0x610000242910: "Network Unavailable" (3/NSURLErrorDomain:-1009); "The Internet connection appears to be offline.">
}>

(2) Also, I expected it to throw a straight up Network Unavailableerror rather than a Partial Failurefailure error with the Network Unavailable error wrapped inside it. Is this the expected behaviour? Does it always throw a Partial Failure error and then has to be unwrapped to find the containing error messages?The documentation appears to be incredibly lacking any explanation, unless I failed to look in the right place.

Any help would be very much appreciated. Thank you.


问:
Alternate ways to reduce execution time for bringing a POstgreSQL table to Pandas with 500000 rows?
I have a PostgreSQL DB with 70 tables of which I wish to access one specific table named "hub_psm_log_inter". I wish to bring it to pandas and apply some operations on it. The table I am accessing has a shape of (500000, 23), which will possibly increase in future. It is taking around 3 minutes for psql.read_sql_query to execute. I wish to reduce the time its taking. The rows which matter to me are where (cust_hub_id = 358 & status_switch = 1). Shape of df_on has only 10000 rows.

```<code>import numpy as np
import pandas as pd

import psycopg2 as pg
import pandas.io.sql as psql

conn = pg.connect(
    database = '',
    user = '',
    password = '',
    host = '',
    port = ''
)

df2 = psql.read_sql_query("SELECT * FROM hub_psm_log_inter", conn)

df4 = df2[df2.cust_hub_id == 358]
df4['status_switch'] = pd.to_numeric(df4['status_switch'], errors='coerce')
df_on = df4[df4.status_switch == 1]
</code>```

答:
Use a WHERE clause in your SQL query:

```<code>SELECT * FROM hub_psm_log_inter WHERE cust_hub_id = 358 AND status_switch = 1
</code>```

From the look of your code, status_switch may be stored as a string in your table, so you might need to quote it, i.e.

```<code>SELECT * FROM hub_psm_log_inter WHERE cust_hub_id = 358 AND status_switch = '1'
</code>```

Body:
I have a PostgreSQL DB with 70 tables of which I wish to access one specific table named "hub_psm_log_inter". I wish to bring it to pandas and apply some operations on it. The table I am accessing has a shape of (500000, 23), which will possibly increase in future. It is taking around 3 minutes for psql.read_sql_query to execute. I wish to reduce the time its taking. The rows which matter to me are where (cust_hub_id = 358 & status_switch = 1). Shape of df_on has only 10000 rows.

import numpy as np
import pandas as pd

import psycopg2 as pg
import pandas.io.sql as psql

conn = pg.connect(
    database = '',
    user = '',
    password = '',
    host = '',
    port = ''
)

df2 = psql.read_sql_query("SELECT * FROM hub_psm_log_inter", conn)

df4 = df2[df2.cust_hub_id == 358]
df4['status_switch'] = pd.to_numeric(df4['status_switch'], errors='coerce')
df_on = df4[df4.status_switch == 1]

Body:
Use a WHERE clause in your SQL query:

SELECT * FROM hub_psm_log_inter WHERE cust_hub_id = 358 AND status_switch = 1

From the look of your code, status_switch may be stored as a string in your table, so you might need to quote it, i.e.

SELECT * FROM hub_psm_log_inter WHERE cust_hub_id = 358 AND status_switch = '1'


问:
how to set an parameter to not filter the SQL query when not set
I have a page with a list of artists and three buttons; photographers, makeup artists, all

I want to query the database to select each type through $_GET when any of the buttons is clicked which is easy for the first two I can set the url to ?type=photographers

however when I want to set the type to all, there's no value in the type column called all, i tried to set the type to * but it doesn't work

```<code>SELECT name, location, score, type FROM artists WHERE type = ?
</code>```

how to set type to show all what should the variable be equal to?

edit: I'm already using the !empty method, now I want to add more rules to my query and it's getting complicated, any other solution where I don't have to have two queries in the if and else?

答:
Seems you have two choices,

1. Create your base sql query SELECT name, location, score, type FROM artists and append where clause based on the type (If type is ALL do not append the clause).

2. When click ALL, really pass the all types (photographers, makeup artists) and check for

 WHERE type IN ();

Body:
I have a page with a list of artists and three buttons; photographers, makeup artists, all

I want to query the database to select each type through $_GET when any of the buttons is clicked which is easy for the first two I can set the url to ?type=photographers

however when I want to set the type to all, there's no value in the type column called all, i tried to set the type to * but it doesn't work

SELECT name, location, score, type FROM artists WHERE type = ?

how to set type to show all what should the variable be equal to?

edit: I'm already using the !empty method, now I want to add more rules to my query and it's getting complicated, any other solution where I don't have to have two queries in the if and else?


问:
Accessing Google Calendar API from Node server
For some reason, I am having a really hard time accessing Google calendar.

I want to be able to add and remove events in a calendar from my Node.js server.

I am finding really conflicting information from the documents.

I followed - https://developers.google.com/identity/protocols/OAuth2ServiceAccount which gives a good guide on how to get an acccess token but then at the end it appears it is only for accessing Drive.

I then followed Google Calendar API v3 Access Not Configured which states you only need an API key but this appears as though it is all done from client side so maybe it's different?

I looked at https://developers.google.com/google-apps/calendar/quickstart/nodejs as well but that seems very complicated just to make a simple API call to a calendar. The sample code references files which isn't clear where they come from or how to structure them. E.g. var TOKEN_PATH = TOKEN_DIR + 'calendar-nodejs-quickstart.json';

I simple guide on how to achieve this would be hugely appreciated.

Thanks

答:
I believe you want to add and remove events in a calendar using Node.js.

About quickstart.js for using calendar API, in order to use calendar API, at first, users have to retrieve client_secret.json with client ID, client secret and so on, and enable calendar API at API console.

As a next step, access token and refresh token have to be retrieved from Google using client_secret.json. Most of quickstart.js in Quickstart is used to retrieve them. var TOKEN_PATH = TOKEN_DIR + 'calendar-nodejs-quickstart.json'; includes the access token and refresh token retrieved using client_secret.json. The access token which has the expiration time can be retrieved from the refresh token which doesn't have the expiration time. At quickstart.js, access token is retrieved every running the script using the refresh token.

Functions except for listEvents(auth) in the quickstart.js are used for the authorization. At listEvents(auth), calendar API can be used by using the access token retrieved by the authorization.

Sample script

Following sample script is for adding and removing events. This supposes that Step 1 and Step 2 in Quickstart have already finished and quickstart.js is used.

For Node.js Quickstart sample, it modified listEvents(). When you use this sample script, please copy and paste Node.js Quickstart sample and change listEvents() as follows, and add following addEvents() and removeEvents().

```<code>function listEvents(auth) {
  var calendar = google.calendar('v3');

  addEvents(auth, calendar); // Add events
  removeEvents(auth, calendar); // Remove events
}
</code>```

1. Add events

Detail information is https://developers.google.com/google-apps/calendar/v3/reference/events/insert.

```<code>function addEvents(auth, calendar){
  calendar.events.insert({
    auth: auth,
    calendarId: 'primary',
    resource: {
      'summary': 'Sample Event',
      'description': 'Sample description',
      'start': {
        'dateTime': '2017-01-01T00:00:00',
        'timeZone': 'GMT',
      },
      'end': {
        'dateTime': '2017-01-01T01:00:00',
        'timeZone': 'GMT',
      },
    },
  }, function(err, res) {
    if (err) {
      console.log('Error: ' + err);
      return;
    }
    console.log(res);
  });
}
</code>```

2. Remove events

Detail information is https://developers.google.com/google-apps/calendar/v3/reference/events/delete.

```<code>function removeEvents(auth, calendar){
  calendar.events.delete({
    auth: auth,
    calendarId: 'primary',
    eventId: "#####",
  }, function(err) {
    if (err) {
      console.log('Error: ' + err);
      return;
    }
    console.log("Removed");
  });
}
</code>```

Body:
I believe you want to add and remove events in a calendar using Node.js.

About quickstart.js for using calendar API, in order to use calendar API, at first, users have to retrieve client_secret.json with client ID, client secret and so on, and enable calendar API at API console.

As a next step, access token and refresh token have to be retrieved from Google using client_secret.json. Most of quickstart.js in Quickstart is used to retrieve them. var TOKEN_PATH = TOKEN_DIR + 'calendar-nodejs-quickstart.json'; includes the access token and refresh token retrieved using client_secret.json. The access token which has the expiration time can be retrieved from the refresh token which doesn't have the expiration time. At quickstart.js, access token is retrieved every running the script using the refresh token.

Functions except for listEvents(auth) in the quickstart.js are used for the authorization. At listEvents(auth), calendar API can be used by using the access token retrieved by the authorization.

Sample script

Following sample script is for adding and removing events. This supposes that Step 1 and Step 2 in Quickstart have already finished and quickstart.js is used.

For Node.js Quickstart sample, it modified listEvents(). When you use this sample script, please copy and paste Node.js Quickstart sample and change listEvents() as follows, and add following addEvents() and removeEvents().

function listEvents(auth) {
  var calendar = google.calendar('v3');

  addEvents(auth, calendar); // Add events
  removeEvents(auth, calendar); // Remove events
}

1. Add events

Detail information is https://developers.google.com/google-apps/calendar/v3/reference/events/insert.

function addEvents(auth, calendar){
  calendar.events.insert({
    auth: auth,
    calendarId: 'primary',
    resource: {
      'summary': 'Sample Event',
      'description': 'Sample description',
      'start': {
        'dateTime': '2017-01-01T00:00:00',
        'timeZone': 'GMT',
      },
      'end': {
        'dateTime': '2017-01-01T01:00:00',
        'timeZone': 'GMT',
      },
    },
  }, function(err, res) {
    if (err) {
      console.log('Error: ' + err);
      return;
    }
    console.log(res);
  });
}

2. Remove events

Detail information is https://developers.google.com/google-apps/calendar/v3/reference/events/delete.

function removeEvents(auth, calendar){
  calendar.events.delete({
    auth: auth,
    calendarId: 'primary',
    eventId: "#####",
  }, function(err) {
    if (err) {
      console.log('Error: ' + err);
      return;
    }
    console.log("Removed");
  });
}

ContentLicense: CC BY-SA 4.0


问:
Handling multiple changesets in source control systems
I have a fairly infrequent problem occuring with source control. In the example here the problem was occuring with Perforce, but I suspect the same problem will occur with many SCMs, especially distributed SCMs.

Perforce supports changelists (or changesets if you prefer). Changelists support two common usages:

When you commit a changelist, the commit is atomic so that all the files are committed or none are. This is the headline feature that most people talk about when referring to changelists.

Perforce supports multiple changelists. Basically, when you check out a file you tell it which changelist it belongs to. So, if you are working on the fancy new email feature which is going to take months of work and makes millions of dollars and somebody from tech support comes to you with a bug that must be fixed yesterday, you don't have to start with a new branch of the whole project. You can just check out the buggy file into a new changelist, fix the problem, check in the new changelist and get back to the real work of the new email feature, as though nothing had happened.

For the most part everything works great. However, when you are implemening the email feature you are making zillions of changes all over the place, especially in main.h, and it just so happens that when go to work on the bug fix you discover that the tiny change you have to make is also in main.h. The changelist for the new feature already has main.h checked out, so you can't easily put it in the changelist for the bug fix.

Now what do you do? You have several choices:

Create a new clientspec. A clientspec in Perforce is a list of files/directories in the depot and a local destination where everything is to be copied. So you can create a second copy of the project without any of changes for the email feature.

Do a fudge. Backup your modified copy of main.h and revert this file. You are then free to checkout main.h into the bugfix changelist. You fix the bug, check in the bugfix changelist, then checkout main.h into the email feature changelist. Finally you merge all your changes from the backup you made at the start.

You determine that all the changes you have made to main.h have no side affects or dependencies, so you just move main.h into the bugfix changelist, make the change and check it in. You then check it out again into the email feature changelist. Obviously there are two problems with this approach: firstly there may in fact be side affects that you hadn't considered and secondly you have corrupted your version histoty.

Option 1 is probably the cleanest, but not always practical. A project I was working on had millions of lines of code and a really complicated build process. It would take a day to setup a new environment, so it was not really practical for a 5 minute bug fix.

Option 3 is a bad option, but is is the quickest, so it can be very seductive.

That leaves Option 2, which is the one I would generally use.

Does anybody have a better solution?

My apologies for the lengthy question, but I have discovered on StackOverflow that fully thought out questions elicit better answers.

答:
This exact problem has been called the "Tangled Working Copy Problem". Ryan Tomayko has a blog entry titled The Thing About Git that talks about this problem in detail and how Git addresses it.

This is one of the best things about Git. I use git add -p at least daily, to help commit individual chunks of code that make sense independently of one another. The fact that two logically different changes are in the same source file has become irrelevant.

OwnerDisplayName: Mike Thompson

OwnerDisplayName: Greg Hewgill


问:
What is Oracle error ORA-01536?
I got the following error on Oracle: ORA-01536

What is the problem?

答:
The online documentation includes a book with explanations and resolutions for all the error messages.  Some of them are a bit cryptic but it is the place to start.  Find out more.

Anyhoo, here is an illustrated solution for ORA-01536.

A DBA creates a new user:

```<code>SQL> create user fox_in_socks identified by tweetlebeetle
  2      default tablespace users quota 1M on users
  3  /

User created.

SQL> grant create session, create table to fox_in_socks
  2  /

Grant succeeded.

SQL>
</code>```

In another session our brave user creates a table...

```<code>SQL> conn fox_in_socks/tweetlebeetle
Connected.
SQL> create table t23 (col1 varchar2(4000))
  2  /

Table created.

SQL>
</code>```

.. and does some work....

```<code>SQL> begin
  2      for i in 1..1000 loop
  3          insert into t23 values (rpad('a', 4000, 'a'));
  4          commit;
  5      end loop;
  6  end;
  7  /
begin
*
ERROR at line 1:
ORA-01536: space quota exceeded for tablespace 'USERS'
ORA-06512: at line 3

SQL>
</code>```

Uh-oh!  So our user goes to their tame DBA and asks for more quota, which they get:

```<code>SQL> alter user fox_in_socks
  2      quota 10M on users
  3  /

User altered.

SQL>
</code>```

Work proceeds:

```<code>SQL> begin
  2      for i in 1..1000 loop
  3          insert into t23 values (rpad('a', 4000, 'a'));
  4          commit;
  5      end loop;
  6  end;
  7  /

PL/SQL procedure successfully completed.

SQL>
</code>```

If the user were an application owner then the DBA could have decided to give them unlimited quota (especially if they were the only user with privileges on that tablespace):

```<code>alter user fox_in_socks
    quota unlimited on users
/
</code>```

(in real life this situation is unlikely to be true for the USERS tablespace).

Users can check their current quota using the appropriate view:

```<code>SQL> select * from user_ts_quotas
  2  /

TABLESPACE_NAME                     BYTES  MAX_BYTES     BLOCKS MAX_BLOCKS DRO
------------------------------ ---------- ---------- ---------- ---------- ---
USERS                             9437184   10485760       1152       1280 NO

SQL>
</code>```

Title: What is Oracle error ORA-01536?

Body:
The online documentation includes a book with explanations and resolutions for all the error messages.  Some of them are a bit cryptic but it is the place to start.  Find out more.

Anyhoo, here is an illustrated solution for ORA-01536.

A DBA creates a new user:

SQL> create user fox_in_socks identified by tweetlebeetle
  2      default tablespace users quota 1M on users
  3  /

User created.

SQL> grant create session, create table to fox_in_socks
  2  /

Grant succeeded.

SQL>

In another session our brave user creates a table...

SQL> conn fox_in_socks/tweetlebeetle
Connected.
SQL> create table t23 (col1 varchar2(4000))
  2  /

Table created.

SQL>

.. and does some work....

SQL> begin
  2      for i in 1..1000 loop
  3          insert into t23 values (rpad('a', 4000, 'a'));
  4          commit;
  5      end loop;
  6  end;
  7  /
begin
*
ERROR at line 1:
ORA-01536: space quota exceeded for tablespace 'USERS'
ORA-06512: at line 3

SQL>

Uh-oh!  So our user goes to their tame DBA and asks for more quota, which they get:

SQL> alter user fox_in_socks
  2      quota 10M on users
  3  /

User altered.

SQL>

Work proceeds:

SQL> begin
  2      for i in 1..1000 loop
  3          insert into t23 values (rpad('a', 4000, 'a'));
  4          commit;
  5      end loop;
  6  end;
  7  /

PL/SQL procedure successfully completed.

SQL>

If the user were an application owner then the DBA could have decided to give them unlimited quota (especially if they were the only user with privileges on that tablespace):

alter user fox_in_socks
    quota unlimited on users
/

(in real life this situation is unlikely to be true for the USERS tablespace).

Users can check their current quota using the appropriate view:

SQL> select * from user_ts_quotas
  2  /

TABLESPACE_NAME                     BYTES  MAX_BYTES     BLOCKS MAX_BLOCKS DRO
------------------------------ ---------- ---------- ---------- ---------- ---
USERS                             9437184   10485760       1152       1280 NO

SQL>


问:
Laravel 5.2.45 Tcpdf installation failed with php version 5.5.11
I need to generate a PDF using TDPDF with Laravel 5.2.45.
I used the following command (reference: here):

```<code>composer require elibyy/tcpdf-laravel
</code>```

and received the following message:

Message: Your PHP version <5.5.11> does not satisfy that requirement.

Is there any other way to download TCPDF with Laravel if my PHP version do not satisfy the requirement?

答:
I updated my composer with following command

```<code>composer update
</code>```

Then added the following line to my composer.json file

```<code>{
"require": {
    "elibyy/tcpdf-laravel": "5.4.*"
} }
</code>```

Next added the service provider to config/app.php.

```<code>'providers' => [
//...
Elibyy\TCPDF\ServiceProvider::class,
]
//...
'aliases' => [
//...
'PDF' => Elibyy\TCPDF\Facades\TCPDF::class
]
</code>```

and again run the following command

```<code>composer update
</code>```

And then to my controller I added the following lines:

```<code>use PDF; // at the top of the file

PDF::SetTitle('Hello World');
PDF::AddPage();
PDF::Write(0, 'Hello World');
PDF::Output('hello_world.pdf');
</code>```

Now I am able to generate a PDF.

Body:
I need to generate a PDF using TDPDF with Laravel 5.2.45.
I used the following command (reference: here):

composer require elibyy/tcpdf-laravel

and received the following message:

Message: Your PHP version <5.5.11> does not satisfy that requirement.

Is there any other way to download TCPDF with Laravel if my PHP version do not satisfy the requirement?

Body:
I updated my composer with following command

composer update

Then added the following line to my composer.json file

{
"require": {
    "elibyy/tcpdf-laravel": "5.4.*"
} }

Next added the service provider to config/app.php.

'providers' => [
//...
Elibyy\TCPDF\ServiceProvider::class,
]
//...
'aliases' => [
//...
'PDF' => Elibyy\TCPDF\Facades\TCPDF::class
]

and again run the following command

composer update

And then to my controller I added the following lines:

use PDF; // at the top of the file

PDF::SetTitle('Hello World');
PDF::AddPage();
PDF::Write(0, 'Hello World');
PDF::Output('hello_world.pdf');

Now I am able to generate a PDF.


问:
Defining an Abstract model with a ForeignKey to another Abstract model
I'm trying to build two abstract classes called SurveyQuestionBase and SurveyResponseBase that will serve as templates to quickly define new concrete Models for implementing specific surveys on our website. The issue I am having is in enforcing that the SurveyResponseBase model, when made concrete, should define a ForeignKey to a concrete model of SurveyQuestionBase.

Django does not allow us to define ForeignKeys to abstract classes so I cannot, for instance, do this:
question = models.ForeignKey(SurveyQuestionBase)
Neither can I have it as None or app_label.ModelName for similar reasons.

One hacky fix is to create a new concrete model SurveyQuestionConcrete and make the ForeignKey point to this: question = models.ForeignKey(concrete_model), combined with validation to ensure this model is replaced.

Is there a cleaner way to achieve the same thing? All I need to do is ensure that when someone defines a concrete model from SurveyResponseBase they include a ForeignKey to a concrete model defined from SurveyQuestionBase

Here's the full code:

```<code>from __future__ import unicode_literals

from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models

# Implementation borrows from: https://github.com/jessykate/django-survey/

class SurveyQuestionBase(models.Model):
    TEXT = 'text'
    INTEGER = 'integer'
    RADIO = 'radio'
    SELECT = 'select'
    MULTI_SELECT = 'multi-select'

    ANSWER_TYPE_CHOICES = (
        (INTEGER, 'Integer',),
        (TEXT, 'Text',),
        (RADIO, 'Radio',),
        (SELECT, 'Select',),
        (MULTI_SELECT, 'Multi-Select',),
    )

    question = models.TextField()
    required = models.BooleanField()
    question_type = models.CharField(choices=ANSWER_TYPE_CHOICES, max_length=20)

    class Meta:
        abstract = True

class SurveyResponseBase(models.Model):
    """
    concrete_question_model: 'app_label.Model' - Define the concrete model this question belongs to
    """
    concrete_model = 'SurveyQuestionBase'

    question = models.ForeignKey(concrete_model)
    response = models.TextField()

    class Meta:
        abstract = True
</code>```

答:
I believe you can't do that because the ForeignKey doesn't know what actual model to point to.

You may be looking for GenericForeignKey (https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#generic-relations). It allows you to define that relationship properly.

Body:
I'm trying to build two abstract classes called SurveyQuestionBase and SurveyResponseBase that will serve as templates to quickly define new concrete Models for implementing specific surveys on our website. The issue I am having is in enforcing that the SurveyResponseBase model, when made concrete, should define a ForeignKey to a concrete model of SurveyQuestionBase.

Django does not allow us to define ForeignKeys to abstract classes so I cannot, for instance, do this:
question = models.ForeignKey(SurveyQuestionBase)
Neither can I have it as None or app_label.ModelName for similar reasons.

One hacky fix is to create a new concrete model SurveyQuestionConcrete and make the ForeignKey point to this: question = models.ForeignKey(concrete_model), combined with validation to ensure this model is replaced.

Is there a cleaner way to achieve the same thing? All I need to do is ensure that when someone defines a concrete model from SurveyResponseBase they include a ForeignKey to a concrete model defined from SurveyQuestionBase

Here's the full code:

from __future__ import unicode_literals

from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models

# Implementation borrows from: https://github.com/jessykate/django-survey/

class SurveyQuestionBase(models.Model):
    TEXT = 'text'
    INTEGER = 'integer'
    RADIO = 'radio'
    SELECT = 'select'
    MULTI_SELECT = 'multi-select'

    ANSWER_TYPE_CHOICES = (
        (INTEGER, 'Integer',),
        (TEXT, 'Text',),
        (RADIO, 'Radio',),
        (SELECT, 'Select',),
        (MULTI_SELECT, 'Multi-Select',),
    )

    question = models.TextField()
    required = models.BooleanField()
    question_type = models.CharField(choices=ANSWER_TYPE_CHOICES, max_length=20)

    class Meta:
        abstract = True

class SurveyResponseBase(models.Model):
    """
    concrete_question_model: 'app_label.Model' - Define the concrete model this question belongs to
    """
    concrete_model = 'SurveyQuestionBase'

    question = models.ForeignKey(concrete_model)
    response = models.TextField()

    class Meta:
        abstract = True


问:
How to retrieve particular data from firebase?

While retrieving the data I am using this code

```<code>databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
     for (DataSnapshot data : dataSnapshot.getChildren()) {
       Firebasemodel firebasemodel = data.getValue(Firebasemodel.class);
       firebasemodels.add(firebasemodel);
    }
 }
 @Override
public void onCancelled(DatabaseError databaseError) {

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

This code snippet which returns the complete data of firebase database.

But I want to retrieve the complete data of particular users. How do I achieve it?

Thanks in advance

答:
Try code below:

```<code>FirebaseDatabase.getInstance().getReference().child("notepad-secure/notepad").addListenerForSingleValueEvent(new ValueEventListener() {

    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        Iterator<DataSnapshot> dataSnapshots = dataSnapshot.getChildren().iterator();

        while (dataSnapshots.hasNext()) {
            user = dataSnapshotChild.getValue(User.class);
            users_list.add(user);
        }
    }

    @Override
        public void onCancelled(DatabaseError databaseError) {
        Log.d("Error", "---" + databaseError.getMessage());
    }
});
</code>```

Model class:

```<code>public class User {

    public String id;
    public String note;
    public String tittle;

    public User() {
    }

    public User(String id, String note, String tittle) {
        this.id= id;
        this.note= note;
        this.tittle= tittle;
    }
}
</code>```

And Declare

```<code>List<User> users_list;
User user;
</code>```

Body:
While retrieving the data I am using this code

databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
     for (DataSnapshot data : dataSnapshot.getChildren()) {
       Firebasemodel firebasemodel = data.getValue(Firebasemodel.class);
       firebasemodels.add(firebasemodel);
    }
 }
 @Override
public void onCancelled(DatabaseError databaseError) {

}
});`

This code snippet which returns the complete data of firebase database.

But I want to retrieve the complete data of particular users. How do I achieve it?

Thanks in advance

Body:
Try code below:

FirebaseDatabase.getInstance().getReference().child("notepad-secure/notepad").addListenerForSingleValueEvent(new ValueEventListener() {

    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        Iterator<DataSnapshot> dataSnapshots = dataSnapshot.getChildren().iterator();

        while (dataSnapshots.hasNext()) {
            user = dataSnapshotChild.getValue(User.class);
            users_list.add(user);
        }
    }

    @Override
        public void onCancelled(DatabaseError databaseError) {
        Log.d("Error", "---" + databaseError.getMessage());
    }
});

Model class:

public class User {

    public String id;
    public String note;
    public String tittle;

    public User() {
    }

    public User(String id, String note, String tittle) {
        this.id= id;
        this.note= note;
        this.tittle= tittle;
    }
}

And Declare

List<User> users_list;
User user;


问:
Java - print sequence of numbers using two threads with inter thread communication
I want to print number in the below format. This should be taken care by two thread t1,t2. Can anyone help to enhance the below code which I have written?

```<code>First t1 should print 0-4
Then t2 should print 5-9
Then again t1 should print 10-14
Then t2 should print 15-19
</code>```

0
1
2
3
4

5
6
7
8
9

10
11
12
13
14

```<code>class PrintNumber implements Runnable{
    String name;

    public void run(){
            print();
    }

    synchronized public void print(){
            for(int i=0;i< 5;i++){
                System.out.println(i+" -- "+Thread.currentThread());
            }
    }

    public static void main(String[] args){
        Runnable r = new PrintNumber();
        Thread t1 = new Thread(r,"t1");
        Thread t2 = new Thread(r,"t2");
        t1.start();
        t2.start();
    }
}
</code>```

答:
You can use wait and notify to achieve inter thread communication for your sczenario.

```<code>class PrintNumber implements Runnable {
    String name;
    Integer count = 0;

    @Override
    public void run() {
        try {
            print();
        } catch (final InterruptedException e) {
            e.printStackTrace();
        }
    }

    synchronized public void print() throws InterruptedException {
        while (count < 15) {
            for (int i = 0; i < 5; i++) {
                count++;
                System.out.println(count + " -- " + Thread.currentThread());
            }
            notifyAll();
            wait();
        }
    }

    public static void main(final String[] args) {
        final Runnable r = new PrintNumber();
        final Thread t1 = new Thread(r, "t1");
        final Thread t2 = new Thread(r, "t2");
        t1.start();
        t2.start();
    }
}
</code>```

For more information see:

A simple scenario using wait() and notify() in java

Body:
I want to print number in the below format. This should be taken care by two thread t1,t2. Can anyone help to enhance the below code which I have written?

First t1 should print 0-4
Then t2 should print 5-9
Then again t1 should print 10-14
Then t2 should print 15-19

0
1
2
3
4

5
6
7
8
9

10
11
12
13
14

class PrintNumber implements Runnable{
    String name;

    public void run(){
            print();
    }

    synchronized public void print(){
            for(int i=0;i< 5;i++){
                System.out.println(i+" -- "+Thread.currentThread());
            }
    }

    public static void main(String[] args){
        Runnable r = new PrintNumber();
        Thread t1 = new Thread(r,"t1");
        Thread t2 = new Thread(r,"t2");
        t1.start();
        t2.start();
    }
}

Body:
You can use wait and notify to achieve inter thread communication for your sczenario.

class PrintNumber implements Runnable {
    String name;
    Integer count = 0;

    @Override
    public void run() {
        try {
            print();
        } catch (final InterruptedException e) {
            e.printStackTrace();
        }
    }

    synchronized public void print() throws InterruptedException {
        while (count < 15) {
            for (int i = 0; i < 5; i++) {
                count++;
                System.out.println(count + " -- " + Thread.currentThread());
            }
            notifyAll();
            wait();
        }
    }

    public static void main(final String[] args) {
        final Runnable r = new PrintNumber();
        final Thread t1 = new Thread(r, "t1");
        final Thread t2 = new Thread(r, "t2");
        t1.start();
        t2.start();
    }
}

For more information see:

A simple scenario using wait() and notify() in java


问:
Visualizing geographic- Information in hadoop
I have a selected geographic data set with ST_Bin Ids. Now i want to visualize them in a map. What is the easiest way do this? </p>

<p>(I can downloaded this data set to local machine. But I don't have actual coordinates) </p>

答:
As per my knowledge you can view the geographic data in based on you have proper geographical data

HUE Editor and Elasticsearch Geolocation

http://gethue.com/wp-content/uploads/2015/03/search-only.png
http://blog.eslimasec.com/2014/05/elastic-security-deploying-logstash.html

Hope this Helps!!!..

Body:
I have a selected geographic data set with ST_Bin Ids. Now i want to visualize them in a map. What is the easiest way do this?

(I can downloaded this data set to local machine. But I don't have actual coordinates)


问:
How to know when a ListBoxItem comes into view?
Is there an event that tells me when a list box item comes into view?

The problem I have is that I can have several thousand elements that I set as my ListBox.ItemSource. Each element will generate a bitmap (which takes a while) so if I would just put this bitmap generation in the constructor creating the collection would take forever to create. Instead I want to defer the bitmap generation when an item comes into view.

Is there a way to do this? Ideally I would prefer not to loop through all the items and check if they are visible.

答:
You could use SelectedItem to get the initial selection and then you could generate your bitmaps for the few above and below it - the exact number will depend on the size of your bitmaps and the size of your ListBox.

I suggest you generate a slightly larger range than you can see so when you pan up/down your list you're not constantly waiting while you render the new bitmaps; think of Google maps - if you pan a short distance the image is already there and it's only when you pan a larger distance that you have to wait for it to redraw.

As you pan up/down your list you could use IsMouseOver to find the item that you're currently hovering over and then update your rendered bitmaps accordingly, again slightly more than you can see.


问:
Android studio execute AsyncClass before onMapReady
I have this code where i have to call data from database yung asynctask the coordinates for my googlemap. but the onMapReady is executing before my Asynctask so the location is always null. I call the asynctask on my oncreate here is my code.

AsyncTask on onCreate

```<code>        HashMap<String, String> postData = new HashMap<>();
        postData.put("rqstID", rqstID);
        AsyncClass taskDetails = new AsyncClass(AcceptActivity.this, postData, "Getting details", new AsyncResponse() {
            @Override
            public void processFinish(String s) {
                Log.d("AcceptActivity", s);
                JSONObject parentObject = null;
                try {
                    parentObject = new JSONObject(s);
                    JSONArray parentArray = parentObject.getJSONArray("result");
                    JSONObject finalObject = parentArray.getJSONObject(0);
                    lat1 = finalObject.getString("rqstLat");
                    lng1 = finalObject.getString("rqstLng");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        taskDetails.execute("http://10.0.2.2/wingman/requestDetails.php");
</code>```

onMapReady

```<code> @Override
public void onMapReady(GoogleMap googleMap) {
    mGoogleMap = googleMap;
    LatLng location = new LatLng(Double.valueOf(lat1), Double.valueOf(lng1));
    CameraUpdate update = CameraUpdateFactory.newLatLngZoom(location, 15);
    mGoogleMap.moveCamera(update);
    MarkerOptions options = new MarkerOptions()
            .position(location)
            .snippet("I'm around here!!!");
    CircleOptions circle = new CircleOptions()
            .center(location)
            .radius(2000)
            .fillColor(0x55add8e6)
            .strokeColor(Color.BLUE)
            .strokeWidth(2);
    mGoogleMap.addCircle(circle);
    mGoogleMap.addMarker(options);
}
</code>```

答:
I think you have to make a function for what ever task you want to perform on map basis on user experience and pass parameter related which value you need to perform your task on map like latitude longitude.

```<code>private void yourFunctionName(double lat1, double lng1){
   LatLng location = new LatLng(Double.valueOf(lat1), Double.valueOf(lng1));
   CameraUpdate update = CameraUpdateFactory.newLatLngZoom(location, 15);
   mGoogleMap.moveCamera(update);
   MarkerOptions options = new MarkerOptions()
        .position(location)
        .snippet("I'm around here!!!");
   CircleOptions circle = new CircleOptions()
        .center(location)
        .radius(2000)
        .fillColor(0x55add8e6)
        .strokeColor(Color.BLUE)
        .strokeWidth(2);
   mGoogleMap.addCircle(circle);
   mGoogleMap.addMarker(options);
}
</code>```

you not need to perform any task in onMapReady() function

```<code>@Override
public void onMapReady(GoogleMap googleMap) {
   mGoogleMap = googleMap;

}
</code>```

store only google map object

```<code>mGoogleMap = googleMap;
</code>```

now perform network operation and call which function you want to perform

```<code>  HashMap<String, String> postData = new HashMap<>();
    postData.put("rqstID", rqstID);
    AsyncClass taskDetails = new AsyncClass(AcceptActivity.this, postData,
    "Getting details", new AsyncResponse() {
        @Override
        public void processFinish(String s) {
            Log.d("AcceptActivity", s);
            JSONObject parentObject = null;
            try {
                parentObject = new JSONObject(s);
                JSONArray parentArray = parentObject.getJSONArray("result");
                JSONObject finalObject = parentArray.getJSONObject(0);
                lat1 = finalObject.getString("rqstLat");
                lng1 = finalObject.getString("rqstLng");
                yourFunctionName(Lat1, lng1) // CALL THIS AFTER GETED RESULT
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    });
    taskDetails.execute("http://10.0.2.2/wingman/requestDetails.php");
</code>```

Body:
I have this code where i have to call data from database yung asynctask the coordinates for my googlemap. but the onMapReady is executing before my Asynctask so the location is always null. I call the asynctask on my oncreate here is my code.

AsyncTask on onCreate

        HashMap<String, String> postData = new HashMap<>();
        postData.put("rqstID", rqstID);
        AsyncClass taskDetails = new AsyncClass(AcceptActivity.this, postData, "Getting details", new AsyncResponse() {
            @Override
            public void processFinish(String s) {
                Log.d("AcceptActivity", s);
                JSONObject parentObject = null;
                try {
                    parentObject = new JSONObject(s);
                    JSONArray parentArray = parentObject.getJSONArray("result");
                    JSONObject finalObject = parentArray.getJSONObject(0);
                    lat1 = finalObject.getString("rqstLat");
                    lng1 = finalObject.getString("rqstLng");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        taskDetails.execute("http://10.0.2.2/wingman/requestDetails.php");

onMapReady

 @Override
public void onMapReady(GoogleMap googleMap) {
    mGoogleMap = googleMap;
    LatLng location = new LatLng(Double.valueOf(lat1), Double.valueOf(lng1));
    CameraUpdate update = CameraUpdateFactory.newLatLngZoom(location, 15);
    mGoogleMap.moveCamera(update);
    MarkerOptions options = new MarkerOptions()
            .position(location)
            .snippet("I'm around here!!!");
    CircleOptions circle = new CircleOptions()
            .center(location)
            .radius(2000)
            .fillColor(0x55add8e6)
            .strokeColor(Color.BLUE)
            .strokeWidth(2);
    mGoogleMap.addCircle(circle);
    mGoogleMap.addMarker(options);
}

Body:
I think you have to make a function for what ever task you want to perform on map basis on user experience and pass parameter related which value you need to perform your task on map like latitude longitude.

private void yourFunctionName(double lat1, double lng1){
   LatLng location = new LatLng(Double.valueOf(lat1), Double.valueOf(lng1));
   CameraUpdate update = CameraUpdateFactory.newLatLngZoom(location, 15);
   mGoogleMap.moveCamera(update);
   MarkerOptions options = new MarkerOptions()
        .position(location)
        .snippet("I'm around here!!!");
   CircleOptions circle = new CircleOptions()
        .center(location)
        .radius(2000)
        .fillColor(0x55add8e6)
        .strokeColor(Color.BLUE)
        .strokeWidth(2);
   mGoogleMap.addCircle(circle);
   mGoogleMap.addMarker(options);
}

you not need to perform any task in onMapReady() function

@Override
public void onMapReady(GoogleMap googleMap) {
   mGoogleMap = googleMap;

}

store only google map object

mGoogleMap = googleMap;

now perform network operation and call which function you want to perform

  HashMap<String, String> postData = new HashMap<>();
    postData.put("rqstID", rqstID);
    AsyncClass taskDetails = new AsyncClass(AcceptActivity.this, postData,
    "Getting details", new AsyncResponse() {
        @Override
        public void processFinish(String s) {
            Log.d("AcceptActivity", s);
            JSONObject parentObject = null;
            try {
                parentObject = new JSONObject(s);
                JSONArray parentArray = parentObject.getJSONArray("result");
                JSONObject finalObject = parentArray.getJSONObject(0);
                lat1 = finalObject.getString("rqstLat");
                lng1 = finalObject.getString("rqstLng");
                yourFunctionName(Lat1, lng1) // CALL THIS AFTER GETED RESULT
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    });
    taskDetails.execute("http://10.0.2.2/wingman/requestDetails.php");


问:
Is there an explode function in angularjs as PHP does?
In php when you want to explode a variable value just used the explode function:

```<code>$day = date("j", $exploded_line[0]);
</code>```

In angularjs. I want to explode the date. I have $scope.from.

```<code>$scope.from = "2015-01-10";
</code>```

I want to get only the day which is 10. Is there a explode function in angularjs? Thank you  in advance.

答:
You can use in angular like below,

```<code>$scope.beforesplit='9,10,11,12'
$scope.aftersplit= $scope.beforesplit.split(',');
</code>```

$scope.aftersplit have ["9", "10", "11", "12"]

Hope it helps!

Body:
In php when you want to explode a variable value just used the explode function:

$day = date("j", $exploded_line[0]);

In angularjs. I want to explode the date. I have $scope.from.

$scope.from = "2015-01-10";

I want to get only the day which is 10. Is there a explode function in angularjs? Thank you  in advance.

Body:
You can use in angular like below,

$scope.beforesplit='9,10,11,12'
$scope.aftersplit= $scope.beforesplit.split(',');

$scope.aftersplit have ["9", "10", "11", "12"]

Hope it helps!


问:
Creating arrays with your own data structures
From what I understand in order to initialize a array you would call something like this:

```<code>from array import *
array_example = array([type of some sort],[entries into the array])
</code>```

where type of some sort could be anything such as an integer. My question is if there is any way for me use a data structure I have defined(Letter) and use that type when initializing an array.

Here is what I tried:

```<code>x = Letter('A')
i = type(x)
array = array(i,[x])
</code>```

where I then get the following error:

builtins.TypeError: array() argument 1 must be a unicode character, not type

Sorry if it's a stupid question

```<code>class Letter:

    def __init__(self, letter):
        """
        -------------------------------------------------------
        Initialize a Letter object.
        Use: l = Letter(char)
        -------------------------------------------------------
        Preconditions:
            letter - an single uppercase letter of the alphabet (str)
        Postconditions:
            Letter values are set.
        -------------------------------------------------------
        """
        assert letter.isalpha() and letter.isupper(), "Invalid letter"

        self.letter = letter
        self.count = 0
        self.comparisons = 0
        return

    def __str__(self):
        """
        -------------------------------------------------------
        Creates a formatted string of Letter data.
        Use: print(m)
        Use: s = str(m)
        -------------------------------------------------------
        Postconditions:
            returns:
            the value of self.letter (str)
        -------------------------------------------------------
        """
        return "{}: {}, {}".format(self.letter, self.count, self.comparisons)

    def __eq__(self, rs):
        """
        -------------------------------------------------------
        Compares this Letter against another Letter for equality.
        Use: l == rs
        -------------------------------------------------------
        Preconditions:
            rs - [right side] Letter to compare to (Letter)
        Postconditions:
            returns:
            result - True if name and origin match, False otherwise (boolean)
        -------------------------------------------------------
        """
        self.count += 1
        self.comparisons += 1
        result = self.letter == rs.letter
        return result

    def __lt__(self, rs):
        """
        -------------------------------------------------------
        Determines if this Letter comes before another.
        Use: f < rs
        -------------------------------------------------------
        Preconditions:
            rs - [right side] Letter to compare to (Letter)
        Postconditions:
            returns:
            result - True if Letter precedes rs, False otherwise (boolean)
        -------------------------------------------------------
        """
        self.comparisons += 1
        result = self.letter < rs.letter
        return result

    def __le__(self, rs):
        """
        -------------------------------------------------------
        Determines if this Letter precedes or is or equal to another.
        Use: f <= rs
        -------------------------------------------------------
        Preconditions:
            rs - [right side] Letter to compare to (Letter)
        Postconditions:
            returns:
            result - True if this Letter precedes or is equal to rs,
              False otherwise (boolean)
        -------------------------------------------------------
        """
        self.comparisons += 1
        result = self.letter <= rs.letter
        return result
</code>```

答:
As pointed out by in the other answers, the array only works with certain pre-defined types. That means you cannot use it for types/classes you define yourself. Most of the time, there is no reason for using an array, but if you feel that you absolutely need it, you can use a numpy.array:

```<code>import numpy as np

x = Letter('A')
my_array = np.array([x]) # array is a bad name
</code>```

This of course requires numpy to be installed and all your elements will be stored as general objects in the array.

Body:
From what I understand in order to initialize a array you would call something like this:

from array import *
array_example = array([type of some sort],[entries into the array])

where type of some sort could be anything such as an integer. My question is if there is any way for me use a data structure I have defined(Letter) and use that type when initializing an array.

Here is what I tried:

x = Letter('A')
i = type(x)
array = array(i,[x])

where I then get the following error:

builtins.TypeError: array() argument 1 must be a unicode character, not type

Sorry if it's a stupid question

class Letter:

    def __init__(self, letter):
        """
        -------------------------------------------------------
        Initialize a Letter object.
        Use: l = Letter(char)
        -------------------------------------------------------
        Preconditions:
            letter - an single uppercase letter of the alphabet (str)
        Postconditions:
            Letter values are set.
        -------------------------------------------------------
        """
        assert letter.isalpha() and letter.isupper(), "Invalid letter"

        self.letter = letter
        self.count = 0
        self.comparisons = 0
        return

    def __str__(self):
        """
        -------------------------------------------------------
        Creates a formatted string of Letter data.
        Use: print(m)
        Use: s = str(m)
        -------------------------------------------------------
        Postconditions:
            returns:
            the value of self.letter (str)
        -------------------------------------------------------
        """
        return "{}: {}, {}".format(self.letter, self.count, self.comparisons)

    def __eq__(self, rs):
        """
        -------------------------------------------------------
        Compares this Letter against another Letter for equality.
        Use: l == rs
        -------------------------------------------------------
        Preconditions:
            rs - [right side] Letter to compare to (Letter)
        Postconditions:
            returns:
            result - True if name and origin match, False otherwise (boolean)
        -------------------------------------------------------
        """
        self.count += 1
        self.comparisons += 1
        result = self.letter == rs.letter
        return result

    def __lt__(self, rs):
        """
        -------------------------------------------------------
        Determines if this Letter comes before another.
        Use: f < rs
        -------------------------------------------------------
        Preconditions:
            rs - [right side] Letter to compare to (Letter)
        Postconditions:
            returns:
            result - True if Letter precedes rs, False otherwise (boolean)
        -------------------------------------------------------
        """
        self.comparisons += 1
        result = self.letter < rs.letter
        return result

    def __le__(self, rs):
        """
        -------------------------------------------------------
        Determines if this Letter precedes or is or equal to another.
        Use: f <= rs
        -------------------------------------------------------
        Preconditions:
            rs - [right side] Letter to compare to (Letter)
        Postconditions:
            returns:
            result - True if this Letter precedes or is equal to rs,
              False otherwise (boolean)
        -------------------------------------------------------
        """
        self.comparisons += 1
        result = self.letter <= rs.letter
        return result

Body:
As pointed out by in the other answers, the array only works with certain pre-defined types. That means you cannot use it for types/classes you define yourself. Most of the time, there is no reason for using an array, but if you feel that you absolutely need it, you can use a numpy.array:

import numpy as np

x = Letter('A')
my_array = np.array([x]) # array is a bad name

This of course requires numpy to be installed and all your elements will be stored as general objects in the array.


问:
Which Security provided by pentaho in S3 output any encryption?
I am using Pentaho, and used s3 output step to put the file in S3 bucket but I want to know which in-transit security is provided by pentaho and how to apply AES encryption in Pentaho?</p>

答:
Pentaho can encrypt only your password with aes currently.
You can use http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingServerSideEncryption.html
for serverside encryption.
For any transit/client side encryption I`d suggest you to write your own plugin with extending functionality of existing s3 output.

Or submit ticket for desired functioanality at http://jira.pentaho.com .


问:
Resetting WordPress post loop
I'm trying to get a page ID before and after a post loop, the page ID is displaying correctly before the loop, but when I try and display it after the loop it just displays the last post ID of the loop.

I've tried using all of the following to reset the loop and none seem to work:

```<code>wp_reset_postdata()
wp_reset_query()
rewind_posts()
</code>```

The loop code is:

```<code><?php

echo 'Shows the page ID (correct)=' . $post->ID;

$args = array(
'post_type' => 'accommodation',
'posts_per_page' => '9999',
);

$wp_query = new WP_Query( $args );
if ($wp_query->have_posts()) :
while($wp_query->have_posts()) :
$wp_query->the_post(); ?>

<option value="<?php the_ID(); ?>"><?php echo the_title(); ?></option>

<?php endwhile;
else :
esc_html_e('No bookings','sohohotel');
endif;

wp_reset_postdata();

echo 'Shows the ID of the last post in the loop (not correct)=' . $post->ID; ?>
</code>```

Note I'm using WP_Query and not query_posts, so I'm not sure where I'm going wrong, any ideas greatly appreciated!

答:
use this</p>

```<code>$wp_query = new WP_Query( $args );
if ($wp_query->have_posts()) : $wp_query->the_post();
while($wp_query->have_posts()) :
$wp_query->the_post(); ?>

<option value="<?php the_ID(); ?>"><?php the_title(); ?></option>

<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php else :
esc_html_e('No bookings','sohohotel');
endif;
</code>```

Title: Resetting WordPress post loop

Body:
I'm trying to get a page ID before and after a post loop, the page ID is displaying correctly before the loop, but when I try and display it after the loop it just displays the last post ID of the loop.

I've tried using all of the following to reset the loop and none seem to work:

wp_reset_postdata()
wp_reset_query()
rewind_posts()

The loop code is:

<?php

echo 'Shows the page ID (correct)=' . $post->ID;

$args = array(
'post_type' => 'accommodation',
'posts_per_page' => '9999',
);

$wp_query = new WP_Query( $args );
if ($wp_query->have_posts()) :
while($wp_query->have_posts()) :
$wp_query->the_post(); ?>

<option value="<?php the_ID(); ?>"><?php echo the_title(); ?></option>

<?php endwhile;
else :
esc_html_e('No bookings','sohohotel');
endif;

wp_reset_postdata();

echo 'Shows the ID of the last post in the loop (not correct)=' . $post->ID; ?>

Note I'm using WP_Query and not query_posts, so I'm not sure where I'm going wrong, any ideas greatly appreciated!

Body:
use this

$wp_query = new WP_Query( $args );
if ($wp_query->have_posts()) : $wp_query->the_post();
while($wp_query->have_posts()) :
$wp_query->the_post(); ?>

<option value="<?php the_ID(); ?>"><?php the_title(); ?></option>

<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php else :
esc_html_e('No bookings','sohohotel');
endif;