问:
error on wcf application when used as resource to move received data to asp.net web API
so bascially i have a console application acting as a client software receiving data from a WCF feed. this works just fine when i want to do a console.writeline and print the data i'm getting in the console. I don't control the service end of the WCF feed so i have to use this console client software to access the data.

I'm trying to build an ASP.net web api application to pass this data to my own client via REST api. There are other complex reasons i have to do it this way but when it comes down to it i have to. I've built the basic web api for doing a GET to get the information. added the console application as a resource to the web api application but get an error message when I make the GET call.

This is the URL i'm using to make the GET call.

```<code>http://localhost:60421/api/CallData?skillNumber=92
</code>```

After i make this call i get the below error message

[ERROR] System.InvalidOperationException occurred
      HResult=0x80131509
      Message=Could not find default endpoint element that references contract 'FeedService.IFeedService' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element.
      Source=
      StackTrace:

The error occurs in this cs file. I've commented at the line it occurs in.

```<code>using ScoreBoardClientTest.FeedService;

namespace ScoreBoardClientTest
{
    public class FeedServiceAgent : IFeedServiceAgent, IFeedServiceCallback
    {
        private static FeedServiceClient _feedServiceClient;
        private ConnectionStats.ConnectionStatus _connectionStatus;

        private bool _retrying;
        private bool _disposed;

        public FeedServiceAgent()       //(IEventAggregator eventAggregator)
        {
            //Guard.ArgumentNotNull(eventAggregator, "eventAggregator");

            //_eventAggregator = eventAggregator;

            InitializeServiceClient();
        }

        public event MessageReceivedEventHandler MessageReceived;

                public void InitializeServiceClient()
        {

// The error message occurs at the line right below this
                _feedServiceClient = new FeedServiceClient(new InstanceContext(this));
                _feedServiceClient.InnerChannel.Opening += OnOpening;
                _feedServiceClient.InnerChannel.Opened += OnOpened;
                _feedServiceClient.InnerChannel.Closing += OnClosing;
                _feedServiceClient.InnerChannel.Closed += OnClosed;
                _feedServiceClient.InnerChannel.Faulted += OnFaulted;
            }

            private void DisposeServiceClient()
            {
                if (_feedServiceClient == null)
                    return;

                try
                {
                _feedServiceClient.InnerChannel.Opening -= OnOpening;
                _feedServiceClient.InnerChannel.Opened -= OnOpened;
                _feedServiceClient.InnerChannel.Closing -= OnClosing;
                _feedServiceClient.InnerChannel.Closed -= OnClosed;
                _feedServiceClient.InnerChannel.Faulted -= OnFaulted;
                _feedServiceClient.Abort();
            }
            catch
            {
                //Don't care.
            }
            finally
            {
                _feedServiceClient = null;
            }
        }

        public ConnectionStats.ConnectionStatus ConnectionStatus
        {
            get { return _connectionStatus; }
            set
            {
                _connectionStatus = value;
                PublishConnectionStatus();
            }
        }

        private void PublishConnectionStatus()
        {

        }
        private void ProcessCmsData(A cmsData)
        {
            if (cmsData == null)
                return;

            var skill = new Skill();
            var agents = new List<Agent>();
            var cmLookupdata = new List<CmLookupData>();
            //  LookupData lookupdata = new LookupData();
            if (cmsData.C != null && cmsData.C.Length > 0)
                LookupDataTranslator.Translate(cmsData.C, cmLookupdata);

            if (cmsData.AMember != null)
                SkillTranslator.Translate(cmsData.AMember, skill, cmLookupdata);

            if (cmsData.B != null && cmsData.B.Length > 0)
                AgentTranslator.Translate(cmsData.B, agents, cmsData.AMember.A, cmsData.AMember.CmId); // passing skill params to validate the cmid to discard bad data

            var mappedCmsData = new CmsData(skill, agents, cmLookupdata);

            if (MessageReceived != null)
                MessageReceived(this, new MessageReceivedEventArgs(mappedCmsData, null));
        }

        #region FeedServiceClient Channel Events

        private void OnOpening(object sender, EventArgs eventArgs)
        {
            _connectionStatus = ConnectionStats.ConnectionStatus.Connecting;
        }

        private void OnOpened(object sender, EventArgs eventArgs)
        {
            _connectionStatus = ConnectionStats.ConnectionStatus.Connected;
        }

        private void OnClosing(object sender, EventArgs eventArgs)
        {
            _connectionStatus = ConnectionStats.ConnectionStatus.Disconnecting;
        }

        private void OnClosed(object sender, EventArgs eventArgs)
        {
            _connectionStatus = ConnectionStats.ConnectionStatus.Disconnected;
        }

        private void OnFaulted(object sender, EventArgs eventArgs)
        {
            _connectionStatus = ConnectionStats.ConnectionStatus.Disconnected;

            if (!_retrying)
                ThreadPool.QueueUserWorkItem(delegate
                {
                    Reconnect();
                });
        }

        #endregion

        private void Reconnect()
        {
            _retrying = true;

            _connectionStatus = ConnectionStats.ConnectionStatus.Reconnecting;

            // We don't want each client attempting the first reconnect all at the same time.
            var random = new Random();
            int randomWaitValue = random.Next(1, 10000);

            Thread.Sleep(randomWaitValue);

            // Try reconnecting 10 times.
            for (int i = 1; i <= 10; i++)
            {
                try
                {
                    DisposeServiceClient();

                    _feedServiceClient = new FeedServiceClient(new InstanceContext(this));
                    _feedServiceClient.Open();
                    _feedServiceClient.InnerChannel.Opening += OnOpening;
                    _feedServiceClient.InnerChannel.Opened += OnOpened;
                    _feedServiceClient.InnerChannel.Closing += OnClosing;
                    _feedServiceClient.InnerChannel.Closed += OnClosed;
                    _feedServiceClient.InnerChannel.Faulted += OnFaulted;

                    _connectionStatus = ConnectionStats.ConnectionStatus.Reconnected;

                    _retrying = false;

                    //_logger.Info(String.Format("The Scoreboard Client was able to reconnect after {0} retries.", i)) ;

                    return;
                }
                catch (Exception exception)
                {
                    //_logger.Error(String.Format("The Scoreboard Client is unable to reconnect: {0}", exception)) ;

                    // Wait 30 seconds between retries to reduce network congestion.
                    Thread.Sleep(30000);
                }
            }

            //_logger.Info("The Scoreboard Client was unable to reconnect after 10 retries.") ;

            _connectionStatus = ConnectionStats.ConnectionStatus.UnableToConnect;
        }

        #region Implementation of IDisposable

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
                if (disposing)
                {
                    // Dispose managed resources here.
                    DisposeServiceClient();
                }

            _disposed = true;
        }

        #endregion

        public void NotifyCmsData(A cmsData)
        {
            ThreadPool.QueueUserWorkItem(delegate
            {
                ProcessCmsData(cmsData);
            });
        }

        public void Subscribe(string eventTopic, int cmId)
        {
            if (String.IsNullOrEmpty(eventTopic))
                return;

            InvokeAction(x => x.Subscribe(eventTopic, cmId));
        }

        public void Unsubscribe(string eventTopic, int cmId)
        {
            if (String.IsNullOrEmpty(eventTopic))
                return;

            InvokeAction(x => x.Unsubscribe(eventTopic, cmId));
        }

        public void RefreshCmsData()
        {
            throw new NotImplementedException();
        }

        public LookupData GetLookupData()
        {
            LookupData lookupdata = new LookupData();
            try
            {
                LookupDataTranslator.Translate(_feedServiceClient.GetLookupData(), lookupdata);
            }
            catch (Exception e)
            {
                //if (_logger != null)
                //    _logger.Error("Exception in finding the lookup data. Exception:" + e.Message);
                throw e;
            }
            return lookupdata;
        }

        private void InvokeAction(Action<IFeedService> action)
        {
            try
            {
                action(_feedServiceClient);
            }
            catch (Exception exception)
            {
                //_logger.Error(" Exception in FeedService InvokeAction:" + exception.ToString());

                _connectionStatus = ConnectionStats.ConnectionStatus.UnableToConnect;
            }
        }
    }
}
</code>```

The console application has a properly configured config file for the console application which is what the error message suggests does not exist. also, as i said above the console application functions fully by itself.

QUESTION
How do you use a WCF console application as a resource for a web api successfully?

答: I had to include the FeedService web URL inside of the web api service as long as the console application</p>

Body:
so bascially i have a console application acting as a client software receiving data from a WCF feed. this works just fine when i want to do a console.writeline and print the data i'm getting in the console. I don't control the service end of the WCF feed so i have to use this console client software to access the data.

I'm trying to build an ASP.net web api application to pass this data to my own client via REST api. There are other complex reasons i have to do it this way but when it comes down to it i have to. I've built the basic web api for doing a GET to get the information. added the console application as a resource to the web api application but get an error message when I make the GET call.

This is the URL i'm using to make the GET call.

http://localhost:60421/api/CallData?skillNumber=92

After i make this call i get the below error message

[ERROR] System.InvalidOperationException occurred
      HResult=0x80131509
      Message=Could not find default endpoint element that references contract 'FeedService.IFeedService' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element.
      Source=
      StackTrace:

The error occurs in this cs file. I've commented at the line it occurs in.

using ScoreBoardClientTest.FeedService;

namespace ScoreBoardClientTest
{
    public class FeedServiceAgent : IFeedServiceAgent, IFeedServiceCallback
    {
        private static FeedServiceClient _feedServiceClient;
        private ConnectionStats.ConnectionStatus _connectionStatus;

        private bool _retrying;
        private bool _disposed;

        public FeedServiceAgent()       //(IEventAggregator eventAggregator)
        {
            //Guard.ArgumentNotNull(eventAggregator, "eventAggregator");

            //_eventAggregator = eventAggregator;

            InitializeServiceClient();
        }

        public event MessageReceivedEventHandler MessageReceived;

                public void InitializeServiceClient()
        {

// The error message occurs at the line right below this
                _feedServiceClient = new FeedServiceClient(new InstanceContext(this));
                _feedServiceClient.InnerChannel.Opening += OnOpening;
                _feedServiceClient.InnerChannel.Opened += OnOpened;
                _feedServiceClient.InnerChannel.Closing += OnClosing;
                _feedServiceClient.InnerChannel.Closed += OnClosed;
                _feedServiceClient.InnerChannel.Faulted += OnFaulted;
            }

            private void DisposeServiceClient()
            {
                if (_feedServiceClient == null)
                    return;

                try
                {
                _feedServiceClient.InnerChannel.Opening -= OnOpening;
                _feedServiceClient.InnerChannel.Opened -= OnOpened;
                _feedServiceClient.InnerChannel.Closing -= OnClosing;
                _feedServiceClient.InnerChannel.Closed -= OnClosed;
                _feedServiceClient.InnerChannel.Faulted -= OnFaulted;
                _feedServiceClient.Abort();
            }
            catch
            {
                //Don't care.
            }
            finally
            {
                _feedServiceClient = null;
            }
        }

        public ConnectionStats.ConnectionStatus ConnectionStatus
        {
            get { return _connectionStatus; }
            set
            {
                _connectionStatus = value;
                PublishConnectionStatus();
            }
        }

        private void PublishConnectionStatus()
        {

        }
        private void ProcessCmsData(A cmsData)
        {
            if (cmsData == null)
                return;

            var skill = new Skill();
            var agents = new List<Agent>();
            var cmLookupdata = new List<CmLookupData>();
            //  LookupData lookupdata = new LookupData();
            if (cmsData.C != null && cmsData.C.Length > 0)
                LookupDataTranslator.Translate(cmsData.C, cmLookupdata);

            if (cmsData.AMember != null)
                SkillTranslator.Translate(cmsData.AMember, skill, cmLookupdata);

            if (cmsData.B != null && cmsData.B.Length > 0)
                AgentTranslator.Translate(cmsData.B, agents, cmsData.AMember.A, cmsData.AMember.CmId); // passing skill params to validate the cmid to discard bad data

            var mappedCmsData = new CmsData(skill, agents, cmLookupdata);

            if (MessageReceived != null)
                MessageReceived(this, new MessageReceivedEventArgs(mappedCmsData, null));
        }

        #region FeedServiceClient Channel Events

        private void OnOpening(object sender, EventArgs eventArgs)
        {
            _connectionStatus = ConnectionStats.ConnectionStatus.Connecting;
        }

        private void OnOpened(object sender, EventArgs eventArgs)
        {
            _connectionStatus = ConnectionStats.ConnectionStatus.Connected;
        }

        private void OnClosing(object sender, EventArgs eventArgs)
        {
            _connectionStatus = ConnectionStats.ConnectionStatus.Disconnecting;
        }

        private void OnClosed(object sender, EventArgs eventArgs)
        {
            _connectionStatus = ConnectionStats.ConnectionStatus.Disconnected;
        }

        private void OnFaulted(object sender, EventArgs eventArgs)
        {
            _connectionStatus = ConnectionStats.ConnectionStatus.Disconnected;

            if (!_retrying)
                ThreadPool.QueueUserWorkItem(delegate
                {
                    Reconnect();
                });
        }

        #endregion

        private void Reconnect()
        {
            _retrying = true;

            _connectionStatus = ConnectionStats.ConnectionStatus.Reconnecting;

            // We don't want each client attempting the first reconnect all at the same time.
            var random = new Random();
            int randomWaitValue = random.Next(1, 10000);

            Thread.Sleep(randomWaitValue);

            // Try reconnecting 10 times.
            for (int i = 1; i <= 10; i++)
            {
                try
                {
                    DisposeServiceClient();

                    _feedServiceClient = new FeedServiceClient(new InstanceContext(this));
                    _feedServiceClient.Open();
                    _feedServiceClient.InnerChannel.Opening += OnOpening;
                    _feedServiceClient.InnerChannel.Opened += OnOpened;
                    _feedServiceClient.InnerChannel.Closing += OnClosing;
                    _feedServiceClient.InnerChannel.Closed += OnClosed;
                    _feedServiceClient.InnerChannel.Faulted += OnFaulted;

                    _connectionStatus = ConnectionStats.ConnectionStatus.Reconnected;

                    _retrying = false;

                    //_logger.Info(String.Format("The Scoreboard Client was able to reconnect after {0} retries.", i)) ;

                    return;
                }
                catch (Exception exception)
                {
                    //_logger.Error(String.Format("The Scoreboard Client is unable to reconnect: {0}", exception)) ;

                    // Wait 30 seconds between retries to reduce network congestion.
                    Thread.Sleep(30000);
                }
            }

            //_logger.Info("The Scoreboard Client was unable to reconnect after 10 retries.") ;

            _connectionStatus = ConnectionStats.ConnectionStatus.UnableToConnect;
        }

        #region Implementation of IDisposable

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
                if (disposing)
                {
                    // Dispose managed resources here.
                    DisposeServiceClient();
                }

            _disposed = true;
        }

        #endregion

        public void NotifyCmsData(A cmsData)
        {
            ThreadPool.QueueUserWorkItem(delegate
            {
                ProcessCmsData(cmsData);
            });
        }

        public void Subscribe(string eventTopic, int cmId)
        {
            if (String.IsNullOrEmpty(eventTopic))
                return;

            InvokeAction(x => x.Subscribe(eventTopic, cmId));
        }

        public void Unsubscribe(string eventTopic, int cmId)
        {
            if (String.IsNullOrEmpty(eventTopic))
                return;

            InvokeAction(x => x.Unsubscribe(eventTopic, cmId));
        }

        public void RefreshCmsData()
        {
            throw new NotImplementedException();
        }

        public LookupData GetLookupData()
        {
            LookupData lookupdata = new LookupData();
            try
            {
                LookupDataTranslator.Translate(_feedServiceClient.GetLookupData(), lookupdata);
            }
            catch (Exception e)
            {
                //if (_logger != null)
                //    _logger.Error("Exception in finding the lookup data. Exception:" + e.Message);
                throw e;
            }
            return lookupdata;
        }

        private void InvokeAction(Action<IFeedService> action)
        {
            try
            {
                action(_feedServiceClient);
            }
            catch (Exception exception)
            {
                //_logger.Error(" Exception in FeedService InvokeAction:" + exception.ToString());

                _connectionStatus = ConnectionStats.ConnectionStatus.UnableToConnect;
            }
        }
    }
}

The console application has a properly configured config file for the console application which is what the error message suggests does not exist. also, as i said above the console application functions fully by itself.

QUESTION
How do you use a WCF console application as a resource for a web api successfully?


来源: stackexchange

问:
How can I manually tell an owner-drawn WPF Control to refresh/redraw without executing measure or arrange passes?
We are doing custom drawing in a control subclass's OnRender.  This drawing code is based on an external trigger and data.  As such, whenever the trigger fires, we need to re-render the control based on that data. What we're trying to do is find out how to force the control to re-render but without going through an entire layout pass.

As stated above, most answers I've seen revolve around invalidating the Visual which invalidates the layout which forces new measure and arrange passes which is very expensive, especially for very complex visual trees as ours is.  But again, the layout does not change, nor does the VisualTree. The only thing that does is the external data which gets rendered differently. As such, this is strictly a pure rendering issue.

Again, we're just looking for a simple way to tell the control that it needs to re-execute OnRender.  I have seen one 'hack' in which you create a new DependencyProperty and register it with 'AffectsRender' which you just set to some value when you want to refresh the control, but I'm more interested in what's going on inside the default implementation for those properties: what they call to affect that behavior.

Update:

Well, it looks like there isn't any such call as even the AffectsRender flag still causes an Arrange pass internally (as per CodeNaked's answer below) but I've posted a second answer that shows the built-in behaviors as well as a work-around to suppress your layout pass code from running with a simple nullable size as a flag. See below.

答:
You shouldn't be calling InvalidateVisual() unless the size of your control changes, and even then there are other ways to cause re-layout.

To efficiently update the visual of a control without changing it's size. Use a DrawingGroup. You create the DrawingGroup and put it into the DrawingContext during OnRender() and then anytime after that you can Open() the DrawingGroup to change it's visual drawing commands, and WPF will automatically and efficiently re-render that portion of the UI. (you can also use this technique with RenderTargetBitmap if you'd prefer to have bitmap which you can make incremental changes to, rather than redrawing every time)

This is what it looks like:

```<code>DrawingGroup backingStore = new DrawingGroup();

protected override void OnRender(DrawingContext drawingContext) {
    base.OnRender(drawingContext);

    Render(); // put content into our backingStore
    drawingContext.DrawDrawing(backingStore);
}

// I can call this anytime, and it'll update my visual drawing
// without ever triggering layout or OnRender()
private void Render() {
    var drawingContext = backingStore.Open();
    Render(drawingContext);
    drawingContext.Close();
}

private void Render(DrawingContext drawingContext) {
    // put your render code here
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You shouldn't be calling InvalidateVisual() unless the size of your control changes, and even then there are other ways to cause re-layout.

To efficiently update the visual of a control without changing it's size. Use a DrawingGroup. You create the DrawingGroup and put it into the DrawingContext during OnRender() and then anytime after that you can Open() the DrawingGroup to change it's visual drawing commands, and WPF will automatically and efficiently re-render that portion of the UI. (you can also use this technique with RenderTargetBitmap if you'd prefer to have bitmap which you can make incremental changes to, rather than redrawing every time)

This is what it looks like:

DrawingGroup backingStore = new DrawingGroup();

protected override void OnRender(DrawingContext drawingContext) {
    base.OnRender(drawingContext);

    Render(); // put content into our backingStore
    drawingContext.DrawDrawing(backingStore);
}

// I can call this anytime, and it'll update my visual drawing
// without ever triggering layout or OnRender()
private void Render() {
    var drawingContext = backingStore.Open();
    Render(drawingContext);
    drawingContext.Close();
}

private void Render(DrawingContext drawingContext) {
    // put your render code here
}


问:
How to implement http long polling in Angular 2
I have a use case as follows:

User selects a video to be uploaded to their profile.

Angular sends a request to node.js server which returns an Amazon S3 pre-signed URL.

Browser 'directly' uploads the file to S3.

Elastictranscoder kicks in to transcode the video.

AWS-SNS follows an https endpoint to inform the node.js back-end of  transcoding's completion.

How to reflect this fact that the video is now available on the Angular side?

I'm doing something similar to the following and it is working fine, but I'm not so sure if the error-case is being handled correctly? Should I be doing anything more?

```<code> startLp(): Observable<any> {
   return this.http
     .get("/getvideostatus?video-id=blah", { headers: this.headers })
     .map(res => {
       return res.json();
     })
     .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
}
</code>```

This is just a regular http request, the only difference is the server not returning the response immediately.

Would this constitute a valid http long poll?

答:
This is what I ended up doing:</p>

```<code>public startLp(): Observable<any> {
let that = this;
let doLp = function(): Observable<any> {
  return that.http
    .get("/getvideostatus?video-id=blah", { headers: that.headers })
    .map(res => {
      return res.json().data
    })
    .catch((error: any) => {
      return doLp();
    });
};

return doLp();
}
</code>```

Body:
I have a use case as follows:

User selects a video to be uploaded to their profile.

Angular sends a request to node.js server which returns an Amazon S3 pre-signed URL.

Browser 'directly' uploads the file to S3.

Elastictranscoder kicks in to transcode the video.

AWS-SNS follows an https endpoint to inform the node.js back-end of  transcoding's completion.

How to reflect this fact that the video is now available on the Angular side?

I'm doing something similar to the following and it is working fine, but I'm not so sure if the error-case is being handled correctly? Should I be doing anything more?

 startLp(): Observable<any> {
   return this.http
     .get("/getvideostatus?video-id=blah", { headers: this.headers })
     .map(res => {
       return res.json();
     })
     .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
}

This is just a regular http request, the only difference is the server not returning the response immediately.

Would this constitute a valid http long poll?

Body:
This is what I ended up doing:

public startLp(): Observable<any> {
let that = this;
let doLp = function(): Observable<any> {
  return that.http
    .get("/getvideostatus?video-id=blah", { headers: that.headers })
    .map(res => {
      return res.json().data
    })
    .catch((error: any) => {
      return doLp();
    });
};

return doLp();
}


问:
APEX - Parsing a recursive JSON
I am programming to salesforce (APEX).
The input is complex and recursive JSON. Something like

```<code>{
    "id":"0",
    "children":[
        {
            "id":"1",
            "children":[...]
        },
        {
            "id":"2",
            "children":[...]
        }
    ]
}
</code>```

I need a way to iterate a complex and recursive JSON (in APEX).

anyone can help?

Thanks,

Hagai

答:
If you know the names of all the attributes in your JSON object, you can create classes to represent them and then deserialize.  For instance:

```<code>public class myObject {
  public String id;
  public List<myObject> children;
}
</code>```

Then write a method that returns the children

```<code>static List<myObject> getChildren(myObject parent){
    List<myObject> children = new List<myObject>();
    for ( myObject c : parent.children ){
        children.addAll( getChildren(c) );
        children.add(c);
    }
    return children;
}
</code>```

And finally put the two together:

```<code>myObject parent = (myObject)JSON.deserialize(jsonString,myObject.class);
List<myObject> all = new List<myObject>();
all.add(parent);
all.addAll(getChildren(parent));
</code>```

Title: APEX - Parsing a recursive JSON

Body:
I am programming to salesforce (APEX).
The input is complex and recursive JSON. Something like

{
    "id":"0",
    "children":[
        {
            "id":"1",
            "children":[...]
        },
        {
            "id":"2",
            "children":[...]
        }
    ]
}

I need a way to iterate a complex and recursive JSON (in APEX).

anyone can help?

Thanks,

Hagai

Body:
If you know the names of all the attributes in your JSON object, you can create classes to represent them and then deserialize.  For instance:

public class myObject {
  public String id;
  public List<myObject> children;
}

Then write a method that returns the children

static List<myObject> getChildren(myObject parent){
    List<myObject> children = new List<myObject>();
    for ( myObject c : parent.children ){
        children.addAll( getChildren(c) );
        children.add(c);
    }
    return children;
}

And finally put the two together:

myObject parent = (myObject)JSON.deserialize(jsonString,myObject.class);
List<myObject> all = new List<myObject>();
all.add(parent);
all.addAll(getChildren(parent));


问:
Removing the largest variance from a group
If I have a set of objects each with the same description, but with different amounts.

```<code>{

    {
    "_id": "101",
    "description": "DD from my employer1",
    "amount": 1000.33
    },
    {
    "_id": "102",
    "description": "DD from my employer1",
    "amount": 1000.34
    },
    {
    "_id": "103",
    "description": "DD from my employer1",
    "amount": 999.35
    },
    {
    "_id": "104",
    "description": "DD from my employer1"",
    "amount": 5000.00
    },
    {
    "_id": "105",
    "description": "DD from my employer2",
    "amount": 2000.01
    },
    {
    "_id": "106",
    "description": "DD from my employer2",
    "amount": 1999.33
    },
    {
    "_id": "107",
    "description": "DD from my employer2",
    "amount": 1999.33
    }

}
</code>```

Below, I am able to group them using the following:

```<code>{
{
    "$group": {
        "_id": {
            "$subtract": [
                {
                    "$trunc": "$amount"
                },
                {
                    "$mod": [
                        {
                            "$trunc": "$amount"
                        },
                        10
                    ]
                }
            ]
        },
        "results": {
            "$push": "$_id"
        }
    }
},
{
    "$redact": {
        "$cond": {
            "if": {
                "$gt": [
                    {
                        "$size": "$results"
                    },
                    1
                ]
            },
            "then": "$$KEEP",
            "else": "$$PRUNE"
        }
    }
},
{
    "$unwind": "$results"
},
{
    "$group": {
        "_id": null,
        "results": {
            "$push": "$results"
        }
    }
}
}
</code>```

Is there a way to include all the amounts in the group (_ids: 101, 102, and 103 plus 105,106,107) even if they have a small difference, but exclude the bonus amount, which in the sample above as _id 104?

I am looking for a simple array output of just the _ids.

Looking for the following result:

```<code>{ "result": [ "101", "102", "103", "105", "106", "107" ] }
</code>```

答:
I think it's all a bit subjective to the actual data, but if it's simply about a significant "positive" difference to the "average" payment then that is the best algorithm to apply:

```<code>db.collection.aggregate([
  { "$group": {
    "_id": "$description",
    "avg": { "$avg": "$amount" },
    "docs": { "$push": { "_id": "$_id", "amount": "$amount" } }
  }},
  { "$addFields": {
    "docs": {
      "$filter": {
        "input": "$docs",
        "as": "doc",
        "cond": {
          "$gt": [ "$avg", { "$subtract": [ "$$doc.amount", "$avg" ] } ]
        }
      }
    }
  }},
  { "$unwind": "$docs" },
  { "$group": {
    "_id": null,
    "results": { "$push": "$docs._id" }
  }}
])
</code>```

From your given data this would exclude the "104" amount since the difference from the amount to the average amounts from "employer 1" is greater than the average itself. This will be the case for a large "upwards" variation.

As with all "grouping" methods that rely on creating an array within the grouped document, you need to be careful in real world scenarios to not break the BSON limit.

Body:
If I have a set of objects each with the same description, but with different amounts.

{

    {
    "_id": "101",
    "description": "DD from my employer1",
    "amount": 1000.33
    },
    {
    "_id": "102",
    "description": "DD from my employer1",
    "amount": 1000.34
    },
    {
    "_id": "103",
    "description": "DD from my employer1",
    "amount": 999.35
    },
    {
    "_id": "104",
    "description": "DD from my employer1"",
    "amount": 5000.00
    },
    {
    "_id": "105",
    "description": "DD from my employer2",
    "amount": 2000.01
    },
    {
    "_id": "106",
    "description": "DD from my employer2",
    "amount": 1999.33
    },
    {
    "_id": "107",
    "description": "DD from my employer2",
    "amount": 1999.33
    }

}

Below, I am able to group them using the following:

{
{
    "$group": {
        "_id": {
            "$subtract": [
                {
                    "$trunc": "$amount"
                },
                {
                    "$mod": [
                        {
                            "$trunc": "$amount"
                        },
                        10
                    ]
                }
            ]
        },
        "results": {
            "$push": "$_id"
        }
    }
},
{
    "$redact": {
        "$cond": {
            "if": {
                "$gt": [
                    {
                        "$size": "$results"
                    },
                    1
                ]
            },
            "then": "$$KEEP",
            "else": "$$PRUNE"
        }
    }
},
{
    "$unwind": "$results"
},
{
    "$group": {
        "_id": null,
        "results": {
            "$push": "$results"
        }
    }
}
}

Is there a way to include all the amounts in the group (_ids: 101, 102, and 103 plus 105,106,107) even if they have a small difference, but exclude the bonus amount, which in the sample above as _id 104?

I am looking for a simple array output of just the _ids.

Looking for the following result:

{ "result": [ "101", "102", "103", "105", "106", "107" ] }

Body:
I think it's all a bit subjective to the actual data, but if it's simply about a significant "positive" difference to the "average" payment then that is the best algorithm to apply:

db.collection.aggregate([
  { "$group": {
    "_id": "$description",
    "avg": { "$avg": "$amount" },
    "docs": { "$push": { "_id": "$_id", "amount": "$amount" } }
  }},
  { "$addFields": {
    "docs": {
      "$filter": {
        "input": "$docs",
        "as": "doc",
        "cond": {
          "$gt": [ "$avg", { "$subtract": [ "$$doc.amount", "$avg" ] } ]
        }
      }
    }
  }},
  { "$unwind": "$docs" },
  { "$group": {
    "_id": null,
    "results": { "$push": "$docs._id" }
  }}
])

From your given data this would exclude the "104" amount since the difference from the amount to the average amounts from "employer 1" is greater than the average itself. This will be the case for a large "upwards" variation.

As with all "grouping" methods that rely on creating an array within the grouped document, you need to be careful in real world scenarios to not break the BSON limit.


问:
Read highlighted text from a picture using tesseract
I am trying to read text from an image using tesseract, the picture is high qualit, so tesseract is able to read the text with 95% accuracy, which is OK for me at this point, however tesseract in unable to read the text which is highlighted (selected), Please refer the PIC

How can i read the text from selected area using tesseract, Is there any way to identify which word is highlighted in the image ?

Code used to read and convert the text from image as below.

tesseract::TessBaseAPI *myOCR = new tesseract::TessBaseAPI();

//cout << "hello" << endl;

if (myOCR->Init("C:\\QTSoftware\\IODriver\\", "eng")) {

    SaveLineLog(brdInd, "Unable to initialize tesseract engine", __LINE__);

    return RC_TESSERACT_ENG_FAILURE;

    //fprintf(stderr, "Could not initialize tesseract.\n");

    //return RC_THREAD_FAILURE;
    //exit(1);
}

SaveLineLog(brdInd, "tesseract engine is UP :)", __LINE__);

//strcpy_s(fileName, "C:\\TEMP\\T481Logs\\FrameOCR23_0.jpg");

FILE *pFile;

fopen_s(&pFile,fileName, "r");    // Open picture

PIX* pix;                         // Image format from `leptonica`

pix = pixReadStreamBmp(pFile);

fclose(pFile);

//Pix *pix = pixRead(fileName);

//Pix *pix = pixReadStreamBmp(fileName);

//cout << "Tesseract - Pix : " << pix << endl;

if (pix == NULL)
{
   SaveLineLog(brdInd, "Pix failure", __LINE__);

   return RC_TESSERACT_PIX_FAILURE;
}

myOCR->SetImage(pix);

char* outText = myOCR->GetUTF8Text();
```

答:
If all images have this format, you can first invert colors, then use Threshold binarization to get rid of this shadow.
It's better always to pre-process and provide clean image to the OCR engine, it will probably enhance the detection percent too.</p>

ContentLicense: CC BY-SA 4.0


问:
Restrict date in jquery datepicker based on another datepicker or textbox
I have two text boxes with a datepicker hooked up to them. The text boxes are for start date and end date. The first datepicker is setup so that the user cannot choose a date before today, but can choose any date in the future.

How can I setup the second datepicker so that it cannot choose a date before the date chosen in the first date picker? For example: If today is 12/11/10 and I choose 12/15/10 in the first datepicker, then the second date picker shouldn't be able to choose anything before 12/15/10.

Heres what I have so far:

```<code>$("#txtStartDate").datepicker({ minDate: 0 });
$("#txtEndDate").datepicker({});
</code>```

答:
Update:

The approach above set the minDate only on creation time.
I used the onSelect event to change the minDate option of the second datepicker like this:

```<code>$("#txtStartDate").datepicker({
  showOn: "both",
  onSelect: function(dateText, inst){
     $("#txtEndDate").datepicker("option","minDate",
     $("#txtStartDate").datepicker("getDate"));
  }
});
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have two text boxes with a datepicker hooked up to them. The text boxes are for start date and end date. The first datepicker is setup so that the user cannot choose a date before today, but can choose any date in the future.

How can I setup the second datepicker so that it cannot choose a date before the date chosen in the first date picker? For example: If today is 12/11/10 and I choose 12/15/10 in the first datepicker, then the second date picker shouldn't be able to choose anything before 12/15/10.

Heres what I have so far:

$("#txtStartDate").datepicker({ minDate: 0 });
$("#txtEndDate").datepicker({});

Body:
Update:

The approach above set the minDate only on creation time.
I used the onSelect event to change the minDate option of the second datepicker like this:

$("#txtStartDate").datepicker({
  showOn: "both",
  onSelect: function(dateText, inst){
     $("#txtEndDate").datepicker("option","minDate",
     $("#txtStartDate").datepicker("getDate"));
  }
});


问:
Unable to pass data to web method always getting null c#
I am unable to send data from my client app to a web method, i dont actually know what i am doing wrong any help would be appreciate.

Client:

```<code>    public void syncClient(Customer c)
    {
        try
        {
                var datos = new JavaScriptSerializer().Serialize(c);
                DataContractJsonSerializer ser =
                new DataContractJsonSerializer(typeof(string));
                MemoryStream mem = new MemoryStream();
                ser.WriteObject(mem, datos);

                string data = Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);

                string url = store.ParentUrl + "Api/syncClientFromChild";

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.ContentType = @"application/json"; //set the content type to JSON
                request.Method = "POST";

                System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();

                byte[] send = encoding.GetBytes(data);
                request.ContentLength = send.Length;

                using (Stream newStream = request.GetRequestStream())
                {
                    newStream.Write(send, 0, send.Length);
                }

                WebResponse ws1 = request.GetResponse();
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                ApiCtrlResponse response = serializer.Deserialize<ApiCtrlResponse>(serializer.Serialize(ws1.GetResponseStream()));
                if (response.success == true)
                {
                    c.Synced = true;
                    _customerService.UpdateCustomer(c);
                }

        }
        catch (Exception A)
        {
        }
    }
</code>```

I believe thats fine, but the other method i always get null in the string i need to receive:

```<code>[System.Web.Services.WebMethod]
public ActionResult syncClientFromChild(string Customer)
{
    // do something
}
</code>```

What i am missing ? Thanks in advance !

答:
use a Model to accept  Http Post,try to not use string,like</p>

```<code>public class ReceiveModel
{
string Customer;
}

public ActionResult syncClientFromChild(ReceiveModel model)
</code>```

Body:
I am unable to send data from my client app to a web method, i dont actually know what i am doing wrong any help would be appreciate.

Client:

    public void syncClient(Customer c)
    {
        try
        {
                var datos = new JavaScriptSerializer().Serialize(c);
                DataContractJsonSerializer ser =
                new DataContractJsonSerializer(typeof(string));
                MemoryStream mem = new MemoryStream();
                ser.WriteObject(mem, datos);

                string data = Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);

                string url = store.ParentUrl + "Api/syncClientFromChild";

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.ContentType = @"application/json"; //set the content type to JSON
                request.Method = "POST";

                System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();

                byte[] send = encoding.GetBytes(data);
                request.ContentLength = send.Length;

                using (Stream newStream = request.GetRequestStream())
                {
                    newStream.Write(send, 0, send.Length);
                }

                WebResponse ws1 = request.GetResponse();
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                ApiCtrlResponse response = serializer.Deserialize<ApiCtrlResponse>(serializer.Serialize(ws1.GetResponseStream()));
                if (response.success == true)
                {
                    c.Synced = true;
                    _customerService.UpdateCustomer(c);
                }

        }
        catch (Exception A)
        {
        }
    }

I believe thats fine, but the other method i always get null in the string i need to receive:

[System.Web.Services.WebMethod]
public ActionResult syncClientFromChild(string Customer)
{
    // do something
}

What i am missing ? Thanks in advance !

Body:
use a Model to accept  Http Post,try to not use string,like

public class ReceiveModel
{
string Customer;
}

public ActionResult syncClientFromChild(ReceiveModel model)


问:
Basic UIAlertController Unable to satisfy constraints
```<code> UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title
                                                                         message:message
                                                                  preferredStyle:UIAlertControllerStyleAlert];

[alertController show];
</code>```

This code is causing the following error:

```<code>...[LayoutConstraints] Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want.
Try this:
    (1) look at each constraint and try to figure out which you don't expect;
    (2) find the code that added the unwanted constraint or constraints and fix it.
(Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
(
"<NSAutoresizingMaskLayoutConstraint:0x7af32260 h=-&- v=-&- UITransitionView:0x7ae60c70.height == UIWindow:0x7aebc600.height   (active)>",
"<NSAutoresizingMaskLayoutConstraint:0x7af9b6f0 h=--- v=--- UIWindow:0x7aebc600.height == 0   (active)>",
"<NSLayoutConstraint:0x79f1f050 UIView:0x7ae6ec40.height >= 44   (active)>",
"<NSLayoutConstraint:0x79f1d6a0 _UIAlertControllerView:0x7a26ce00'Error'.height == UIView:0x7ae6ec40.height   (active)>",
"<NSLayoutConstraint:0x7aafb360 _UIAlertControllerView:0x7a26ce00'Error'.centerY == UITransitionView:0x7ae60c70.centerY   (active)>",
"<NSLayoutConstraint:0x7afb81e0 V:|-(>=0)-[_UIAlertControllerView:0x7a26ce00'Error']   (active, names: '|':UITransitionView:0x7ae60c70 )>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x79f1f050 UIView:0x7ae6ec40.height >= 44   (active)>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to     catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView  listed in <UIKit/UIView.h> may also be helpful.
</code>```

Note: In the wider context of what my app is doing, I have no choice but to use [alertController show]

答:
You have UIWindow:0x7aebc600.height == 0. I'm guessing that your issue.

Obviously your window height shouldn't be set to 0, otherwise whatever that you add to it won't have enough height.

Additionally you can find a very good debugging tutorial from here. On the page search for "Will attempt to recover by breaking constraint"

Body:
 UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title
                                                                         message:message
                                                                  preferredStyle:UIAlertControllerStyleAlert];

[alertController show];

This code is causing the following error:

...[LayoutConstraints] Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want.
Try this:
    (1) look at each constraint and try to figure out which you don't expect;
    (2) find the code that added the unwanted constraint or constraints and fix it.
(Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
(
"<NSAutoresizingMaskLayoutConstraint:0x7af32260 h=-&- v=-&- UITransitionView:0x7ae60c70.height == UIWindow:0x7aebc600.height   (active)>",
"<NSAutoresizingMaskLayoutConstraint:0x7af9b6f0 h=--- v=--- UIWindow:0x7aebc600.height == 0   (active)>",
"<NSLayoutConstraint:0x79f1f050 UIView:0x7ae6ec40.height >= 44   (active)>",
"<NSLayoutConstraint:0x79f1d6a0 _UIAlertControllerView:0x7a26ce00'Error'.height == UIView:0x7ae6ec40.height   (active)>",
"<NSLayoutConstraint:0x7aafb360 _UIAlertControllerView:0x7a26ce00'Error'.centerY == UITransitionView:0x7ae60c70.centerY   (active)>",
"<NSLayoutConstraint:0x7afb81e0 V:|-(>=0)-[_UIAlertControllerView:0x7a26ce00'Error']   (active, names: '|':UITransitionView:0x7ae60c70 )>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x79f1f050 UIView:0x7ae6ec40.height >= 44   (active)>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to     catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView  listed in <UIKit/UIView.h> may also be helpful.

Note: In the wider context of what my app is doing, I have no choice but to use [alertController show]


问:
Shorten C++ function input parameters?
Our group recently switched to C++. My supervisor is kind enough to provide a template which consists of a bunch of classes and relevant methods. The problem I found is that most methods require a lot of input parameters, like this:

```<code>void AdvectionReactionDiffusion::boundary(const arma::Col<double>& n, const arma::Col<double>& u, const arma::Col<double>& uhat, const arma::Col<double>& fhat, arma::Col<double>& fb, arma::Mat<double>& fb_u, arma::Mat<double>& fb_uhat, arma::Mat<double>& fb_fhat) const {}
</code>```

So, for the sake of better readability and less human mistakes, is there any good ways to shorten these inputs without breaking the current structure of the code?

I come from a Python background, and what I will do in Python is wrap relevant inputs in a named tuple and throw it at the function. But I have no idea of how to apply the similar trick in C++.

答:
If you read the docs on Col and Mat you will find

Combining this with using namespace arma; in your cpp file (never in the header!!!) you can do

```<code>void AdvectionReactionDiffusion::boundary(const vec& n,
                                          const vec& u,
                                          const vec& uhat,
                                          const vec& fhat,
                                          vec& fb,
                                          mat& fb_u,
                                          mat& fb_uhat,
                                          mat& fb_fhat) const {}
</code>```

You tagged this question c++11 so instead of having output parameters you could also return a std::tuple.

```<code>std::tuple<vec,mat,mat,mat>
AdvectionReactionDiffusion::boundary(const vec& n,
                                     const vec& u,
                                     const vec& uhat,
                                     const vec& fhat) const {}
</code>```

which you can then unpack using std::tie

```<code>std::tie(fb, fb_u, fb_uhat, fb_fhat) = ARD.boundary(n,u,uhat,fhat);
</code>```

You can of course do the same to the input parameters.

Title: Shorten C++ function input parameters?

Body:
Our group recently switched to C++. My supervisor is kind enough to provide a template which consists of a bunch of classes and relevant methods. The problem I found is that most methods require a lot of input parameters, like this:

void AdvectionReactionDiffusion::boundary(const arma::Col<double>& n, const arma::Col<double>& u, const arma::Col<double>& uhat, const arma::Col<double>& fhat, arma::Col<double>& fb, arma::Mat<double>& fb_u, arma::Mat<double>& fb_uhat, arma::Mat<double>& fb_fhat) const {}

So, for the sake of better readability and less human mistakes, is there any good ways to shorten these inputs without breaking the current structure of the code?

I come from a Python background, and what I will do in Python is wrap relevant inputs in a named tuple and throw it at the function. But I have no idea of how to apply the similar trick in C++.

Body:
If you read the docs on Col and Mat you will find

Combining this with using namespace arma; in your cpp file (never in the header!!!) you can do

void AdvectionReactionDiffusion::boundary(const vec& n,
                                          const vec& u,
                                          const vec& uhat,
                                          const vec& fhat,
                                          vec& fb,
                                          mat& fb_u,
                                          mat& fb_uhat,
                                          mat& fb_fhat) const {}

You tagged this question c++11 so instead of having output parameters you could also return a std::tuple.

std::tuple<vec,mat,mat,mat>
AdvectionReactionDiffusion::boundary(const vec& n,
                                     const vec& u,
                                     const vec& uhat,
                                     const vec& fhat) const {}

which you can then unpack using std::tie

std::tie(fb, fb_u, fb_uhat, fb_fhat) = ARD.boundary(n,u,uhat,fhat);

You can of course do the same to the input parameters.


问:
condense an if/else if statement using logical operators with javascript
I'm learning AngularJS, trying to make a simple calculator, and I'm trying to condense this if/else if statement to 1-2 lines, using the Javascript logical Operators (&&, ||, !)

Given this example, how could I reduce it?
(if you don't understand $scope, ignore it. Its basically a view. So when someone clicks 9, the calculator will display 9 on the answer screen)

```<code>$scope.setOperand = function (operandEntered) {

    if ($scope.leftOperand === null) {
        $scope.leftOperand = operandEntered;
    }
    else if ($scope.operator === null) {
        $scope.leftOperand = $scope.leftOperand + operandEntered;
    }
    else if ($scope.rightOperand === null) {
        $scope.rightOperand = operandEntered;
    }
    else if ($scope.answer === null) {
        $scope.rightOperand = $scope.rightOperand + operandEntered;
    }
 };
</code>```

答:
TLDR;

Making all the same assumptions as below, this will work and of course is dead simple:

```<code>$scope.setOperand = function (operand) {
    var prop = $scope['leftOperand'] === null ? 'leftOperand' : 'rightOperand';
    $scope[prop] = +$scope[prop] + operand;
};
</code>```

The key is this part: +$scope[prop] That casts null to 0, so you end up adding it to one side or the other, if it's null or has a value (which is what the logic seems to do). Bergi pointed out that null and null for both values isn't handled, but I'd say the calculation should be done elsewhere:

```<code>$scope.calc = function(){
    return eval(
        +$scope.leftOperand         // Cast if null to 0
        + ($scope.operator || '+')  // Default to add if null
        +$scope.rightOperand        // Cast if null to 0
    );
};
</code>```

Assuming you have one left/right operand (and you're not trying to do multiple operations):

```<code>var $scope = {
    operator: '-',
    answer: null,
    leftOperand: null,
    rightOperand: 3,
};
</code>```

We can start with:

```<code>$scope.setOperand = function (operand) {
    var prop = ['leftOperand','rightOperand'].reduce(function(t, k) {
        return $scope[k] === null ? k : t;
    });
    $scope[prop] = +$scope[prop] + operand;
};
</code>```

https://jsfiddle.net/w89dLrqw/

Which is four lines. We can remove one line with a little hijinks:

```<code>$scope.setOperand = function (operand) {
    [['leftOperand','rightOperand'].reduce(function(t, k) {
        return $scope[k] === null ? k : t;
    })].map(function(prop){$scope[prop] = +$scope[prop] + operand});
};
</code>```

https://jsfiddle.net/b63x7aag/

Or, if you will:

```<code>$scope.setOperand = function (operand) {
    [['leftOperand','rightOperand'].reduce(function(t, k) {return $scope[k] === null ? k : t;})]
    .map(function(prop){$scope[prop] = +$scope[prop] + operand});
};
</code>```

And another one (props to @bergi):

```<code>$scope.setOperand = function (operand) {
    (function(prop){$scope[prop] = +$scope[prop] + operand})
    (['leftOperand','rightOperand'].reduce(function(t, k){return !+$scope[k] ? k : t}));
};
</code>```

https://jsfiddle.net/mh1bvhcj/1/

That last two look minified, and that last one runs "upside-down". I can't see how this is useful to write it this way just so it takes up very little horizontal space.

What I don't understand is what the else if ($scope.answer === null) is in there for, since having answer === null doesn't seem like it would affect the operands as far as I can tell. So this may or may not work, depending on what that's about.

Body:
I'm learning AngularJS, trying to make a simple calculator, and I'm trying to condense this if/else if statement to 1-2 lines, using the Javascript logical Operators (&&, ||, !)

Given this example, how could I reduce it?
(if you don't understand $scope, ignore it. Its basically a view. So when someone clicks 9, the calculator will display 9 on the answer screen)

$scope.setOperand = function (operandEntered) {

    if ($scope.leftOperand === null) {
        $scope.leftOperand = operandEntered;
    }
    else if ($scope.operator === null) {
        $scope.leftOperand = $scope.leftOperand + operandEntered;
    }
    else if ($scope.rightOperand === null) {
        $scope.rightOperand = operandEntered;
    }
    else if ($scope.answer === null) {
        $scope.rightOperand = $scope.rightOperand + operandEntered;
    }
 };

Body:
TLDR;

Making all the same assumptions as below, this will work and of course is dead simple:

$scope.setOperand = function (operand) {
    var prop = $scope['leftOperand'] === null ? 'leftOperand' : 'rightOperand';
    $scope[prop] = +$scope[prop] + operand;
};

The key is this part: +$scope[prop] That casts null to 0, so you end up adding it to one side or the other, if it's null or has a value (which is what the logic seems to do). Bergi pointed out that null and null for both values isn't handled, but I'd say the calculation should be done elsewhere:

$scope.calc = function(){
    return eval(
        +$scope.leftOperand         // Cast if null to 0
        + ($scope.operator || '+')  // Default to add if null
        +$scope.rightOperand        // Cast if null to 0
    );
};

Assuming you have one left/right operand (and you're not trying to do multiple operations):

var $scope = {
    operator: '-',
    answer: null,
    leftOperand: null,
    rightOperand: 3,
};

We can start with:

$scope.setOperand = function (operand) {
    var prop = ['leftOperand','rightOperand'].reduce(function(t, k) {
        return $scope[k] === null ? k : t;
    });
    $scope[prop] = +$scope[prop] + operand;
};

https://jsfiddle.net/w89dLrqw/

Which is four lines. We can remove one line with a little hijinks:

$scope.setOperand = function (operand) {
    [['leftOperand','rightOperand'].reduce(function(t, k) {
        return $scope[k] === null ? k : t;
    })].map(function(prop){$scope[prop] = +$scope[prop] + operand});
};

https://jsfiddle.net/b63x7aag/

Or, if you will:

$scope.setOperand = function (operand) {
    [['leftOperand','rightOperand'].reduce(function(t, k) {return $scope[k] === null ? k : t;})]
    .map(function(prop){$scope[prop] = +$scope[prop] + operand});
};

And another one (props to @bergi):

$scope.setOperand = function (operand) {
    (function(prop){$scope[prop] = +$scope[prop] + operand})
    (['leftOperand','rightOperand'].reduce(function(t, k){return !+$scope[k] ? k : t}));
};

https://jsfiddle.net/mh1bvhcj/1/

That last two look minified, and that last one runs "upside-down". I can't see how this is useful to write it this way just so it takes up very little horizontal space.

What I don't understand is what the else if ($scope.answer === null) is in there for, since having answer === null doesn't seem like it would affect the operands as far as I can tell. So this may or may not work, depending on what that's about.


问:
Sharing a struct safely amongst multiple threads
Under Windows/C++, if I have a struct:

```<code>struct ListItem {
    ListItem* next;
    ListItem* prev;
    ...
}
</code>```

together with multiple threads running in both the main process and in several dynamically loaded DLLs, and all of those threads need to share the above struct, how do I stop them stomping on each other? Something like:

```<code>ListItem* list = ...

A

list->next = ...

B
</code>```

What do I put at A and B to prevent no more than one thread at a time running list->next = ...?

答:
You are looking for synchronization. Take a look at mutex.

http://www.relisoft.com/win32/active.html

http://msdn.microsoft.com/en-us/library/ms684266(v=vs.85).aspx

http://www.installsetupconfig.com/win32programming/threadprocesssynchronizationapis11_42.html

Body:
Under Windows/C++, if I have a struct:

struct ListItem {
    ListItem* next;
    ListItem* prev;
    ...
}

together with multiple threads running in both the main process and in several dynamically loaded DLLs, and all of those threads need to share the above struct, how do I stop them stomping on each other? Something like:

ListItem* list = ...

A

list->next = ...

B

What do I put at A and B to prevent no more than one thread at a time running list->next = ...?


问:
Difference between paging and segmentation
I am trying to understand both paradigms of memory management;however, I fail to see the big picture and the difference between both. Paging consists of taking fixed size pages from a secondary to a primary storage in order to do some task requested by a process. Segmentation consists of assigning to each unit in a process an address space, so they are allowed to grow. I don't quiet see how they are related and that's because there are still a lot of holes in my understanding. Can someone fill them up?</p>

答:
I think you have something confused. One problem you have is that the term "segment" had multiple meanings.

Segmentation is a method of memory management. Memory is managed in segments that are of variable or fixed length, depending upon the processor. Segments originated on 16-bit processors as a means to access more than 64K of memory.

On the PDP-11, programmers used segments to map different memory into the 64K address space. At any given time a process could only access 64K of memory but the memory that made up that 64K could change.

The 8086 and it successors used segments with base registers. Each segment could have 64K (that grew with the processors) but a process could have 4 segments (more in later processors).

Paging allows a process to have a larger address space than there is physical memory available.

The 8086's successors used the kludge of paging on top of segments. However, that bit of ugliness has finally gone away in 64-bit mode.


问:
How to splice user correctly from scope in AngularJS?
I am trying to remove user from the list. For some reason, splicing is not removing the user from the list. Can any one help me solve this. I am getting the users from a backend API call, and I am using a PUT method to update it when it removes that particular user.

app.js

```<code>app.controller('MyCtrl', function($scope, $window) {

    $scope.inactive = true;

    $scope.confirmedAction = user => {
        const index = $scope.userInfo.users.indexOf(user);
        $scope.userInfo.users.splice(user, 1);
        $window.location.href = '#/user';
    };

});
</code>```

答:
you should splice based on index

```<code>$scope.userInfo.users.splice(index, 1);
</code>```

as per the docs Array.prototype.splice

index at which to start changing the array (with origin 0). If greater than the length of the array, actual starting index will be set to the length of the array

just to show a POC

```<code>var array = ['val1','val2','val3']
var index = array.indexOf('val2')
array.splice(index,1);

console.log(array);
//['val1','val3']
</code>```

Body:
I am trying to remove user from the list. For some reason, splicing is not removing the user from the list. Can any one help me solve this. I am getting the users from a backend API call, and I am using a PUT method to update it when it removes that particular user.

app.js

app.controller('MyCtrl', function($scope, $window) {

    $scope.inactive = true;

    $scope.confirmedAction = user => {
        const index = $scope.userInfo.users.indexOf(user);
        $scope.userInfo.users.splice(user, 1);
        $window.location.href = '#/user';
    };

});

Body:
you should splice based on index

$scope.userInfo.users.splice(index, 1);

as per the docs Array.prototype.splice

index at which to start changing the array (with origin 0). If greater than the length of the array, actual starting index will be set to the length of the array

just to show a POC

var array = ['val1','val2','val3']
var index = array.indexOf('val2')
array.splice(index,1);

console.log(array);
//['val1','val3']


问:
Text format after an image in a block displayed by QTextEdit
In a QTextEdit object, I want to display a document made of two parts : a title and a text. The text begins with an image (an initial, placed at left), hence my code :

```<code>  QTextCursor cur = this->textCursor();

  // title :
  [... defining the title block format and the title's text char format ...]
  cur.insertBlock( title_blockformat, title_textcharformat );
  cur.insertText("TITLE");

  // initial + text
  // [... defining the text block format and text's text char format ...]
  cur.insertBlock( text_blockformat, text_textcharformat );
  // [...defining the image format...]
  cur.insertImage( imageformat, QTextFrameFormat::FloatLeft);
  cur.insertText("SOME TEXT");
</code>```

I'm stuck with the following problem : the title is correctly displayed, the image too but the text is displayed with a default format, as if the line

```<code>  cur.insertBlock( text_blockformat, text_textcharformat );
</code>```

was somehow forgotten because of the image. When I remove the call to cur.insertImage() my text is correctly displayed.

I checked cur.insertImage didn't add a new block : the image and the text belong to the same block.

Any idea to help me ?

答: Because the default mode is that when you don't reassign your own charformat, the text inserted by the cursor will adopt the charformat used by the current text fragment. In your case, it's the format of the image.</p>

Body:
In a QTextEdit object, I want to display a document made of two parts : a title and a text. The text begins with an image (an initial, placed at left), hence my code :

  QTextCursor cur = this->textCursor();

  // title :
  [... defining the title block format and the title's text char format ...]
  cur.insertBlock( title_blockformat, title_textcharformat );
  cur.insertText("TITLE");

  // initial + text
  // [... defining the text block format and text's text char format ...]
  cur.insertBlock( text_blockformat, text_textcharformat );
  // [...defining the image format...]
  cur.insertImage( imageformat, QTextFrameFormat::FloatLeft);
  cur.insertText("SOME TEXT");

I'm stuck with the following problem : the title is correctly displayed, the image too but the text is displayed with a default format, as if the line

  cur.insertBlock( text_blockformat, text_textcharformat );

was somehow forgotten because of the image. When I remove the call to cur.insertImage() my text is correctly displayed.

I checked cur.insertImage didn't add a new block : the image and the text belong to the same block.

Any idea to help me ?


问:
How to know when a View has scrolled into view
We are currently developing an app that displays large data sets in "registers" and in rows. We are using a TableLayout as the base view and then adding table rows for every item (with a LinearLayout in each row).

I have noticed that once the amount of records get beyond a certain point (1000+ records), the device slows down tremendously. I am sure that this is a simple memory issue(maybe rendering too?) and have devised a plan that could increase the speed.

We have implemented continuous paging on a lot of silverlight projects, and I figure that this is the best approach to take in Android?

The only problem I have now is to recognize when a specific view (say row 100) has been scrolled into view, so that I can start to render the next couple of lines.

Does anyone know how to do this, or of a better way to implement/handle large data sets?

Regards

答:
You just need to add onScrollListener onto your View.
Preferably Use ListView to show data

From the following code your can get the index of the current view.

ListView.OnScrollListener is the interface that you need to implement and give body to

  following two methods.

listView.setOnScrollListener(new ListView.OnScrollListener(){

public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                int totalItemCount) {
        }

```<code>    public void onScrollStateChanged(AbsListView view, int scrollState) {
        switch (scrollState) {
        case OnScrollListener.SCROLL_STATE_IDLE:
            mBusy = false;

            int first = view.getFirstVisiblePosition();
            int count = view.getChildCount();

            break;
        case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:

            break;
        case OnScrollListener.SCROLL_STATE_FLING:

            break;

        }
    }
</code>```

});

Try Printing the value of first and count variable it will solve your problem.Hopefully :)

Body:
You just need to add onScrollListener onto your View.
Preferably Use ListView to show data

From the following code your can get the index of the current view.

ListView.OnScrollListener is the interface that you need to implement and give body to

  following two methods.

listView.setOnScrollListener(new ListView.OnScrollListener(){

public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                int totalItemCount) {
        }

    public void onScrollStateChanged(AbsListView view, int scrollState) {
        switch (scrollState) {
        case OnScrollListener.SCROLL_STATE_IDLE:
            mBusy = false;

            int first = view.getFirstVisiblePosition();
            int count = view.getChildCount();

            break;
        case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:

            break;
        case OnScrollListener.SCROLL_STATE_FLING:

            break;

        }
    }

});

Try Printing the value of first and count variable it will solve your problem.Hopefully :)


问:
How to remove all characters not inside parentheses using regex
I have a string that contains commas both inside and outside of a parentheses block:
    foo(bat,foo),bat

How can I use regex to replace the comma not inside parentheses?
                                                                  foo(bat,foo)bat

答:
Considering that we want to remove all commas outside of all blocks and don't want to modify nested blocks.

Let's add string validation for cases when there are unclosed/unopened blocks found with

```<code>def validate_string(string):
    left_parts_count = len(string.split('('))
    right_parts_count = len(string.split(')'))
    diff = left_parts_count - right_parts_count
    if diff == 0:
        return
    if diff < 0:
        raise ValueError('Invalid string: "{string}". '
                         'Number of closed '
                         'but not opened blocks: {diff}.'
                         .format(string=string,
                                 diff=-diff))
    raise ValueError('Invalid string: "{string}". '
                     'Number of opened '
                     'but not closed blocks: {diff}.'
                     .format(string=string,
                             diff=diff))
</code>```

then we can do our job without regular expressions, just using str methods

```<code>def remove_commas_outside_of_parentheses(string):
    # if you don't need string validation
    # then remove this line and string validator
    validate_string(string)

    left_parts = string.split('(')
    if len(left_parts) == 1:
        # no opened blocks found,
        # remove all commas
        return string.replace(',', '')

    left_outer_part = left_parts[0]

    left_outer_part = left_outer_part.replace(',', '')

    left_unopened_parts = left_parts[-1].split(')')
    right_outer_part = left_unopened_parts[-1]
    right_outer_part = right_outer_part.replace(',', '')
    return '('.join([left_outer_part] +
                    left_parts[1:-1] +
                    [')'.join(left_unopened_parts[:-1]
                              + [right_outer_part])])
</code>```

it can look a bit nasty, i suppose, but it works.

Tests

```<code>>>>remove_commas_outside_of_parentheses('foo,bat')
foobat
>>>remove_commas_outside_of_parentheses('foo,(bat,foo),bat')
foo(bat,foo)bat
>>>remove_commas_outside_of_parentheses('bar,baz(foo,(bat,foo),bat),bar,baz')
barbaz(foo,(bat,foo),bat)barbaz
</code>```

"broken" ones:

```<code>>>>remove_commas_outside_of_parentheses('(')
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<input>", line 4, in remove_commas_outside_of_parentheses
  File "<input>", line 17, in validate_string
ValueError: Invalid string: "(". Number of opened but not closed blocks: 1.
>>>remove_commas_outside_of_parentheses(')')
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<input>", line 4, in remove_commas_outside_of_parentheses
  File "<input>", line 12, in validate_string
ValueError: Invalid string: ")". Number of closed but not opened blocks: 1.
</code>```

Body:
Considering that we want to remove all commas outside of all blocks and don't want to modify nested blocks.

Let's add string validation for cases when there are unclosed/unopened blocks found with

def validate_string(string):
    left_parts_count = len(string.split('('))
    right_parts_count = len(string.split(')'))
    diff = left_parts_count - right_parts_count
    if diff == 0:
        return
    if diff < 0:
        raise ValueError('Invalid string: "{string}". '
                         'Number of closed '
                         'but not opened blocks: {diff}.'
                         .format(string=string,
                                 diff=-diff))
    raise ValueError('Invalid string: "{string}". '
                     'Number of opened '
                     'but not closed blocks: {diff}.'
                     .format(string=string,
                             diff=diff))

then we can do our job without regular expressions, just using str methods

def remove_commas_outside_of_parentheses(string):
    # if you don't need string validation
    # then remove this line and string validator
    validate_string(string)

    left_parts = string.split('(')
    if len(left_parts) == 1:
        # no opened blocks found,
        # remove all commas
        return string.replace(',', '')

    left_outer_part = left_parts[0]

    left_outer_part = left_outer_part.replace(',', '')

    left_unopened_parts = left_parts[-1].split(')')
    right_outer_part = left_unopened_parts[-1]
    right_outer_part = right_outer_part.replace(',', '')
    return '('.join([left_outer_part] +
                    left_parts[1:-1] +
                    [')'.join(left_unopened_parts[:-1]
                              + [right_outer_part])])

it can look a bit nasty, i suppose, but it works.

Tests

>>>remove_commas_outside_of_parentheses('foo,bat')
foobat
>>>remove_commas_outside_of_parentheses('foo,(bat,foo),bat')
foo(bat,foo)bat
>>>remove_commas_outside_of_parentheses('bar,baz(foo,(bat,foo),bat),bar,baz')
barbaz(foo,(bat,foo),bat)barbaz

"broken" ones:

>>>remove_commas_outside_of_parentheses('(')
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<input>", line 4, in remove_commas_outside_of_parentheses
  File "<input>", line 17, in validate_string
ValueError: Invalid string: "(". Number of opened but not closed blocks: 1.
>>>remove_commas_outside_of_parentheses(')')
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<input>", line 4, in remove_commas_outside_of_parentheses
  File "<input>", line 12, in validate_string
ValueError: Invalid string: ")". Number of closed but not opened blocks: 1.


问:
Cassandra 3.0 Kill Rogue queries
Someone in my team just issued a select count(*) query on a very large table. An alert got raised and now I need to fix the issue.

Is there a query which allows me to kill the rogue query?

I googled but I didn't find a clear answer

https://issues.apache.org/jira/browse/CASSANDRA-1740 (no clear answer)
https://groups.google.com/forum/#!topic/astyanax-cassandra-client/F-OyecIaRs0 (no clear answer)

What command I should use to list and kill the running queries? (cassandra 3.0)

答:
Have the default timeouts been adjusted at all?  Those defaults are set to keep something like this from happening.

AFIAK, there isn't a way to kill individual queries.  Your best bet would be to locate that query's coordinator node, and bounce it.

Title: Cassandra 3.0 Kill Rogue queries


问:
Assigning Variable Types to numbers java
I'm trying to figure out how to assign multiple variables to int type but I'm not sure how to assign it to them. Also, I'm having difficulty understanding how you can use a boolean with this restriction. I was thinking about putting them in an array but I'm not sure if there is an easier approach to the problem. Any help is much appreciated!

Instructions for Attraction.java

Write a Java program Attraction.java that has the following characteristics.

extends Place
New attributes: type (int) price (double)
New Methods: public Attraction(String name, String desc, double latitude, double longitude, double price, int type) where for type values:

0 is an amusement park
1 is an aquarium
2 is a zoo
public double getPrice() -- returns current price

public int getType() -- returns type

public boolean hasAnimals() -- returns true if type contains "zoo" or "aquarium"

答:
Your hasAnimals method needs to return a boolean value i.e. true or false based on the value of the type variable.

You're .. kind of on the right track, but you're not honoring the requirements of the method. It shouldn't print anything, and it shouldn't return type because type is an int and not the boolean that is required.

```<code>public boolean hasAnimals() {
    if(type == 1) {
        return true; // aquarium has animals
    } else if (type == 2) {
        return true; // zoo has animals
    } else {
        return false;
    }
}
</code>```

Think carefully about what a method is called, and what it should do. This method is just a way to answer a yes/no question.

Body:
Your hasAnimals method needs to return a boolean value i.e. true or false based on the value of the type variable.

You're .. kind of on the right track, but you're not honoring the requirements of the method. It shouldn't print anything, and it shouldn't return type because type is an int and not the boolean that is required.

public boolean hasAnimals() {
    if(type == 1) {
        return true; // aquarium has animals
    } else if (type == 2) {
        return true; // zoo has animals
    } else {
        return false;
    }
}

Think carefully about what a method is called, and what it should do. This method is just a way to answer a yes/no question.


问:
ListBox.ItemTemplate with a custom control template inside DataTemplate
I'm developing a Windows Phone application. I have defined a ListBox.ItemTemplate's DataTemplate as follows:

```<code><ListBox Margin="10,10,8,8" x:Name="ChoicesList">
  <ListBox.ItemsPanel>
    <ItemsPanelTemplate>
      <StackPanel />
    </ItemsPanelTemplate>
  </ListBox.ItemsPanel>
  <ListBox.ItemTemplate>
    <DataTemplate>
      <Grid x:Name="ListBoxItemLayout" Background="Transparent" Margin="10">
        <Grid.ColumnDefinitions>
          <ColumnDefinition Width="0.281*"/>
          <ColumnDefinition Width="0.719*"/>
        </Grid.ColumnDefinitions>
        <Image Source="{Binding ImagePath}" Height="100"/>
        <StackPanel Margin="5,0,0,0" Grid.Column="1">
          <TextBlock x:Name="Name" TextWrapping="Wrap" Text="{Binding Name}" Style="{StaticResource PhoneTextTitle3Style}"/>
          <TextBlock x:Name="Description" Margin="0,5,0,0" TextWrapping="Wrap" Text="{Binding Description}" d:LayoutOverrides="Width" Style="{StaticResource PhoneTextSmallStyle}"/>
          <TextBlock x:Name="Rating" TextWrapping="Wrap" Text="{Binding Rating}" />
        </StackPanel>
      </Grid>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>
</code>```

I want to convert all the content inside the ListBoxItem as a Control because I want to add a Click event to it.

How can I do this?

Thank you.

答:
In blend you can just use the "Make into Control" option.

You should also consider using the "SelectionChanged" event on the listbox, rather than a click (tap) on the control.

Body:
I'm developing a Windows Phone application. I have defined a ListBox.ItemTemplate's DataTemplate as follows:

<ListBox Margin="10,10,8,8" x:Name="ChoicesList">
  <ListBox.ItemsPanel>
    <ItemsPanelTemplate>
      <StackPanel />
    </ItemsPanelTemplate>
  </ListBox.ItemsPanel>
  <ListBox.ItemTemplate>
    <DataTemplate>
      <Grid x:Name="ListBoxItemLayout" Background="Transparent" Margin="10">
        <Grid.ColumnDefinitions>
          <ColumnDefinition Width="0.281*"/>
          <ColumnDefinition Width="0.719*"/>
        </Grid.ColumnDefinitions>
        <Image Source="{Binding ImagePath}" Height="100"/>
        <StackPanel Margin="5,0,0,0" Grid.Column="1">
          <TextBlock x:Name="Name" TextWrapping="Wrap" Text="{Binding Name}" Style="{StaticResource PhoneTextTitle3Style}"/>
          <TextBlock x:Name="Description" Margin="0,5,0,0" TextWrapping="Wrap" Text="{Binding Description}" d:LayoutOverrides="Width" Style="{StaticResource PhoneTextSmallStyle}"/>
          <TextBlock x:Name="Rating" TextWrapping="Wrap" Text="{Binding Rating}" />
        </StackPanel>
      </Grid>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

I want to convert all the content inside the ListBoxItem as a Control because I want to add a Click event to it.

How can I do this?

Thank you.


问:
Is the Roslyn model so C#/VB.NET centric that it precludes XAML analysis now and in the future?
I have just read the blog entry by JetBrains (Resharper) that suggests that Roslyn could never do XAML analysis:

Another core difference is that Roslyn covers exactly two languages, C# and VB.NET, whereas ReSharper architecture is multilingual

(quote from resharper blog)

For the uninitiated Resharper can do very good static analysis on XAML code allowing code completion and refactoring together with C#.

I am curious. Is the Roslyn architecture general enough to be extended to other languages than C# and VB.Net such as XAML or is it very specific.

To avoid suggesting this is opinion based I am looking for evidence in the source. Obviously any code can be refactored /re-engineered over time to fit some other purpose but I'm only interested in current evidence in the source or references to quotes from Roslyn develepors indicating that there is intent to extend Roslyn as an analysis engine to other languages such as XAML.

答:
Hard to teach "languages" in a paragraph or two. People tend top call many things "language" and in some very general sense they might be but in real-world of programming "language" means programming language. In that world, XAML is not language at all :-) because you can't write code in it.

XAML is a data description format and yes in a very general sense it can be called a language (has some basic constructs, their combination rules, and the result denotes something meaningful). But it doesn't have even its own syntax - it's XML. So it belongs to a group with say MSBuild and HTML. The kind of analysis you could, in theory, do with that is entirely different and very much related to the actual domain that the format describes.

For MSBuild files, you could write some code to analyze dependencies it denotes and says try to find and point out holes in that but all you need for that are a few standard .NET classes. You don't need a parser, don't have any code generation, etc. You just load XML like any other and you already have everything and cam cruise around and dig out relations. Same for XAML. For everything XML-based "Roslyn" is XmlDocument, or XPathDocument.

Roslyn breaks it basks to produce a tree structure that allows you the same kind of cruising freedom that you get just by loading the XAML document into XmlDocument.


问:
Including template PHP file at the end of functions file
I'm learning basic PHP with a book. Inside the book I have done this example:

```<code><?php
session_start()

if(array_key_exists("taskName", $_GET)) {
    $_SESSION["taskList"][] = $_GET["taskName"];
}

$taskList= [];

if(array_key_exists("taskList", $_SESSION)) {
    $taskList = $_SESSION["taskList"];
}

include "template.php";
</code>```

The "include template.php" at the end of "functions.php" file is used in the book and it seems to work. But, when using in my example, the template.php which is used to be displayed the results, didn't work, here are the template.php part which uses PHP code:

```<code><table>
            <tr>
                <th>Tasks</th>
            </tr>
            <?php foreach($taskList as $task) : ?>
            <tr>
                <td><?=$task?></td>
            </tr>
            <?php endforeach; ?>
        </table>
</code>```

Here are displayed errors:

```<code>Notice: Undefined variable: taskList in C:\xampp\htdocs\to-do-list\template.php on line 27

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\to-do-list\template.php on line 27
</code>```

In my understanding, the template.php isn't getting info from functions.php as the book it gets.

PHP Documentation

In this documentation above have the following example:

```<code><?php
$a = 1;
include 'b.inc';
?>
</code>```

So, b.inc will have the $a var. It's the same what happens in the book.

答:
Your example works just fine, however since I can't think to start where is the problem exactly, I'd suggest to

Edit session_start() line to add semicolon at the end of the line.

Make sure to open the url of functions.php file not the template.php file.

If this error applies when you request the file functions.php without GET arguments then try to provide an argument. like http://localhost/test/functions.php?taskName=anyName.

Here is the exact code I tried and called the functions.php with and without arguments and works fine

functions.php

```<code><?php

session_start();

if(array_key_exists("taskName", $_GET)) {
    $_SESSION["taskList"][] = $_GET["taskName"];
}

$taskList= [];

if(array_key_exists("taskList", $_SESSION)) {
    $taskList = $_SESSION["taskList"];
}

include "template.php";
</code>```

template.php

```<code><table>
    <tr>
        <th>Tasks</th>
    </tr>
        <?php foreach($taskList as $task) : ?>
            <tr>
                <td><?=$task?></td>
            </tr>
        <?php endforeach; ?>
</table>
</code>```

Body:
I'm learning basic PHP with a book. Inside the book I have done this example:

<?php
session_start()

if(array_key_exists("taskName", $_GET)) {
    $_SESSION["taskList"][] = $_GET["taskName"];
}

$taskList= [];

if(array_key_exists("taskList", $_SESSION)) {
    $taskList = $_SESSION["taskList"];
}

include "template.php";

The "include template.php" at the end of "functions.php" file is used in the book and it seems to work. But, when using in my example, the template.php which is used to be displayed the results, didn't work, here are the template.php part which uses PHP code:

                Tasks

            <?php foreach($taskList as $task) : ?>

                <?=$task?>

            <?php endforeach; ?>

Here are displayed errors:

Notice: Undefined variable: taskList in C:\xampp\htdocs\to-do-list\template.php on line 27

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\to-do-list\template.php on line 27

In my understanding, the template.php isn't getting info from functions.php as the book it gets.

PHP Documentation

In this documentation above have the following example:

<?php
$a = 1;
include 'b.inc';
?>

So, b.inc will have the $a var. It's the same what happens in the book.

Body:
Your example works just fine, however since I can't think to start where is the problem exactly, I'd suggest to

Edit session_start() line to add semicolon at the end of the line.

Make sure to open the url of functions.php file not the template.php file.

If this error applies when you request the file functions.php without GET arguments then try to provide an argument. like http://localhost/test/functions.php?taskName=anyName.

Here is the exact code I tried and called the functions.php with and without arguments and works fine

functions.php

<?php

session_start();

if(array_key_exists("taskName", $_GET)) {
    $_SESSION["taskList"][] = $_GET["taskName"];
}

$taskList= [];

if(array_key_exists("taskList", $_SESSION)) {
    $taskList = $_SESSION["taskList"];
}

include "template.php";

template.php

<table>
    <tr>
        <th>Tasks</th>
    </tr>
        <?php foreach($taskList as $task) : ?>
            <tr>
                <td><?=$task?></td>
            </tr>
        <?php endforeach; ?>
</table>


问:
Move Post Title above Post Date Wordpress Visual Composer
Is there any way to move the title above the date and change the date settings to "Date" instead of "Posted 4 days ago"?

I'm using Albertino theme with visual Composer

答:
Solved

by using the excerpt template and changing Show post date after to '1' on date settings on Visual Composer Global Options


问:
Error: Could not find an installed version of Gradle either in Android Studio, or on your system to install the gradle wrapper
I develop a hybrid app usin cordova. While I was trying to build the android verion of my App, i got this error:

Error: Could not find an installed version of Gradle either in Android Studio,
or on your system to install the gradle wrapper. Please include gradle
in your path, or install Android Studio.

..although Android Studio is already installed and everything worked so far.

Does anybody know the reason for this issue?

答:
The problem is in the file: \cordova\lib\check_reqs.js
When cordova checks the location of graddle is doing this: var androidPath = path.join(process.env['ProgramFiles'], 'Android') + '/';

If you don't have installed in certain location, cordova can't find the file.
So... edit tcheck_reqs.js and do this (i'm using Windows 10 and cordova 7.0.1):

```<code>return 'C:\\Android\\sdk\\gradle\\gradle-3.2\\bin\\gradle';

if (androidStudioPath !== null && fs.existsSync(androidStudioPath)) {
    var dirs = fs.readdirSync(androidStudioPath);
    if(dirs[0].split('-')[0] == 'gradle') {
        return path.join(androidStudioPath, dirs[0], 'bin', 'gradle');
    }

} else {
    //OK, let's try to check for Gradle!
    return forgivingWhichSync('gradle');
}
</code>```

It's not a real fix, but if you are sure of your gradle location it will be fine, hope cordova fix this.

Body:
The problem is in the file: \cordova\lib\check_reqs.js
When cordova checks the location of graddle is doing this: var androidPath = path.join(process.env['ProgramFiles'], 'Android') + '/';

If you don't have installed in certain location, cordova can't find the file.
So... edit tcheck_reqs.js and do this (i'm using Windows 10 and cordova 7.0.1):

return 'C:\\Android\\sdk\\gradle\\gradle-3.2\\bin\\gradle';

if (androidStudioPath !== null && fs.existsSync(androidStudioPath)) {
    var dirs = fs.readdirSync(androidStudioPath);
    if(dirs[0].split('-')[0] == 'gradle') {
        return path.join(androidStudioPath, dirs[0], 'bin', 'gradle');
    }

} else {
    //OK, let's try to check for Gradle!
    return forgivingWhichSync('gradle');
}

It's not a real fix, but if you are sure of your gradle location it will be fine, hope cordova fix this.


问:
Android: Gallery interfering with scale setting of ImageView
I have some images that are 48 pixels (or greater) in height, and 48 pixels (or greater) in width. So basically I have images that are either 48 X greater than 48, or greater than 48 x 48. I want to make some thumbnails from these images that are center cropped and NOT scaled so that they maintain image quality. I can't use:

```<code>setScaleType(ScaleType.CENTER_CROP)
</code>```

because although it achieves the cropping I am looking for, it unfortunately scales the image. What I am trying to achieve with the crop is that it either cuts off the left & right of an image that is greater than 48 pixels in width, or the top & bottom of an image that is greater than 48 pixels in height.

I tried ScaleType.CENTER in an XML layout, and it seems to be exactly what I want. I'm using these images in a Gallery, so in my gallery Adapter I do:

```<code>    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ImageView thumb = new ImageView(mContext);
        thumb.setScaleType(ScaleType.CENTER);
        thumb.setLayoutParams(new LayoutParams(THUMB_SIZE, THUMB_SIZE));

        if (mPhotos != null) {
            String imageUrl = mPhotos.get(position).getPhotoHref();
            imageUrl = imageUrl.replaceAll(mPattern, mFormat);
            ImageManager.instance().displayImage(imageUrl, mContext, thumb, DefaultThumbId);
        } else {
            thumb.setImageResource(DefaultThumbId);
        }

        return thumb;
    }
</code>```

but for some reason, the entire image is shown, but scaled way down. It works perfect in an XML layout, but not when I do this in code and feed it to a Gallery. What gives?

答: This was actually not a Gallery problem, the images I was downloading weren't being scaled properly, so they were coming in with a max width/height that was the same size as the view, instead of a min width/height to achieve what I wanted here. I download at the proper size now and setScaleType(ScaleType.CENTER_CROP) works properly.</p>

Body:
I have some images that are 48 pixels (or greater) in height, and 48 pixels (or greater) in width. So basically I have images that are either 48 X greater than 48, or greater than 48 x 48. I want to make some thumbnails from these images that are center cropped and NOT scaled so that they maintain image quality. I can't use:

setScaleType(ScaleType.CENTER_CROP)

because although it achieves the cropping I am looking for, it unfortunately scales the image. What I am trying to achieve with the crop is that it either cuts off the left & right of an image that is greater than 48 pixels in width, or the top & bottom of an image that is greater than 48 pixels in height.

I tried ScaleType.CENTER in an XML layout, and it seems to be exactly what I want. I'm using these images in a Gallery, so in my gallery Adapter I do:

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ImageView thumb = new ImageView(mContext);
        thumb.setScaleType(ScaleType.CENTER);
        thumb.setLayoutParams(new LayoutParams(THUMB_SIZE, THUMB_SIZE));

        if (mPhotos != null) {
            String imageUrl = mPhotos.get(position).getPhotoHref();
            imageUrl = imageUrl.replaceAll(mPattern, mFormat);
            ImageManager.instance().displayImage(imageUrl, mContext, thumb, DefaultThumbId);
        } else {
            thumb.setImageResource(DefaultThumbId);
        }

        return thumb;
    }

but for some reason, the entire image is shown, but scaled way down. It works perfect in an XML layout, but not when I do this in code and feed it to a Gallery. What gives?