text:
Q: Understanding importing in Python I have checked for similar questions but no one answered my question, which I know that it's quite dumb, but anyway.
Let's say that I have the following:
my_app
    input_module
        data_input.py
        data_processing.py
        __init__.py
    output_module
        output_generation.py
        output_display.py
        __init__.py
    __init__.py
main.py

The __init__.py files are correctly done.
output_generation.py needs to import a class from data_input.py and I do it by writing from input_module import DataInputClass since in the __init__.py I import that class. The thing is that if I do from my_app.input_module import DataInputClass, then the error is that my_app module hasn't been found, which I understand.
But, if then in main.py I do: from my_app.output_module import DataOutputClass, then it will trigger an error in the line from input_module import DataInputClass of output_generation.py saying that input is not found, which I also understand.
My question is how can I fix this The easiest solution is putting main.py inside of my_app but, is there any other way to solve this without doing it? Is there any way to make the imports relative with respect to the file in which the import is done, and not the working directory of the main file?
Sorry if the question is confusing.
Thanks!


text:
Q: SKSprite following CGMutablePath alignment I'm confused on what is going on here.  I know its supposed to be some coordinate shift, but when I use a circle for the path it traces it exactly.  If I use a curve as below this is the result I get.  I just want to draw the curve then have a sprite be able to trace the curve.  Any ideas what is wrong?
//  CGPathRef circle = CGPathCreateWithEllipseInRect(CGRectMake(0,0,400,400), NULL);

CGMutablePathRef circle = CGPathCreateMutable();
CGPathMoveToPoint(circle, NULL, 0, 0);
CGPathAddQuadCurveToPoint(circle, NULL, 200, 200, 265, 20);

SKAction *followTrack = [SKAction followPath:circle asOffset:NO orientToPath:YES duration:1.0];
 SKAction *forever = [SKAction repeatActionForever:followTrack];
[MySprite runAction:forever];

A: Without using Maths to confuse you, the reason for the path as you see it is because the third and fourth parameters as defined by the CGPathAddQuadCurveToPoint:
CGPathAddQuadCurveToPoint(path, m, cpx, cpy, x, y)

are control points for the curve that arises as a result of the Math calculation done to obtain the curve defined given the parameters. So for example, given a curve that starts at (0,0) and ends at (0, 200) with a control point sitting at (100, 100), the highest point on that curve will actually sit around (100, 50). In other words, the top most part of the curve will go about half-way up on the y-axis to where the control point's y-coordinate is. So if you want the highest point of the curve to sit at (100, 100), then your control point's y-coordinate would sit around 200.
Of course this gets a bit more complex when the control points sits offset to the center of the curve, or when you have multiple control points making up the curve. Refer to this wikipedia page for a detailed working on curves/paths:
http://en.wikipedia.org/wiki/Bezier_curve

redpajama_set_name: RedPajamaStackExchange


text:
Q: Calling activity if the app is closed I need to create a fullscreen notification for alarm clock. I suppose it should be a simple activity, but I have troubles with calling it. If app is running, everything is ok, but if I manually ruine process of this app, the activity is not shown. It also is not shown if the screen is off.
So, two questions. 1) How to call AlarmActivity if the app is closed? 2) How to call it if the screen is off?
It's AlarmReceiver class:
public class AlarmReceiver extends WakefulBroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Intent alarmIntent = new Intent();
            alarmIntent.setComponent(new ComponentName("com.enjoyalarm.enjoyalarm", "com.enjoyalarm.enjoyalarm.AlarmActivity"));
            alarmIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(alarmIntent);
   }

}
AlarmActivity:
public class AlarmActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alarm);
        Intent intent = getIntent();
    }
}

If it's impossible, how to deal with my problem: fullscreen notification (with buttons, etc)?

A: change your intent from
 Intent alarmIntent = new Intent();

to
 Intent alarmIntent = new Intent(context, AlarmActivity.class);

and remove
alarmIntent.setComponent(new ComponentName("com.enjoyalarm.enjoyalarm", "com.enjoyalarm.enjoyalarm.AlarmActivity"));


text:
Q: Using boost::thread to start/stop logging data (2nd update) I'm currently trying to log real-time data by using boost::thread and a check box. When I check the box, the logging thread starts. When I uncheck, the logging thread stops. The problem arises when I check/uncheck repeatedly and very fast (program crashes, some files aren't logged, etc.). How can I write a reliable thread-safe program where these problems don't occur when repeatedly and quickly checking/unchecking? I also don't want to use join() since this temporarily stops the data input coming from the main thread. In the secondary thread, I'm opening a log file, reading from a socket into a buffer, copying this into another buffer, and then writing this buffer to a log file. I'm thinking that maybe I should use mutex locks for reading/writing. If so, what specific locks should I use? Below is a code snippet:
//Main thread
 if(m_loggingCheckBox->isChecked()) {

...

if(m_ThreadLogData.InitializeReadThread(socketInfo))//opens the socket.
//If socket is opened and can be read, start thread.
 m_ThreadLogData.StartReadThread();
 else
 std::cout << "Did not initialize thread\n";
 }
 else if(!m_loggingCheckBox->isChecked())
 {

m_ThreadLogData.StopReadThread();

}

void ThreadLogData::StartReadThread()
 {
 //std::cout << "Thread started." << std::endl;
 m_stopLogThread = false;
 m_threadSendData = boost::thread(&ThreadLogData::LogData,this);
 }

void ThreadLogData::StopReadThread()
 {
 m_stopLogThread = true;
 m_ReadDataSocket.close_socket(); // close the socket

if(ofstreamLogFile.is_open())
 {
 ofstreamLogFile.flush(); //flush the log file before closing it.
 ofstreamLogFile.close(); // close the log file
 }
 m_threadSendData.interrupt(); // interrupt the thread
 //m_threadSendData.join(); // join the thread. Commented out since this
 temporarily stops data input.

}

//secondary thread
 bool ThreadLogData::LogData()
 {

unsigned short int buffer[1024];
 bool bufferflag;
 unsigned int iSizeOfBuffer = 1024;
 int iSizeOfBufferRead = 0;
 int lTimeout = 5;

if(!ofstreamLogFile.is_open())
 {
 ofstreamLogFile.open(directory_string().c_str(), ios::out);

if(!ofstreamLogFile.is_open())
 {
 return 0;
 }
 }

while(!m_stopLogThread)
 {
 try {
 int ret = m_ReadDataSocket.read_sock(&m_msgBuffer.m_buffer
 [0],iSizeOfBuffer,lTimeout,&iSizeOfBufferRead);

memcpy(&buffer[0],m_msgBuffer.m_buffer,iSizeOfBufferRead);
 bufferflag = m_Buffer.setBuffer(buffer);
 if(!bufferflag) return false;
 object = &m_Buffer;

unsigned int data = object->getData();

ofstreamLogFile << data << std::endl;

boost::this_thread::interruption_point();

} catch (boost::thread_interrupted& interruption) {
 std::cout << "ThreadLogData::LogData(): Caught Interruption thread." << std::endl;
 StopReadThread();
 } catch (...) {
 std::cout << "ThreadLogData::LogData(): Caught Something." << std::endl;
 StopReadThread();
 }

} // end while()

}

A: I like to use Boost Asio for async stuff
#include <iostream>
#include <fstream>

#include <boost/asio.hpp>
#include <boost/asio/signal_set.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/bind.hpp>
#include <boost/optional.hpp>

#include <thread>

using boost::asio::ip::tcp;
namespace asio = boost::asio;

struct program
{
    asio::io_service       _ioservice;
    asio::deadline_timer   _timer;
    asio::signal_set       _signals;
    std::array<char, 1024> _buffer;
    tcp::socket            _client;
    tcp::resolver          _resolver;
    std::ofstream          _logfile;
    std::thread            _thread;

    program()
        : _timer(_ioservice),
        _signals(_ioservice),
        _client(_ioservice),
        _resolver(_ioservice)
    {
        do_connect(_resolver.resolve({ "localhost", "6767" }));
        do_toggle_logging_cycle();

        _signals.add(SIGINT);
        _signals.async_wait([this](boost::system::error_code ec, int) { if (!ec) close(); });

        _thread = std::thread(boost::bind(&asio::io_service::run, boost::ref(_ioservice)));
    }

    ~program()
    {
        if (_thread.joinable())
            _thread.join();
    }

    void close() {
        _ioservice.post([this]() {
            _signals.cancel();
            _timer.cancel();
            _client.close();
        });
    }

private:

  void do_toggle_logging_cycle(boost::system::error_code ec = {})
  {
      if (ec != boost::asio::error::operation_aborted)
      {
          if (_logfile.is_open())
          {
              _logfile.close();
              _logfile.clear();
          } else
          {
              _logfile.open("/tmp/output.log");
          }

          _timer.expires_from_now(boost::posix_time::seconds(2));
          _timer.async_wait(boost::bind(&program::do_toggle_logging_cycle, this, boost::asio::placeholders::error()));
      } else
      {
          std::cerr << "\nDone, goobye\n";
      }
  }

  void do_connect(tcp::resolver::iterator endpoint_iterator) {

      boost::asio::async_connect(
          _client, endpoint_iterator,
          [this](boost::system::error_code ec, tcp::resolver::iterator) {
                if (!ec) do_read();
                else     close();
          });
  }

  void do_read() {
    boost::asio::async_read(
        _client, asio::buffer(_buffer.data(), _buffer.size()),
        [this](boost::system::error_code ec, std::size_t length) {
            if (!ec) {
              if (_logfile.is_open())
              {
                    _logfile.write(_buffer.data(), length);
              }
              do_read();
            } else {
                close();
            }
    });
  }

};

int main()
{
    {
        program p; // does socket reading and (optional) logging on a separate thread

        std::cout << "\nMain thread going to sleep for 15 seconds...\n";
        std::this_thread::sleep_for(std::chrono::seconds(15));

        p.close(); // if the user doesn't press ^C, let's take the initiative
        std::cout << "\nDestruction of program...\n";
    }
    std::cout << "\nMain thread ends\n";
};

The program connects to port 6767 of localhost and asynchronously reads data from it.
If logging is active (_logfile.is_open()), all received data is written to /tmp/output.log.
Now

*

*the reading/writing is on a separate thread, but all operations are serialized using _ioservice (see e.g. the post in close())

*the user can abort the the socket reading loop with Ctrl+C

*every 2 seconds, the logging will be (de)activated (see do_toggle_logging_cycle)

The main thread just sleeps for 15 seconds before canceling the program (similar to the user pressing Ctrl-C).


text:
Q: Botium-core unable to load custom asserter I recently updated the dependencies in my test project. After updating, botium-core is unable to load the custom asserters I had defined.
Here is a snippet of package.json that shows my dependencies.
"dependencies": {
"botium-connector-dialogflow": "^0.0.25",
"botium-core": "^1.11.0",
"jsonpath": "^1.1.0",
"lodash": "^4.17.20",
"minimist": "^1.2.5",
"mocha": "^8.2.1"}

Here is a snippet of botium.json
{
"botium": {
    "Capabilities": {
        "PROJECTNAME": "my-project",
        "CONTAINERMODE": "dialogflow",
        "DIALOGFLOW_PROJECT_ID": "<google project id>",
        "DIALOGFLOW_CLIENT_EMAIL": "<service credentials email>",
        "DIALOGFLOW_PRIVATE_KEY": "<service credentials private key>",
        "ASSERTERS": [
            {
                "ref": "ASSERTER1",
                "src": "./src/asserter1.js"
            }
        ]
    },
    "Sources": {},
    "Envs": {}
}

I also switched the path to .\src\asserter1.js, and it works on my windows machine, but fails in a linux build env.

A: Please see the Github issue tracker for the resolution. Bug has been fixed now.


text:
Q: Notes should be showed only for the author In my note taking project, I want to do so, that notes should be showed only for the author of the object. I am trying to solve this problem for 3 days. But, I could not solve this. Please Help! Thanks in an advance
view.py
 @login_required(login_url='login')
def index(request):
    tasks = Task.objects.all()
    if request.method=='POST':
        form = TaskForm(request.POST)
        if form.is_valid():
            obj = form.save()
            obj.owner = request.user
            obj.save()
            return redirect('/')

    form =  TaskForm()
    user = request
    context = {
    'tasks' : tasks,
    'form':form,
    'obj':obj

    }
    return render(request, 'list.html',context)

models.py
class Task(models.Model):
    title = models.CharField(max_length=200)
    completed = models.BooleanField(default=False)
    created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

A: Your Task will need a ForeignKey to the user model, to keep track who created the task, so:
from django.conf import settings

class Task(models.Model):
    title = models.CharField(max_length=200)
    completed = models.BooleanField(default=False)
    created = models.DateTimeField(auto_now_add=True)
    owner = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE
    )
I think in that case it is better to recreate the migration file that creates the table for the Task model.
Now that we have an owner of the Tasks, we can filter with:
@login_required(login_url='login')
def index(request):
    tasks = Task.objects.filter(owner=request.user)
    if request.method=='POST':
        form = TaskForm(request.POST, request.FILES)
        if form.is_valid():
            form.instance.owner = request.user
            obj = form.save()
            return redirect('/')
    else:
        form =  TaskForm()
    context = {
        'tasks' : tasks,
        'form': form
    }
    return render(request, 'list.html', context)


text:
Q: Шифрование данных для доступа к БД Возник вопрос касающийся шифрования:есть строка, содержащая в себе данные подключения к бд (логин, пароль пользователя, порт и тд). Стоит ли их как-то зашифровывать в коде и расшифровывать во время запросов к базе или как-то по-другому защищать? Пишу код на c#.
Читал на форумах, что стоит пользоваться симметричным и ассиметричным типами шифрования. Например,у пользователя есть публичный ключ, а затем с его помощью расшифровывается симметрично зашифрованная строка (или как-то так этот принцип объясняют...)

A: *

*В случае десктопного приложения - шифрование не поможет. Ну или поможет от уровня "посмотрел в конфиг, а там пароль". Пользователь с правами администратора в любом случае сможет достать пароль пользуясь отладчиком. Возможное решение - использовать Windows auth в случае доменной сети и SQL Server. Тогда воровать будет нечего.

*В случае web - шифрование почти не имеет смысла, т.к. защищает от случая "кто-то залез на сервер и утащил оттуда конфиг". Может быть при совместном доступе к серверу, когда другой пользователь может зайти на сервер, почему-то может посмотреть конфиг, это имеет какой-то смысл, но сценарий imho нереальный.
Так что в общем случае - не стоит. Просто не храните пароль в исходниках, подкидывайте его в момент деплоймента, и все будет хорошо.


text:
Q: Html C:Foreach trying to create table with number of ages I am trying to create a table of users ages if they have a positive test result. Currently I have it working but for every loop it creates another row with the result on. I am trying to have 1 row with the numbers added up. I'm not quite sure how to do this. Below is a picture of the table.

Below is the code that I have created to get the age and ensure it's between the age brackets.

 <c:set var="count2" value="0"/>

Under 20
20-29
30-39
40-49
50-59
60-69
Over 70

 <c:forEach items="${results}" var="result">
<c:set var="neg" value="Positive"/>

<c:set var="u20" value="0"/>
<c:set var="b2029" value="0"/>
<c:set var="b3039" value="0"/>
<c:set var="b4049" value="0"/>
<c:set var="b5059" value="0"/>
<c:set var="b6069" value="0"/>
<c:set var="o70" value="0"/>
<c:set var="age" value="${result.age}"/>
<c:set var="pos" value="${result.testResult}"/>

 <c:if test="${neg eq pos}">

<c:if test="${age<20}">
<c:set var="u20" value="${u20 + 1 }"/>
</c:if>

<c:if test="${age >=20}">
    <c:if test="${age <=29 }">
<c:set var="b2029" value="${b2029 + 1 }"/>
</c:if>
 </c:if>
 <c:if test="${age >=30}">
    <c:if test="${age <=39 }">
 <c:set var="b3039" value="${b3039 + 1 }"/>
 </c:if>
</c:if>

<c:if test="${age >=40}">
    <c:if test="${age <49}">
<c:set var="b4049" value="${b4049 + 1 }"/>
</c:if>
</c:if>

 <c:if test="${age >=50}">
    <c:if test="${age <=59 }">
    <c:set var="b5059" value="${b5059 + 1 }"/>
  </c:if>
</c:if>

  <c:if test="${age >=60}">
    <c:if test="${age <69 }">
<c:set var="b6069" value="${b6069 + 1 }"/>
</c:if>
</c:if>
<c:if test="${age >70}">
<c:set var="o70" value="${o70 + 1 }"/>
</c:if>

</c:if>

${u20}
${b2029}
${b3039}
${b4049}
${b5059}
${b6069}
${o70}

</c:forEach>

So instead of having a row per user (which it is like now) I would just like 1 single row with all ages added up - e.g. the 30-39 category there is 2 positives so this should be 2 rather than 1 and 1. Thank you for your help

A: In your current code you are setting value of <c:set.. variable on each iteration i.e : 0 so it will always have value 0 and also your
 tag is under c:forEach so on each iteration new row(tr) is created .Instead you can change you code like below :

Under 20

<c:set var="neg" value="Positive"/>
<c:set var="u20" value="0"/>
<c:set var="b2029" value="0"/>
<c:set var="b3039" value="0"/>
<c:set var="b4049" value="0"/>
<c:set var="b5059" value="0"/>
<c:set var="b6069" value="0"/>
<c:set var="o70" value="0"/>
 <c:forEach items="${results}" var="result">
<c:set var="age" value="${result.age}"/>
<c:set var="pos" value="${result.testResult}"/>

 <c:if test="${neg eq pos}">

<c:if test="${age<20}">
<c:set var="u20" value="${u20 + 1 }"/>
</c:if>

<c:if test="${age >=20}">
    <c:if test="${age <=29 }">
<c:set var="b2029" value="${b2029 + 1 }"/>
</c:if>
 </c:if>

</c:forEach>

${u20}
${b2029}
${b3039}
${b4049}
${b5059}
${b6069}
${o70}


text:
Q: VerifyError: Error #1014: Class mx.controls.advancedDataGridClasses::AdvancedDataGridRendererProvider could not be found I am porting over a Flex application from 4.1 to 4.5 and have run into some issues with the AdvancedDataGrid classes being found.  The application compiles ok under 4.5.1 but at runtime I get the following error:
VerifyError: Error #1014: Class mx.controls.advancedDataGridClasses::AdvancedDataGridRendererProvider could not be found.
It appears that what was the old datavisualization.swc was divided into to libraries (advancedgrids_4.5.21328.swf and charts_4.5.21328.swf) both of which are present in my project. is there anything in the configuration that I need to update?
I am currently using Eclipse Java EE IDE for Web Developers (Helios Service Release 1)
Many thanks,
Ian

A: Verify error really means that there's something wrong with versions of classes you are trying to access at runtime.
First of all, you can try plaing with 'merged/rsl' settings. Second, you can double-check your includes or try to build your app outside ide, with ant task, for example.

A: You will have to merge your libraries into code. This might be helpful -
VerifyError: Error #1014: class could not be found


text:
Q: How to switch between streams of data in Python Pandas I have two streams of data, both a series of (timestamp, value) tuples.
ie:
[(2013-04-03T22:16:36+0000, 2334.5), (2013-04-03T22:46:36+0000, 43543.23), ...]

The idea is one of these will be 'preferred' and one not, and I want to create a single time series that is a result of the higher preference stream when available, and falls back to a least preferable stream when not.
My idea was to put the timestamps of values from both streams into buckets, and use the buckets as an index for a DataFrame, with a column for each stream, and a list of (timestamp, value) tuples in each bucket. Then I can just go through per bucket, and choose the one with the highest number of points for example.
The data frame would look something like this:
timestamp            stream1                                  stream2
2013-04-03 00:00:00  [(2013-04-03T00:16:36+0000, 2334.5),     [(2013-04-03T00:17:36+0000, 2314.5)]
                      (2013-04-03T00:17:36+0000, 2314.5)]
2013-04-03 00:30:00  [(2013-04-03T00:43:44+0000, 43543.23),   [(2013-04-03T00:47:36+0000, 2364.5)]
                      (2013-04-03T00:54:24+0000, 4443.23)]
2013-04-03 01:00:00  []                                       [(2013-04-03T01:01:30+0000, 34.34)]
2013-04-03 01:30:00  [(2013-04-03T01:35:32+0000, 238734.3)]   [(2013-04-03T01:45:32+0000, 238734.3)]

In this situation, the timestamps have been put into half-hourly buckets, and stream1 is the preferred stream. For the bucket at 00:00, the two points in stream1 would be chosen, for the bucket at 00:30 the two points in stream 1 would be chosen, for the bucket at 01:00 the single point in stream2 would be chosen as stream1 has no data, for the bucket at 01:30 the single data point in stream1 would be chosen as it is the preferred stream.
How would I go about doing this? I have attempted creating the data frame and using resample('h', how='count') to split into hourly counts, and using groupby, but can't quite put the timestamps into buckets and create the lists of values for each stream per bucket.

A: I have a solution but I'm not sure how efficient it is (being a Pandas noob myself), or if there is a way that is more 'panda-style':
hh = date_range('2013-01-01T00:30:00', periods=48, freq='1800S')
s5 = date_range('2013-01-01', freq='5S', end='2013-01-02')
s5 = s5[:720] + s5[1440:]  # introduce a gap in the 5 second data
hh_d = Series(hh.astype('int') / 10 ** 9, index=hh)
s5_d = Series(s5.astype('int') / 10 ** 9, index=s5)
df = DataFrame({
    'hh': hh_d,
    '5s': s5_d,
})
# Make a grouping, for simplicity by day, hour
grp = df.groupby(lambda x: (x.day, x.hour))

result = TimeSeries()
for name, group in grp:
    winner = None
    for column in group.keys():  # iterate over the columns (streams)
        data = group[column].dropna()  # ditch any NaNs that will be present
        # next, perform the test (in this case, just the length)
        if not winner or len(data) > len(group[winner].dropna()):
            winner = column
    # finally, add the data to the result set.
    result = result.append(group[winner].dropna())

Checking the result at the time of the 5 second gap gives:
ipdb> result[719:725]
2013-01-01 00:59:55    1357001995
2013-01-01 01:00:00    1357002000
2013-01-01 01:30:00    1357003800
2013-01-01 02:00:00    1357005600
2013-01-01 02:00:05    1357005605
2013-01-01 02:00:10    1357005610
dtype: float64

Which shows that the half-hour stream was selected during the gap.
The example above is based on length of each column in the group, but I guess any test could be applied.
Hopefully someone with more pandas experience can elaborate on my strawman answer!


text:
Q: Ember-data Serialize/Deserialize embedded records on 3rd level Pardon me for coming up with this title but I really don't know how to ask this so I'll just explain.
Model: Group (has) User (has) Post
Defined as:
// models/group.js
name: DS.attr('string'),

// models/user.js
name: DS.attr('string'),
group: DS.belongsTo('group')

// models/post.js
name: DS.attr('string'),
user: DS.belongsTo('user'),

When I request /posts, my server returns this embedded record:
{
  "posts": [
    {
      "id": 1,
      "name": "Whitey",
      "user": {
        "id": 1,
        "name": "User 1",
        "group": 2
      }
    }
  ]
}

Notice that the group didn't have the group record but an id instead.
With my serializers:
// serializers/user.js
export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
    attrs: {
        group: {embedded: 'always'}
    }
});

// serializers/post.js
export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
    attrs: {
        user: {embedded: 'always'}
    }
});

This expects that the User and Post model have embedded records in them. However, it entails a problem since in the json response doesn't have an embedded group record.
The question is, is there a way I can disable embedding records in the 3rd level?
Please help.

A: Here is a good article about serialization:
http://www.toptal.com/emberjs/a-thorough-guide-to-ember-data#embeddedRecordsMixin
Ember docs:
http://emberjs.com/api/data/classes/DS.EmbeddedRecordsMixin.html
Basically, what it says is that you have 2 options 1) serialize and 2) deserialize. Those two have 3 options:

*

*'no' - don't include any data,

*'id' or 'ids' - include id(s),

*'records' - include data.

When you write {embedded: 'always'} this is shorthand for: {serialize: 'records', deserialize: 'records'}.
If you don't want the relationship sent at all write: {serialize: false}.
The Ember defaults for EmbeddedRecordsMixin are as follows:
BelongsTo: {serialize:'id', deserialize:'id'}
HasMany: {serialize:false, deserialize:'ids'}


text:
Q: SUM(CASE WHEN) with condition of another aggregate function I'm fairly new to SQL and can't seem to get my query doing what I want it to do.
I want the sum of one column based on the occurrence of another condition.
My table looks something like this:

ID
Location
Scan_Code
Scan_Date

1
PlaceA
01
2021-02-01

1
PlaceA
02
2021-02-01

2
PlaceA
01
2021-02-01

2
PlaceA
02
2021-02-02

3
PlaceB
01
2021-02-01

3
PlaceB
02
2021-02-01

3
PlaceB
01
2021-02-02

3
PlaceB
02
2021-02-02

4
PlaceB
02
2021-02-02

The result should sum the occurrence of Scan 01 on any given Date per Location and sum of Scan 02 IF there was a Scan 01 on the same day for that ID.
Expected result for the table above
|Scan_Date |Location|Sum_Scan01|ConditionalSum02|
|----------|--------|----------|----------------|
|2021-02-01|PlaceA  |2         |1               |
|2021-02-01|PlaceB  |1         |1               |
|2021-02-02|PlaceB  |1         |1               |

My query currently looks like this and sums all of scan 02 regardless of occurrence of scan 01 and I can't figure out how I can include that condition as I cant just repeat the first one in the second case:
select

scan_date,
Location,
SUM(case when scan_code EQ '01' then 1 else 0 end) as Scan01,
SUM(case when scan_code EQ '02' then 1 else 0 end) as Scan02

from ScanDB

where scan_date between '?From' and '?To'
group by scan_date,Location

Thanks a lot from a new user.

A: You probably need nested aggregation, this should work:
with cte as
 ( select
      id, -- include id in inital calculation
      scan_date,
      Location,
      SUM(case when scan_code = '01' then 1 else 0 end) as cntScan01,
      SUM(case when scan_code = '02' then 1 else 0 end) as cntScan02
   from ScanDB
   where scan_date between '?From' and '?To'
   group by id,scan_date,Location
 )
select
   scan_date,
   Location,
   SUM(cntScan01) as Scan01,
   -- check if 01 exists for same id
   SUM(case when cntScan01 > 0 then cntScan02 else 0 end) as Scan02
from cte
group by scan_date,Location

A: I would be inclined to use window functions:
select scan_date, Location,
       sum(case when scan_code EQ '01' then 1 else 0 end) as Scan01,
       sum(case when num_id_01 > 0 and scan_code EQ '02' then 1 else 0 end) as Scan02
from (select s.*,
             sum(case when scan_code EQ '01' then 1 else 0 end) over (partition by id, scan_date) as num_id_01
      from ScanDB s
      where s.scan_date between '?From' and '?To'
     ) s
group by scan_date, Location;


text:
Q: Could not load the Tomcat server configuration I have installed apache tomcat7 using sudo apt get in ubuntu. I have added apache tomcat 7 to eclipse using Windows > Preferences > Server > Runtime Environment.But when I'm starting the server from server view by right clicking the shown Tomcat v7.0 Server at localhost [Stopped,Republish]
It says:

Could not load the Tomcat server configuration at /Servers/Tomcat v7.0
  Server at localhost-config. The configuration may be corrupt or
  incomplete.

The path to tomcat7 that I've provided is /usr/share/tomcat7

A: I've just been encountering a very similar issue in Ubuntu while trying to get Eclipse Mars and Tomcat7 integrated because Eclipse was expecting the tomcat configuration files etc to be all in the same location, and with the necessary permissions to be able to change those files.
The following instructions from this blog article helped me in the end:
cd /usr/share/tomcat7
sudo ln -s /var/lib/tomcat7/conf conf
sudo ln -s /var/log/tomcat7 log
sudo ln -s /etc/tomcat7/policy.d/03catalina.policy conf/catalina.policy
sudo chmod -R a+rwx /usr/share/tomcat7/conf

A: I've just solved this exact problem on my Ubuntu 14.04 with Eclipse Mars 2.
This could happen when Eclipse is not finding Tomcat's configuration files where they are expected to be. This place is in
$eclipse_workspace_folder/$version_of_your_tomcat_server_at_localhost/
(by default if you didn't changed server's name). So you have to copy all the files under your $tomcat_installation_folder/conf/* to the workspace server's folder.
But it was easier to just remove the server from your server list and add it again. Eclipse will automatically recreate all these files again into the proper folders. Like in the picture below:

In my case I've downloaded tomcat-8.0.35 from the website, so the configuration files needed are in /opt/apache-tomcat-8.0.35/conf/ filesystem.
Just delete the desired server from the Servers view (Window -> Show View -> Servers) and then go to Window -> Preferences -> Server -> Runtime Environment -> Add and add the server again.

A: The application is trying to load /usr/share/tomcat7/conf/ which doesn't exist. Eclipse assumes conf is in the same directory as bin
In Ubuntu, conf is placed in /etc/tomcat7/ and there is a symbolic link in /var/lib/tomcat7/.
To solve this, you can either

*

*Download package from Apache Tomcat, and place them in a specific directory, say /opt/ or

*Create a symbolic link in /usr/share/tomcat7/ pointing to /etc/tomcat7/conf

A: A quick solution in eclipse to resolve when Tomcat could not load as per the following error:

Just refresh the Tomcat folder should do the trick.  If it still does not work, delete all files in eclipse under the Tomcat folder, re-copy the server files then refresh the Tomcat folder.  Tomcat should restart correctly after that.

A: You can install tomcat7 in ~/tomcat7 instead of /usr/share/tomcat7.

*

*Close Eclipse.

*Delete org.eclipse.wst.server.core.prefs and org.eclipse.jst.server.tomcat.core.prefs in {workspace-directory}/.metadata/.plugins/org.eclipse.core.runtime/.settings.

*Launch Eclipse.

*Go to Window->Show View->Other... and choose the Servers.

*Select Tomcat v7.0 Server from the server type and press Next.

*Enter /home/user/tomcat7 (not /usr/share/tomcat7) into the "Tomcat installation directory" and press Download.

*Wait a few minutes and press Finish.

tomcat7 worked correctly with Eclipse 4.4 on my Ubuntu 15.04 in this way.

A: I know it's an old question and it has been solved already but for me the Tomcat conf/tomcat-users.xml file was created with a different encoding from the rest of the configuration files. The first line of that file looked like this:
<?xml version='1.0' encoding='cp65001'?>

All I had to do to solve the issue was change that line for:
<?xml version="1.0" encoding="UTF-8"?>

And voila.
I have no idea what 'cp65001' means or why it was created like that.
Maybe this will help other users facing the same issue.

A: I have Windows 8.1, Eclipse Neon, Tomcat 8.
The solution is to copy all the files from folder ".../Tomcatxxx/conf" to the ".../Workspace_directory/Servers" and try to launch server again.

A: You tried to start Tomcat and got the following error:
Could not load the Tomcat server configuration at /Servers/Tomcat v7.0 Server at localhost-config. The configuration may be corrupt or incomplete

How to solve:

*

*Close Eclipse

*Copy all files from TOMCAT_7_HOME/conf to WORKSPACE_FOLDER/Servers/Tomcat v7.0 Server at localhost-config

*Start Eclipse

*Expand the Servers project, click on the Tomcat 7 project and hit F5

*Start Tomcat from Eclipse

A: I know it's been a while since this question was posted, but I was just getting this exact error, and I have a really simple solution that MIGHT work for some. All I did was double click on the folder 'Servers', which then allowed me to start the server with no error message. Sometimes the solution is right in front of your eyes. This might work for some people like me who go straight to google without trying fix the issue themselves!

A: on Centos 7, this will do it, for Tomcat 7 :
(my tomcat install dir: opt/apache-tomcat-7.0.79)

*

*mkdir /var/lib/tomcat7

*cd /var/lib/tomcat7

*sudo ln -s /opt/apache-tomcat-7.0.79/conf conf

*mkdir /var/log/tomcat7

*cd /var/log/tomcat7

*sudo ln -s /opt/apache-tomcat-7.0.79/logs log

not sure the log link is necessary, the configuration is the critical one.
:

A: Had the same issue with Kepler (after trying to add a Tomcat 7 server).
Whilst adding the server I opted to install the Tomcat binary using the download/install feature inside Eclipse. I added the server without adding any apps. After the install I tried adding an app and got the error.
I immediately deleted the Tomcat 7 server from Eclipse then repeated the same steps to add Tomcat 7 back in (obviously skipping the download/install step as the binary was downloaded first time around).
After adding Tomcat 7 a second time I tried adding / publishing an app and it worked fine. Didn't bother with any further RCA, it started working and that was good enough for me.

A: I had the same problem in Eclipse Oxygen with Tomcat 8 in ubuntu 16.04 LTS.
Solution:
1. Give permission to entire tomcat folder (chmod 777 -R /Tomcat)
2. Delete and re-add the server in eclipse
3. Restart eclipse
4. Start the tomcat server. It will work..........

A: In the Servers tab of eclipse, go to the properties of the server and Switch location to latest downloaded tomcat version.
This resolved the issue for me.
Tomcat Server Properties

A: I solved this problem. DON'T USE THE .exe
Unistall Tomcat and download the .zip from Tomcat's web site. Then unpack and put it in C:\Program Files. Open Eclipse and set the server. it will work.


text:
Q: How to set TLS 1.1 in Powershell? I need to be able to enable tls 1.1 while script is running and to revert back to normal when the script is finished. How would I be able to do this?
Googling this hasn't yielded any results.

A: try{
    $InitialSecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol
    [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls11

    # Your code here
}
finally {
    [System.Net.ServicePointManager]::SecurityProtocol = $InitialSecurityProtocol
{

You don't need the try/finally block, but it will help with ensuring that the TLS setting is reverted upon completion of the script. The [System.Net.ServicePointManager]::SecurityProtocol setting will always be reset in a new PowerShell session, too, so unless you're going to be reusing the session that you're in, you don't really have to worry about the value being changed.
If you want TLS 1.1 or 1.2, you can specify:
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls11 -bor [System.Net.SecurityProtocolType]::Tls12

Note that if you have a really old version of PowerShell (anything without .Net 4.5 installed, IIRC) then the above command will not work. This is because TLS 1.1 and 1.2 were not added until .Net 4.5 added them to the .Net framework.
Also, this will only affect .Net calls or most PowerShell module commands. If you're using an external application or potentially some third party modules, you may need alternative configurations.

Note that as of .Net Core v2.0+ (so Powershell Core 6+, Powershell 7+) and I think as of .Net Framework 4.7+ (so latter versions of Windows Powershell after .Net Framework 4.7+ updates have been installed, and possibly only on later versions of Windows) the default value for [System.Net.ServicePointManager]::SecurityProtocol has changed from Ssl3, Tls to a much more failsafe SystemDefault (which did not exist at all, previously). When it's set to SystemDefault, the Powershell session will allow the operating system to determine the security protocols used, so the ciphers and protocols used will be whatever the OS is configured for. This setting is the best setting for most situations, since it should include all future OS updates and system configuration changes.


text:
Q: iOS7 Custom Transitions with UINavigationController I am using the iOS7 custom transitions to modally present a new view controller.
The new view controller is a navigation controller.
The controller animates up from the bottom, while the background view blurs.
My issue is that the navigation bar on the new controller, while animating upwards, appears to allows for a status bar, ie it seems to be 64 points high. When it has reached its final location and called completeTransition it realises no status bar space is required and snaps back to 44 points.
Is there a way to

*

*Initially inform the nav controller/top view controller that no status bar is required.
OR

*Call whatever method that completeTransition is calling before the animation so that the automatic re-adjusting takes place then.

While animating:

Animation complete:

A: The trick was to add the view of the presented view controller to the container view AFTER setting its initial position off the bottom of the screen. This prevents the container view from thinking it is at the top of the screen and automatically laying out with status bar provision accordingly.
It is related to the following from WRESTLING WITH STATUS BARS AND NAVIGATION BARS ON IOS 7:
"UINavigationController will alter the height of its UINavigationBar to either 44 points or 64 points, depending on a rather strange and undocumented set of constraints. If the UINavigationController detects that the top of its view's frame is visually contiguous with its UIWindow's top, then it draws its navigation bar with a height of 64 points. If its view's top is not contiguous with the UIWindow's top (even if off by only one point), then it draws its navigation bar in the "traditional" way with a height of 44 points. This logic is performed by UINavigationController even if it is several children down inside the view controller hierarchy of your application. There is no way to prevent this behavior."

A: Alan, since you haven't marked your question answered I'm putting this up so others can find it. I ran into a similar situation and your fix wouldn't work in my case so this more general solution may be more widely helpful.
Found over here Navigation bar has wrong position when modal a view controller with flip horizontal transition in iOS 7
A quick workaround is to put:
[self.navigationController.navigationBar.layer removeAllAnimations];

In the viewWillAppear of the view you are transitioning to.  This would avoid the need to first place your view below the screen and then move it up before animating.
As you pointed out above, the UINavigationController is figuring out it's size at some point and this is conflicting with the animation.

A: I had similar problems with the UINavigationBar.
In one case, it was in a custom splitview (we can't use the UIKit one because there are some features missing in iOS 5.0) and also with a UINavigationController that has its view added inside another view.
The use of controller hierarchy helped a lot here, it seems iOS also pays some attention to that when deciding how to layout the UINavigationBar. I was able to have a UINavigationController with the correct height defined by the OS without having the UINavigationBar contiguous with its UIWindow's top, so that is possible to do.
There was a problem however, when the view first appeared it had the incorrect height and then kind of automatically increased to have the correct height of 64 pixels all by itself.
The solution to get the view with the correct height from the start was to initially define the view with the whole width of the screen and then use the [UIViewController viewDidLayoutSubviews] method to define the frame of the view with the width I wanted.
This meant the controller was doing the layout of the UINavigationBar the way I wanted it to and then I would correct the frame of the view and that would not change the height of the UINavigationBar.
For the specific situation the OP presented, you can do the contrary. First define the view with half the width so the bar is small at the beginning and then change the width back to what you want. I tested this in another situation and it also worked, but it didn't had an animation, that may kill my solution. I recommend changing the width and the x position.
This is a terrible hack, so if someone comes up with a solution that will allow me to remove this code, do share.


text:
Q: SAP GUI Script & VBA: Get System Name / ID I have already created a gui scripting to automate some task. Now, there is a part where I needed to get the SAP system ID / Name. I need get the system ID / Name where the user is currently logged on.
Currently I am using Q4N. So far below is my Code:
Dim app As Variant
Dim SAPGUIAuto As Object
Dim Connection As Variant
Dim session As Variant
Dim MainPage as Worksheet
set MainPage = Sheets("Main")

If Not IsObject(app) Then
Set SAPGUIAuto = GetObject("SAPGUI")
Set app = SAPGUIAuto.GetScriptingEngine
End If
If Not IsObject(Connection) Then
Set Connection = app.Children(0)
End If
If Not IsObject(session) Then
Set session = Connection.Children(0)
End If
If IsObject(WScript) Then
WScript.ConnectObject session, "on"
WScript.ConnectObject app, "on"
End If

Set Info = session.Info()

MainPage.Range("E22") = Val(Info.SystemName())

I tried to display this Info.SystemName() but it gives me zero number.
I also tried recording a script in order to get this info:

Unfortunately, there is no recorded step for me to be able to get the system ID.


text:
Q: undefined method: nil:NilClass Can someone help explain why the following code produces a:
5.times do
  star_count = star_count + 1
  puts "*" * star_count
end

#=> NoMethodError: undefined method `+' for nil:NilClass

The desired effect of the code is the following image below:
*
**
***
****
*****

Sorry for including the asterisk triangle as code ... was not outputting right so that was the only solution I could think of. Treating the triangle as an image did not work either.

A: start_count must be initialized to 0 before the loop in this case.
Anyway, there is more idiomatic in Ruby:
5.times do |index|
  puts '*' * (index + 1)
end

A: You can also use upto instead of times to start from another index than zero.
1.upto(5) do |index|
  puts '*' * index
end


text:
Q: Posting to a secure API with swift I'm trying to post to an API secured with a key (MailGun) with swift but it appears that my key is never utilized as I receive a Forbidden 401 error (Unauthorized - No valid API key provided) according to https://documentation.mailgun.com/api-intro.html#errors
I've verified the URL and key are correct by posting using curl, but I am unable to figure out why my key is not used here. I'm hoping someone can point in the right direction as to why this isn't authenticating correctly
My code is as such but I have replaced all the personal info with <>:
// Email the FBO with desired information
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: NSURL(string: "https://api.mailgun.net/v3/<My Domain>/messages")!)
request.HTTPMethod = "POST"
let data = "from: Excited User <scheduler@<mg.mydomain.com>>&to: [bar@example.com,<my email>]&subject:Hello&text:Testinggsome Mailgun awesomness!"
request.HTTPBody = data.dataUsingEncoding(NSASCIIStringEncoding)
request.setValue("key-<my key>", forHTTPHeaderField: "api")
let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
    if let error = error {
        print(error)
    }

    if let response = response {
        print("url = \(response.URL!)")
        print("response = \(response)")
        let httpResponse = response as! NSHTTPURLResponse
        print("response code = \(httpResponse.statusCode)")
    }
})
task.resume()

Update:
Banged away at it for a few hours and I still can't get my head around it. Maybe I'm not exactly sure what you mean? I can successfully get a response with curl by using:
curl -s --user 'api:key-<my personal key>' https://api.mailgun.net/v3/mg.<my domain>.com/messages -F from='Reservation Scheduler <scheduler@mg.<my domain>.com>' -F to=reservations@<my domain>.com -F subject='Curl Test' -F text='Test from terminal'

I tried inputting it explicitly like so:
request.setValue("api", forHTTPHeaderField: "username")
request.setValue("key-<my key>", forHTTPHeaderField: "password")

It looks to me like the basic auth credentials are never sent? How can I be sure that the fields are "user" and "password"?

A: After verifying my header appeared to be missing the authentication section of the header I was able to get this working properly with a large HTTP response. I put the full path into Keys.plist so that I can upload my code to github and broke out some of the arguments into variables so I can have them programmatically set later down the road.
// Email the FBO with desired information
// Parse our Keys.plist so we can use our path
var keys: NSDictionary?

if let path = NSBundle.mainBundle().pathForResource("Keys", ofType: "plist") {
    keys = NSDictionary(contentsOfFile: path)
}

if let dict = keys {
    // variablize our https path with API key, recipient and message text
    let mailgunAPIPath = dict["mailgunAPIPath"] as? String
    let emailRecipient = "bar@foo.com"
    let emailMessage = "Testing%20email%20sender%20variables"

    // Create a session and fill it with our request
    let session = NSURLSession.sharedSession()
    let request = NSMutableURLRequest(URL: NSURL(string: mailgunAPIPath! + "from=FBOGo%20Reservation%20%3Cscheduler@<my domain>.com%3E&to=reservations@<my domain>.com&to=\(emailRecipient)&subject=A%20New%20Reservation%21&text=\(emailMessage)")!)

    // POST and report back with any errors and response codes
    request.HTTPMethod = "POST"
    let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
        if let error = error {
            print(error)
        }

        if let response = response {
            print("url = \(response.URL!)")
            print("response = \(response)")
            let httpResponse = response as! NSHTTPURLResponse
            print("response code = \(httpResponse.statusCode)")
        }
    })
    task.resume()
}

The Mailgun Path is in Keys.plist as a string called mailgunAPIPath with the value:
https://API:key-<my key>@api.mailgun.net/v3/<my domain>.com/messages?

Hope this offers a solution to anyone else having issues with MailGun and wanting to avoid a 3rd party solution!


text:
Q: Fuzzy text in Qt application? I wrote a Qt application that drawing text, when using a certain font (Inconsolata) in small point sizes, it looked fuzzy:

But when using other font (Courier New, etc..) it's just fine:

What strange here is that other applications using that font looks normal, here is a contrast (left is vim, right is my application):

What would be the problem here?
Environment:
Window 7 Ultimate 64-bit
PySide 1.2.2 & Qt 4.8
Inconsolata.otf (http://www.levien.com/type/myfonts/inconsolata.html)
Code example (the problem is more serious on a dark scheme):
from PySide.QtGui import *

app = QApplication([])
label = QLabel('hello\nworld')
label.setStyleSheet('QLabel {background: #000; color: #fff;}')
label.setFont(QFont('Inconsolata', 11))
label.show()
app.exec_()

A: You can try changing the Qt font style strategy of your QFont and see what gives the best result.
For example to enable antialiasing on your application's default font, you can do:
QFont font = QApplication::font();
font.setStyleStrategy(QFont::PreferAntialias);
QApplication::setFont(font);


text:
Q: How to do this loop in twig? I'm learning twig language! I have a question.
How can I do this loop en twig? I want to concat, in a string var, all the names of my list.
{% for student in studentList %}
    {% set studentString ~ student.name %} // How can i do this line?
{% endfor %}

Thank you!!

A: {% set studentString = '' %}
{% for student in studentList %}
    {% studentString = studentString ~ student.name %}
{% endfor %}


text:
Q: Trying to get property on a non object Yii 1.1.15 I try to change Css file for CGridView widget, in my config/main.php:
'components' => array(
     'widgetFactory' => array(
         'widgets' => array(
            'CGridView' => array(
                'cssFile' => Yii::app()->request->baseUrl . '/css/gridview.css',
            ),
         ),
      ),
  ...

And I get warning:
Trying to get property on a non object /path_to_project/protected/config/main.php on line 79

How I can suppress this warning, and why I getting it, in when I using it in view files it all works.
P.S. Yes I can set display_errors ini set to false and message will dissapearm but I want get clearly with it. Thanks!

A: The reason for the warning is that the CHttpRequest object Yii::app()->request has not been instantiated yet.
From the API page for CApplication:

CApplication will undergo the following lifecycles when processing a
  user request:

*

*load application configuration;

*set up error handling;

*load static application components;

*onBeginRequest: preprocess the user request;

*processRequest: process the user request;

*onEndRequest: postprocess the user request;

  Starting from lifecycle 3, if a PHP error or an uncaught exception occurs, the application will switch to its error handling logic and jump to step 6 afterwards.

Your error is happening at the first step. As such, Yii's error handling has not been setup yet. The only option is to suppress this warning using the @ operator:
 'cssFile' => @Yii::app()->request->baseUrl . '/css/gridview.css',

HOWEVER
This is a terrible idea, since you are essentially hiding the error instead of fixing it.
If your views are being displayed correctly (no css errors), you can omit the Yii::app()->request->baseUrl and just use:
'cssFile' => '/css/gridview.css'

If you are experiencing errors, you can create a class in your components folder that extends CWidgetFactory and set any variables that depend on other components here e.g
class MyWidgetFactory extends CWidgetFactory {
    public function init() {
        parent::init();
        $this->widgets['CGridView']['cssFile'] = Yii::app()->request->baseUrl.'css/gridview.css';
    }
}

You will need to adjust your components to use this file:
'components' => array(
    'widgetFactory' => array(
        'class' => 'MyWidgetFactory'
    ...


text:
Q: How does Anarchy work? No mention of it in the game documentation that I can find. When do you get anarchy? How exactly does it work? Any additional thoughts on when it is worthwhile or just always avoid it? I have played a few games and never had anarchy and suddenly I have a game with anarchy.

A: Anarchy is triggered when you switch to a government type your civilization has previously had.
It lasts a small number of turns, and during anarchy, no yields are accrued (though you can still command units normally).


text: Q: Can anyone resolve this issues? Two buttons (add to cart )are coming with the disabled mode I need to apply the code for the add to cart button but it is coming in disabled mode hence unable to do the required changes.strong text


text:
Q: Custom cell is Duplicating the properties of the other cell in the same Tableview I am using a custom cell for my UITableview in which I am having few UILabels. In one label I am setting it's color to red.That is working very fine for me. But As soon as I am reloading the TableView by Egorefresh Table delegate Methods the color of the label of other cells also start changing to red color. I don't know why this problem is coming and it is causing a lot of disgust to me.
This is the code for the TableView datasource method cellForRowAtIndexPath:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell
  forRowAtIndexPath:(NSIndexPath *)indexPath{

    // Set the Frame for BackgroundView of Cell.
    NSDictionary * insuranceDic = [arr_insurance objectAtIndex:indexPath.row];
    insuranceDic = [[AppDelegate sharedInstance] removeNullsFromDictonary:insuranceDic];
    InsuranceCell * mycell = (InsuranceCell *)cell;
    if([[insuranceDic valueForKey:@"active"] isEqualToString:@"N"]){
        //TTTRegexAttributedLabel * label = [[TTTRegexAttributedLabel alloc] init];
        mycell.lbl_insuranceName.text =  [NSString stringWithFormat:@"%@ (%@)",
       [insuranceDic valueForKey:@"insurance_name"],@"Inactive"];
        mycell.lbl_insuranceName.textColor = [UIColor redColor];
        //[label setText:cell.lbl_insuranceName.text withRegex:@"(Inactive)" withFont:
    [UIFont boldSystemFontOfSize:12] withColor:[UIColor redColor]];
    }
    else{
        mycell.lbl_insuranceName.text = [insuranceDic valueForKey:@"insurance_name"];
    }
}

And on reloading the table view from these methods the problem is occuring :
#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
// For Top Pull to refresh.
    [_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
   //For Bottom Pull to refresh.
    [pullToBottomRefreshManager_ tableViewScrolled];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:
  (BOOL)decelerate{
    // For Top Pull to refresh.
    [_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
    //For Bottom Pull to refresh.
    [pullToBottomRefreshManager_ tableViewReleased];
}

#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

// Belowline is for stop refresh indicator
//[_refreshHeaderView
  egoRefreshScrollViewDataSourceDidFinishedLoading:self.tableView];

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
    // When we going to refresh the data we need to reset the start varible to 1
    // and also removeallthe previous objects from the array.
    str_start = @"1";
    [self getInsuranceList];
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
      return isReloading; // should return if data source model is reloading
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:
  (EGORefreshTableHeaderView*)view{

      return [NSDate date]; // should return date data source was last changed

}

#pragma mark -
#pragma mark MNMBottomPullToRefreshManagerClient Methods
- (void)bottomPullToRefreshTriggered:(MNMBottomPullToRefreshManager *)manager {

   // Here we are incrementing start with records per page means start+=recordsperpare
   or start+=20.
   str_start = [NSString stringWithFormat:@"%d",[str_start intValue]+
   [str_recordsPerPage intValue]];
   [self getInsuranceList];
}

This is the code for cellForRowAtIndexPath method:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
    (NSIndexPath
    *)indexPath{
    static NSString *CellIdentifier = @"Cell";
    InsuranceCell  * cell = [InsuranceCell dequeOrCreateInTable:tableView];
     //    UITableViewCell *cell = [tableView
     dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
      cell = [[[InsuranceCell alloc] initWithStyle:UITableViewCellStyleDefault
      reuseIdentifier:CellIdentifier] autorelease];

    }
    NSDictionary * insuranceDic = [arr_insurance objectAtIndex:indexPath.row];
    insuranceDic = [[AppDelegate sharedInstance] removeNullsFromDictonary:insuranceDic];
    cell.lbl_insuranceNo.text = [insuranceDic valueForKey:@"insurance_no"];
    cell.lbl_groupNo.text = [insuranceDic valueForKey:@"group_no"];
    cell.lbl_priority.text = [self getPriorityDescFromCode:[insuranceDic
    valueForKey:@"priority"]];
    cell.lbl_startDate.text = [insuranceDic valueForKey:@"start_date"];
    cell.lbl_endDate.text = [insuranceDic valueForKey:@"end_date"];
    cell.lbl_copay.text = [insuranceDic valueForKey:@"copay"];

   // This Condition is For setting alternate (White/SkyBlue) Background color for cell.
   //    if (fmod(indexPath.row, 2)==0) {
   //        cell.backgroundView.backgroundColor = [UIColor colorFromRGBIntegers:237       green:243 blue:249 alpha:1];
   //
   //    }
   //    else{
   //        cell.backgroundView.backgroundColor = [UIColor colorFromRGBIntegers:250   green:250 blue:250 alpha:1];
   //    }

   cell.selectionStyle = UITableViewCellEditingStyleNone;
   return cell;
 }

A: It would help if you could add your cellForRowAtIndexPath: implementation.
Given the information you provide I suppose you are reusing cells and not resetting the color before.
You need to override - (void)prepareForReuse in your InsuranceCell
and reset any cell specific properties.
Sample Implementation:
- (void)prepareForReuse {
    [super prepareForReuse];
    // reset the label text color to your default color (e.g. black)
    self.lbl_insuranceName.textColor = [UIColor blackColor];
}

You need to implement this method within your InsuranceCell.
You need to understand, that with the default implementation of cellForRowAtIndexPath: your TableViewCells will be reused. This means you need to reset every property explicitly, before you reuse a cell. The most convenient way to do this, is overriding the prepareForReuse method, as shown above.


text:
Q: Parallelization of the stochastic Euler scheme I wrote a simulation to approximate the law of
a stochastic differential equation via a Monte
Carlo method using the stochastic Euler scheme.
Then I thought, it would be a good idea to speed
up things by means of parallelization, but
although I think it is an easy example (and similar problems were discussed here lots of times), none of my attempts was successful.
First the code (you can find some explanations below):
(* Parameters of the SDE and radius of the Ball *)
T = 10; sigma = 3.0; z = 1; R = 5*10^6;

(* w denotes the noise and h the step size *)
Euler[x_, w_, h_] := x - x^3*h + sigma*w;

(* Noise is a List of Lists of random numbers *)
MCEuler[h_, StepsMC_, Noise_] := Quiet[Check[
  Total[Table[
   Fold[ Euler[#1, #2, h] &, z, Noise[[i]]]
   , {i, 1, StepsMC}]
  ]/StepsMC,
Indeterminate
]];

MCEulerMT[h_, StepsMC_, Noise_] :=
 Total[Table[Catch[Fold[If[Abs[Euler[#1, #2, h]] >= R, Throw[0],
     Euler[#1, #2, h]] &, z, Noise[[i]]]], {i, 1, StepsMC}]]/StepsMC;

Comparison[h_, StepsMC_] := Module[{Noise},
  Noise = Table[RandomReal[NormalDistribution[0, Sqrt[h]], T/h], {StepsMC}];
  Return[{StepsMC, h, MCEuler[h, StepsMC, Noise], MCEulerMT[h, StepsMC, Noise]}];
];

Result =
 Table[Table[Comparison[h, StepsMC], {h, {2^0, 2^-2, 2^-4, 2^-6}}], {StepsMC, {10^3}}]

MCEuler implements the Monte Carlo Simulation
using the standard stochastic Euler scheme. Since
the coefficients of the stochastic differential
equations doesn't fulfill standard assumptions
like Lipschitz-continuity, it is possible, that
some "discrete trajectories" explode. Therefore, I
added the Quiet and Check commands.
MCEulerMT uses again the Euler scheme, but if some
"discrete trajectory" leaves a ball of radius R,
we set the value to zero.
The Comparison-method should test both procedures
on the same noise.
Then I replaced the Table-Commands in MCEuler,
MCEulerMT and the last line of the code (I didn't
use it creating the noise, but I think there are
no side-effects!?) by "ParallelTable" and the runtime was awful. It
was much slower than the code above, and I tried
other implementations and commands (e.g.
Parallelize) but I didn't make any progress.
Perhaps here are some guys, who could explain me,
what's wrong about my idea, and how I could fix
it.

A: The problem you have and what I've shown very often here is, that you can't assume, just that you're using a parallelised version of a function, to gain speed at least double.
The problem with parallelised algorithms is always that you've to package your work-load (the stuff you want to calculate on) on the available processors (cores).
If you start to go parallel you have to start to measure and to find out how to best package your work-load in such sub-units, as that your processors are working on them and don't mutual prevent themselves.
Something that you don't want is that processor A needs to wait on some data, which processor B is actually working on.
It is very often the case, that people expect through the prefix Parallel a parallelisation which will make their algorithms faster and are astonished that it took even longer than before.
You have to keep in mind, that all the definitions are needed to be copied to all the available kernels etc. this is really expensive. So in order to gain something from parallelisation you need to rethink your data layout and how it should be distributed amongst the available kernels.
Every parallel algorithm that I've seen so far does look very different from its serial counterpart. The beautiful thing about Mathematica is that you could leave most of your algorithm parts untouched, but you need to take care about how your data is distributed amongst the kernels.
You could see the parallelisation of Mathematica as a data driven parallelisation. This is because most of Mathematica's internals aren't thread-safe, that's why data gets distributed.
Edit 1: Gaining speed
1. Speeding up Euler:
First thing I've done is running a Profile on your implementation:

It comes at no surprise (reading your code), that the function Euler is called very often. So the first thing that came to my mind was: "if that function is eating up all the processor cycles, why not try to reimplement it to gain some speed?"
The function Euler is rather simple and there is no point to parallelise it,
but why don't Compile it?
cEuler = Compile[{{x, _Real}, {w, _Real}, {h, _Real}},
    Module[{sigma = 3.0}, x - x^3*h + sigma*w],
    CompilationTarget -> "C",
    CompilationOptions -> {
        "ExpressionOptimization" -> True,
        "InlineCompiledFunctions" -> True,
        "InlineExternalDefinitions" -> True}
];

Let me say something about "InlineExternalDefinitions". You've declared some global variables like sigma. The problem with Compile is the following, if we leave the CompilationOption "InlineExternalDefinitions" undefined the code will be compiled as follows:

This means, that every time the function cEuler is called it'll call the main evaluator in order got get the value of sigma. If something like that happens, all the compilation does not make sense anymore and it is even slower compared to a non-compiled version.
If you define "InlineExternalDefinitions" the variable sigma will get inlined and no call to the main evaluator is needed anymore.
2. Creating a global Noise table:
Although Mathematica has quite different parameter passing semantics when compared to C/C++ it gives me allways a bad feeling if arrays/array indices are passed around. That's why I rewrote the Noise creation functionality.
MyNoise = {};

SetAttributes[createNoise, HoldFirst];
createNoise[noise_, h_, StepsMC_] := Module[{T = 10},
  noise = ParallelTable[RandomReal[NormalDistribution[0, Sqrt[h]], T/h], {StepsMC}];
]

We'll call this function with an external list per reference, so that the list is filled up with the list of random numbers.
Actually the Noise creation is the only part of your code that is parallelisable, if you leave the code mostly as it is.
If you execute createNoise and observe the parallel kernel status at the same time, you'll realize that the random number creation is well distributed amongst the kernels, but they aren't really busy.
We should take notice, that we have to weigh the cost of parallelisation with the actual range of the data. It looks that way that a range of StepsMC (1000 in your case) is even not a big enough to really benefit from parallelisation.
But let's see, maybe later we'll increase StepsMC, so it is good to have it and there is no pain in executing it.
3. The rest of the code:
MCEuler[h_, StepsMC_] :=
Quiet[Check[
  Total[Table[
   Fold[cEuler[#1, #2, h] &, z, MyNoise[[i]]], {i, 1, StepsMC}]]/
  StepsMC, Indeterminate]];

MCEulerMT[h_, StepsMC_] :=
 Total[Table[
   Catch[Fold[
     If[Abs[cEuler[#1, #2, h]] >= R, Throw[0], cEuler[#1, #2, h]] &,
       z, MyNoise[[i]]]], {i, 1, StepsMC}]]/StepsMC

Comparison[h_, StepsMC_] :=
  createNoise[MyNoise, h, StepsMC];
  Return[{StepsMC, h, MCEuler[h, StepsMC], MCEulerMT[h, StepsMC]}];]

Here is nothing to parallelize. Although Fold per se can get parallelised, but it is not if you use complex slot patterns. Again, I doubt that with the current range of StepsMC it worth's the effort to rewrite the algorithms to become parallelised on a large degree.

So now let's execute the code:
LaunchKernels[] (*let's save some time *)

Comparison[#, 10^3] & /@ {2^0, 2^-2, 2^-4, 2^-6} // AbsoluteTiming

This yields the following result:

{4.803885, {{1000, 1, Indeterminate, -563.98}, {1000, 1/4,
     Indeterminate, -2051.07}, {1000, 1/16, 0.0108648,
     0.0108648}, {1000, 1/64, -0.0300972, -0.0300972}}}

Comparing that with your original implementation this is a speedup of roughly factor 2:

{10.374996, {...}


text:
Q: DRYing rails view: partial vs helper I need an advice on best practices for DRYing view code.
I have three classes (NewsItem, RssItem and BlogItem) in my app, that use separate views, but have similar parts in them. One of the parts is such:
<% if current_user %>

  <%= marks_bar(@item) %>
  <%= favorite_button(@item, "blog_item") || delete_from_favorite_button(@item, "blog_item") %>
  <%= share_button(@item) %>
  <% if current_user.is_mine?(@item) %>

<%= link_to "Edit", edit_user_blog_item_path(current_user, @item) %>

  <% end %>

<% end %>

It's almost equal for all three classes, so I decided to take it out to some separate place. And here I am confused: should I use a partial or helper method for it?
I know that helpers are used mostly for separating ruby code from HTML, but in this case the helper will look like:
def toolbar_for(item, type_str, edit_path)
  if current_user
    content_tag(:footer) do |b|
      marks_bar(item).to_s <<
      (delete_from_favorite_button(item, type_str) || favorite_button(@item, type_str)).to_s <<
      share_button(@item).to_s <<
      (content_tag(:div) { link_to("Edit", edit_path)} if current_user.is_mine?(@item)).to_s
    end
  end
end

So, there is almost no HTML code here.
Could you please give me advice, what method is better in your opinion and why? Also, are there some performance issues in these methods (for example multiple String concatenation or frequent partial loading might be costly)? (This app is rather high-loaded)

A: I'd use a view partial for this.  Good rule of thumb: if HTML is the output, use a partial. Helpers are not the junk drawer of your Rails app—they should really be used to output data, not presentation.  Though I usually recommend people eschew helpers in general, in favor of presenters, which are vastly underutilized in the Rails world.

A: I would say this is a great example of a partial.
I reserve helpers for generating arbitrary dynamic content. This is kind of a loose description so how about an example: I would make a helper that splits an array of ActiveRecord objects and displays them into N columns. In this case the passed object's structure is being leveraged in some way in order to generate the content, but the content itself is unimportant. If you think about it, form_for also fits this description.
Conversely partials are great for 'static' content, that needs to be reused on multiple pages. For instance you would create a partial to render a single item. The partial determines a particular items 'static' representation.
Your example fits much better into the second bin, in my opinion. Since the @item isn't being manipulated to generate the content, in fact it is hardly being used. It seems this helper is mostly glue code for other appropriately created helpers (share_button and marks_bar). The perfect use case for a partial!


text:
Q: iOS: Table reload altering layout I have UI that has a UITableView and another View. The UITableView has collapsible sections as shown in this sample code. Upon loading it looks like this:

The user can use a swipe gesture to expand the gray view on the right. I'm just changing origin of the gray view and using an animation to achieve this. So then it looks like this:

However, when I close a section of the UITableView, the UI seems to "reset" and snap back to it's original layout:

I would like to for the gray view to remain where it is when I open or close a section of my UITableView. How can I achieve this?
The code for my ViewController is below:
#import "BooklistMaster.h"
#import "BooklistDetailViewController.h"
#import "Booklist.h"
#import "BooklistTitleCell.h"
#import "BooklistTitle.h"
#import "BooklistDetailHeaderView.h"
#import "BooklistDetailSectionInfo.h"
#import "BooklistDetailHandler.h"

static NSString *SectionHeaderViewIdentifier = @"SectionHeaderViewIdentifier";

@interface BooklistDetailViewController ()

@property (nonatomic) NSMutableArray *sectionInfoArray;
@property (nonatomic) NSIndexPath *pinchedIndexPath;
@property (nonatomic) NSInteger openSectionIndex;
@property (nonatomic) CGFloat initialPinchHeight;

@property (nonatomic) IBOutlet BooklistDetailHeaderView *sectionHeaderView;

// use the uniformRowHeight property if the pinch gesture should change all row heights simultaneously
@property (nonatomic) NSInteger uniformRowHeight;

@end

//#define DEFAULT_ROW_HEIGHT 88
#define HEADER_HEIGHT 48

@implementation BooklistDetailViewController

@synthesize listTitleLabel;
@synthesize backButton;
@synthesize booklistMaster;
@synthesize titleBarView;
@synthesize searchBar;
@synthesize tap;
@synthesize booklistId;
@synthesize booklistName;
@synthesize spinner;
@synthesize detailPaneFocused;
@synthesize detailView;
@synthesize swipeLeft;
@synthesize swipeRight;
@synthesize tableView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view sendSubviewToBack:tableView];
    detailPaneFocused=NO;
    listTitleLabel.text = booklistName;
    [spinner startAnimating];
    [spinner setHidden:NO];
     [titleBarView setBackgroundColor:[UIColor colorWithRed:.77647 green:.77647 blue:.79607 alpha:1]];

    tap = [[UITapGestureRecognizer alloc]
           initWithTarget:self
           action:@selector(dismissKeyboard)];
    [tap setCancelsTouchesInView:YES];

    swipeLeft = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(didSwipeLeft:)];
    [swipeLeft setDirection:UISwipeGestureRecognizerDirectionLeft];
    [detailView addGestureRecognizer:swipeLeft];

    swipeRight = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(didSwipeRight:)];
    [swipeRight setDirection:UISwipeGestureRecognizerDirectionRight];
    [detailView addGestureRecognizer:swipeRight];

    // Set up default values.
    self.tableView.sectionHeaderHeight = HEADER_HEIGHT;
    /*
     The section info array is thrown away in viewWillUnload, so it's OK to set the default values here. If you keep the section information etc. then set the default values in the designated initializer.
     */
   // self.uniformRowHeight = DEFAULT_ROW_HEIGHT;
    self.openSectionIndex = NSNotFound;

    UINib *sectionHeaderNib = [UINib nibWithNibName:@"BooklistDetailSectionHeaderView" bundle:nil];
    [self.tableView registerNib:sectionHeaderNib forHeaderFooterViewReuseIdentifier:SectionHeaderViewIdentifier];

    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];

    BooklistDetailHandler *handler = [[BooklistDetailHandler alloc] initForController:self];
    [handler getBooklistForId:booklistId];
}

-(void)didSwipeRight:(UISwipeGestureRecognizer *)recognizer{
    if (detailPaneFocused==YES) {
        detailPaneFocused=NO;
        [UIView animateWithDuration:.3
                         animations:^ {
                             CGRect newBounds = self.detailView.frame;
                             newBounds.origin.x += 200;
                             self.detailView.frame = newBounds;
                             [self.detailView layoutSubviews];

                         }];
    }
}

-(void)didSwipeLeft:(UISwipeGestureRecognizer *)recognizer{
    if (detailPaneFocused==NO) {
        detailPaneFocused=YES;
        [UIView animateWithDuration:.3
                         animations:^ {
                             CGRect newBounds = self.detailView.frame;
                             newBounds.origin.x -= 200;
                             self.detailView.frame = newBounds;
                             [self.detailView layoutSubviews];

                         }];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];

}
- (IBAction)buttonPressed:(id)sender {

    [[self navigationController]  popViewControllerAnimated:YES];
}

-(void)dismissKeyboard {
    [searchBar resignFirstResponder];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [self dismissKeyboard];

}
-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    [self.view addGestureRecognizer:tap];

    [UIView animateWithDuration:.3
                     animations:^ {
                         CGRect newBounds = self.searchBar.frame;
                         newBounds.size.width += 200; //newBounds.size.width -= 215; to contract
                         newBounds.origin.x -= 200;
                         self.searchBar.frame = newBounds;
                         [self.searchBar layoutSubviews];
                     }];

}
-(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    [self.view removeGestureRecognizer:tap];
    [UIView animateWithDuration:.3
                     animations:^ {
                         CGRect newBounds = self.searchBar.frame;
                         newBounds.size.width -= 200; //newBounds.size.width -= 215; to contract
                         newBounds.origin.x += 200;
                         self.searchBar.frame = newBounds;
                         [self.searchBar layoutSubviews];
                     }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return booklistMaster.subLists.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
//    Booklist *list = [booklistMaster.subLists objectAtIndex:section];
//    return list.booklistTitles.count;

    BooklistDetailSectionInfo *sectionInfo = (self.sectionInfoArray)[section];
    NSInteger numStoriesInSection = sectionInfo.booklist.booklistTitles.count;

    return sectionInfo.open ? numStoriesInSection : 0;
}

//- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
//
//    NSMutableArray *array = [[NSMutableArray alloc] init];
//    for (Booklist *list in booklistMaster.subLists) {
//        [array addObject:@"a"];
//    }
//
//    return array;
//
//}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    BooklistDetailHeaderView *sectionHeaderView = [self.tableView dequeueReusableHeaderFooterViewWithIdentifier:SectionHeaderViewIdentifier];

    BooklistDetailSectionInfo *sectionInfo = (self.sectionInfoArray)[section];
    sectionInfo.headerView = sectionHeaderView;

    sectionHeaderView.titleLabel.text = sectionInfo.booklist.listName;
    sectionHeaderView.section = section;
    sectionHeaderView.delegate = self;

    return sectionHeaderView;

}

//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
//
//}
//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//
//  BooklistDetailSectionInfo *sectionInfo = (self.sectionInfoArray)[indexPath.section];
//    return [[sectionInfo objectInRowHeightsAtIndex:indexPath.row] floatValue];
//    // Alternatively, return rowHeight.
//}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    BooklistTitleCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BooklistTitleCell" forIndexPath:indexPath];

    Booklist *booklist = [booklistMaster.subLists objectAtIndex:indexPath.section];
    BooklistTitle *booklistTitle = [booklist.booklistTitles objectAtIndex:indexPath.row];
    cell.titleLabel.text=booklistTitle.title;

    return cell;
}

- (void)sectionHeaderView:(BooklistDetailHeaderView *)sectionHeaderView sectionOpened:(NSInteger)sectionOpened {

    BooklistDetailSectionInfo *sectionInfo = (self.sectionInfoArray)[sectionOpened];

    sectionInfo.open = YES;

    /*
     Create an array containing the index paths of the rows to insert: These correspond to the rows for each quotation in the current section.
     */
    NSInteger countOfRowsToInsert = sectionInfo.booklist.booklistTitles.count;
    NSMutableArray *indexPathsToInsert = [[NSMutableArray alloc] init];
    for (NSInteger i = 0; i < countOfRowsToInsert; i++) {
        [indexPathsToInsert addObject:[NSIndexPath indexPathForRow:i inSection:sectionOpened]];
    }

    /*
     Create an array containing the index paths of the rows to delete: These correspond to the rows for each quotation in the previously-open section, if there was one.
     */
    NSMutableArray *indexPathsToDelete = [[NSMutableArray alloc] init];

    NSInteger previousOpenSectionIndex = self.openSectionIndex;
    if (previousOpenSectionIndex != NSNotFound) {

        BooklistDetailSectionInfo *previousOpenSection = (self.sectionInfoArray)[previousOpenSectionIndex];
        previousOpenSection.open = NO;
        [previousOpenSection.headerView toggleOpenWithUserAction:NO];
        NSInteger countOfRowsToDelete = previousOpenSection.booklist.booklistTitles.count;
        for (NSInteger i = 0; i < countOfRowsToDelete; i++) {
            [indexPathsToDelete addObject:[NSIndexPath indexPathForRow:i inSection:previousOpenSectionIndex]];
        }
    }

    // style the animation so that there's a smooth flow in either direction
    UITableViewRowAnimation insertAnimation;
    UITableViewRowAnimation deleteAnimation;
    if (previousOpenSectionIndex == NSNotFound || sectionOpened < previousOpenSectionIndex) {
        insertAnimation = UITableViewRowAnimationTop;
        deleteAnimation = UITableViewRowAnimationBottom;
    }
    else {
        insertAnimation = UITableViewRowAnimationBottom;
        deleteAnimation = UITableViewRowAnimationTop;
    }

    // apply the updates
    [self.tableView beginUpdates];
    [self.tableView insertRowsAtIndexPaths:indexPathsToInsert withRowAnimation:insertAnimation];
    [self.tableView deleteRowsAtIndexPaths:indexPathsToDelete withRowAnimation:deleteAnimation];
    [self.tableView endUpdates];

    self.openSectionIndex = sectionOpened;
}

- (void)sectionHeaderView:(BooklistDetailHeaderView *)sectionHeaderView sectionClosed:(NSInteger)sectionClosed {

    /*
     Create an array of the index paths of the rows in the section that was closed, then delete those rows from the table view.
     */
    BooklistDetailSectionInfo *sectionInfo = (self.sectionInfoArray)[sectionClosed];

    sectionInfo.open = NO;
    NSInteger countOfRowsToDelete = [self.tableView numberOfRowsInSection:sectionClosed];

    if (countOfRowsToDelete > 0) {
        NSMutableArray *indexPathsToDelete = [[NSMutableArray alloc] init];
        for (NSInteger i = 0; i < countOfRowsToDelete; i++) {
            [indexPathsToDelete addObject:[NSIndexPath indexPathForRow:i inSection:sectionClosed]];
        }
        [self.tableView deleteRowsAtIndexPaths:indexPathsToDelete withRowAnimation:UITableViewRowAnimationTop];
    }
    self.openSectionIndex = NSNotFound;
}

-(void)setMasterBooklist:(BooklistMaster *)list{
    booklistMaster=list;
    /*
     Check whether the section info array has been created, and if so whether the section count still matches the current section count. In general, you need to keep the section info synchronized with the rows and section. If you support editing in the table view, you need to appropriately update the section info during editing operations.
     */
    if ((self.sectionInfoArray == nil) ||
        ([self.sectionInfoArray count] != [self numberOfSectionsInTableView:self.tableView])) {

        // For each play, set up a corresponding SectionInfo object to contain the default height for each row.
        NSMutableArray *infoArray = [[NSMutableArray alloc] init];

        for (Booklist *list in self.booklistMaster.subLists) {

            BooklistDetailSectionInfo *sectionInfo = [[BooklistDetailSectionInfo alloc] init];
            sectionInfo.booklist = list;
            sectionInfo.open = NO;

            // NSNumber *defaultRowHeight = @(DEFAULT_ROW_HEIGHT);
            NSInteger countOfTitles = sectionInfo.booklist.booklistTitles.count;
            for (NSInteger i = 0; i < countOfTitles; i++) {
                //[sectionInfo insertObject:defaultRowHeight inRowHeightsAtIndex:i];
            }

            [infoArray addObject:sectionInfo];
        }

        self.sectionInfoArray = infoArray;
    }
    [spinner stopAnimating];
    [spinner setHidden:YES];
    [self.tableView reloadData];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    if (detailPaneFocused==NO){
//        [self focusDetailPane];
//    }
}
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (detailPaneFocused==NO&&![indexPath isEqual:[tableView indexPathForSelectedRow]]){
        [self focusDetailPane];
    }
    return indexPath;
}

- (void)focusDetailPane{
    detailPaneFocused=YES;
    [UIView animateWithDuration:.3
                     animations:^ {
                         CGRect newBounds = self.detailView.frame;
                         newBounds.origin.x -= 200;
                         self.detailView.frame = newBounds;
                         [self.detailView layoutSubviews];

                     }];
}

@end

A: This is due to auto layout. If you change any frames directly with auto layout turned on, the views will revert to the positions defined by their constraints as soon as the view has to update itself. You should do your animation by making an IBOutlet to any constraints you want to change, and adjust their constant value in code (either that, or turn off auto layout).


text:
Q: How to show the progress bar in FTP download in async class in Android? How to show the  progress bar in FTP download in async class in android?
I've tried many things but didn't get the progress bar. Here's my code,
and I'm calling this class from other Activity passing the context of that activity to this class.
package com.scft;

import it.sauronsoftware.ftp4j.FTPClient;
import it.sauronsoftware.ftp4j.FTPDataTransferListener;

import java.io.File;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.StrictMode;
import android.util.Log;
import android.widget.PopupWindow;
import android.widget.Toast;

public class ftpdownload_class {

    static final String FTP_HOST= "**************";

    /*********  FTP USERNAME ***********/
    static final String FTP_USER = "*********";

    /*********  FTP PASSWORD ***********/
    static final String FTP_PASS  ="*******";
      File fileDownload=null;
      long startTime_ftpDownload=0;
      long endTime_ftpDownload=0;
      long downloaded_file=0;
      long startTime_ftpUpload=0;

      long endTime_ftpUpload=0;
      FTPClient client=null;
        public static File m_fileName;
        private PopupWindow pwindo;
       String  totaltime_ftpUpload,filesize_ftpUpload,ratevalue_ftpUpload,totaltime_ftpDownload,filesize_ftpDownload,ratevalue_ftp_download;
      Context mContext=null;
      public ftpdownload_class( Context c)
      {
          mContext=c;
      }
        public void ftp_downloadStart() {
            FTPClient ftp = new FTPClient();

            try {
                if (android.os.Build.VERSION.SDK_INT > 9) {
                    StrictMode.ThreadPolicy policy =
                            new StrictMode.ThreadPolicy.Builder().permitAll().build();
                    StrictMode.setThreadPolicy(policy);
                }

                ftp.connect(FTP_HOST,158);//158 is the port number
                //System.out.println(ftp.connect(host)[0]);
                ftp.login(FTP_USER, FTP_PASS);
                fileDownload = new File("/sdcard/test.mp3");
                fileDownload.createNewFile();

                startTime_ftpDownload = System.currentTimeMillis();

                ftp.download("test.mp3", fileDownload,
                        new FTPDataTransferListener() {

                    // lenghtOfFile = conection.getContentLength();

                    public void transferred(int arg0) {
                       // download_btn.setVisibility(View.GONE);
                        //Log.v("log_tag", "This is for transfer");
                       // Toast.makeText(getBaseContext(), " transferred ..."+arg0 , Toast.LENGTH_SHORT).show();
                    }

                    public void started() {

                        // TODO Auto-generated method stub
                       // Toast.makeText(getBaseContext(), " Download Started ...", Toast.LENGTH_SHORT).show();
                        //Log.v("log_tag", "This is for started");
                    }

                    public void failed() {
                       // download_btn.setVisibility(View.VISIBLE);
                        Toast.makeText(mContext, "  failed ...", Toast.LENGTH_SHORT).show();
                        System.out.println(" failed ..." );
                    }

                    public void completed() {

                       // download_btn.setVisibility(View.VISIBLE);

                        endTime_ftpDownload = System.currentTimeMillis(); //maybe

                        Toast.makeText(mContext, " Download completed ...", Toast.LENGTH_SHORT).show();

                        getspeedfor_ftp_download();
                        //Log.v("log_tag", "This is for completed");

                    }

                    public void aborted() {
                       // download_btn.setVisibility(View.VISIBLE);
                        Toast.makeText(mContext," transfer aborted,please try again...", Toast.LENGTH_SHORT).show();
                        //Log.v("log_tag", "This is for aborted");

                    }
                });

            } catch (Exception e) {
                e.printStackTrace();
                try {
                    ftp.disconnect(true);
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }

        }

           long downloaded_file_ftp=0;
     public void getspeedfor_ftp_download()
        {

            downloaded_file_ftp = fileDownload.length();

            //Log.d("DownloadManager", "download ended: " + ((endTime - startTime) / 1000) + " secs");
            String abc = (((endTime_ftpDownload - startTime_ftpDownload) / 1000) + " secs");
            totaltime_ftpDownload = abc;

            double size = (downloaded_file_ftp/1024);
            if(size<1000)
                filesize_ftpDownload=String.valueOf(size).concat("Kb");
            else
                filesize_ftpDownload=String.valueOf(size/1024).concat("Mb");

            double rate = (((downloaded_file_ftp / 1024) / ((endTime_ftpDownload - startTime_ftpDownload) / 1000)) * 8);
            rate = Math.round( rate * 100.0 ) / 100.0;

            if(rate > 1000)
                ratevalue_ftp_download = String.valueOf(rate / 1024).concat(" Mbps");
            else
                ratevalue_ftp_download = String.valueOf(rate).concat(" Kbps");
            Log.d("DownloadManager", "download speed: "+ratevalue_ftp_download);

            alertStatus_ftp_download();
        }

        public void alertStatus_ftp_download()
          {

                AlertDialog.Builder alertDialogBuilderfor_ftp_download = new AlertDialog.Builder(mContext);

                // set title
                alertDialogBuilderfor_ftp_download.setTitle("Ftp Download Speed Status");

                // set dialog message
                alertDialogBuilderfor_ftp_download
                .setMessage("Download Speed : "+ratevalue_ftp_download+",  "+"\n Total File Size  :"+filesize_ftpDownload+"\nTotal time taken :   "+totaltime_ftpDownload)
                    //.setMessage("Download Speed  "+ratevalue_ftp_download)
                    .setCancelable(false)
                    .setPositiveButton("Ok",new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int id) {
                            // if this button is clicked, close
                            // current activity
                            dialog.cancel();
                        }
                      })
                    .setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int id) {
                            // if this button is clicked, just close
                            // the dialog box and do nothing
                            dialog.cancel();
                        }
                    });

                    // create alert dialog
                    AlertDialog alertDialogftp_download = alertDialogBuilderfor_ftp_download.create();

                    // show it
                    alertDialogftp_download.show();
                }
}

A: After searching hours and hours, i finally built a solution like this.
Create an Uploader class like this UploadToFtp.java
public class UploadToFtp {
        public FTPClient mFTPClient = null;
        String host;
        String username;
        String password;
        CopyStreamAdapter streamListener;
        ProgressDialog pDialog;
        boolean status = false;

        public boolean ftpUpload1(String srcFilePath, String desFileName,

        String desDirectory, String host, String username, String password,
                final ProgressDialog pDialog) {
            this.pDialog = pDialog;

            this.host = host;
            this.username = username;
            this.password = password;
            int port = 21;
            mFTPClient = new FTPClient();

            try {
                mFTPClient.connect(host, port); // connecting to the host
                mFTPClient.login(username, password); // Authenticate using username
                                                        // and password
                mFTPClient.changeWorkingDirectory(desDirectory); // change directory
                System.out.println("Dest Directory-->" + desDirectory); // to that
                // directory
                // where image
                // will be
                // uploaded
                mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);

                BufferedInputStream buffIn = null;
                final File file = new File(srcFilePath);

                System.out.println("on going file-->" + srcFilePath);
                buffIn = new BufferedInputStream(new FileInputStream(file), 8192);

                mFTPClient.enterLocalPassiveMode();
                streamListener = new CopyStreamAdapter() {

                    @Override
                    public void bytesTransferred(long totalBytesTransferred,
                            int bytesTransferred, long streamSize) {
                        // this method will be called everytime some
                        // bytes are transferred
                        // System.out.println("Stream size" + file.length());
                        // System.out.println("byte transfeedd "
                        // + totalBytesTransferred);

                        int percent = (int) (totalBytesTransferred * 100 / file
                                .length());
                        pDialog.setProgress(percent);

                        if (totalBytesTransferred == file.length()) {
                            System.out.println("100% transfered");

                            removeCopyStreamListener(streamListener);

                        }

                    }

                };
                mFTPClient.setCopyStreamListener(streamListener);

                status = mFTPClient.storeFile(desFileName, buffIn);
                System.out.println("Status Value-->" + status);
                buffIn.close();
                mFTPClient.logout();
                mFTPClient.disconnect();
            } catch (Exception e) {
                e.printStackTrace();
            }

            return status;
        }
    }

Now make an Asynctask in the class where file is actually being fetched or being created, like this
class UploadTask extends AsyncTask<Void, Integer, Void> {
        ProgressDialog pDialog;
        Boolean uploadStat;
        UploadToFtp utp = new UploadToFtp();

        @Override
        protected void onPreExecute() {
            pDialog = new ProgressDialog(UploadActivity.this);
            pDialog.setMessage("Uploading...");
            pDialog.setCancelable(false);
            pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pDialog.show();

            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... params) {
            System.out.println("source url -> " + sourceUrl);
            System.out.println("filename -> " + filename);
            System.out.println("desDirectory -> " + desDirectory);
            uploadStat = new UploadToFtp().ftpUpload1(sourceUrl, filename,
                    desDirectory, app.getHostname(), app.getUsername(),
                    app.getPassword(), pDialog);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (uploadStat) {
                        if (pDialog != null && pDialog.isShowing()) {
                            pDialog.dismiss();
                        }
                        reviewImageView.setImageBitmap(null);
                        mCurrentPhotoPath = "";
                        photo = null;
                        uploadMessage.setVisibility(View.VISIBLE);
                        UploadSuccess.setVisibility(View.VISIBLE);
                    } else {
                        AlertDialog.Builder alertDialog = new AlertDialog.Builder(
                                UploadActivity.this);

                        // Setting Dialog Message
                        alertDialog.setTitle("Error Uploading File");
                        alertDialog
                                .setMessage("Connection lost during upload, please try again!");
                        alertDialog.setCancelable(false);
                        // Setting Icon to Dialog

                        // Setting OK Button
                        alertDialog.setPositiveButton("OK",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,
                                            int id) {
                                        dialog.cancel();
                                    }
                                });
                        alertDialog.show();
                    }
                }
            });
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            if (pDialog != null && pDialog.isShowing()) {
                pDialog.dismiss();
            }
            System.out.println("Result-->" + result);
            super.onPostExecute(result);
        }
    }

Now simply call this Asynctask on button click or any other event you want
new UploadTask().execute();

A: You can do something like this..
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private ProgressDialog mProgressDialog;

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DIALOG_DOWNLOAD_PROGRESS:
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setMessage("waiting 5 minutes..");
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setCancelable(false);
        mProgressDialog.show();
        return mProgressDialog;
    default:
    return null;
    }
}

Then write an async task to update progress..
private class DownloadZipFileTask extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        showDialog(DIALOG_DOWNLOAD_PROGRESS);
    }

    @Override
    protected String doInBackground(String... urls) {
        //Copy you logic to calculate progress and call
        publishProgress("" + progress);
        //Your code Here
    }

    protected void onProgressUpdate(String... progress) {
    mProgressDialog.setProgress(Integer.parseInt(progress[0]));
    }

    @Override
    protected void onPostExecute(String result) {
        dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
    }
}

This is the Procedure to use Progress Dialog update with the AsyncTask, write your code in doInBackground(String...)