How do You Internalize a Song Progression While Soloing?

Question: Here's my problem. I hear a song and I can immediately hear a solo in my head, even anticipating chord changes. It's beautiful.
Everything goes to sh*t when I actually start soloing. The song progression/movement in my head disappears. I believe this is because I'm so focused on soloing over the chords and phrasing that I lose sense of the song itself.
This is what I believe to be the problem anyways...
What do you guys suggest so that I can keep the song movement in my head as I solo? This will allow me to hit chord tones right as they go by and create meaningful phrases.
NOTE
Notice I'm NOT asking "how can I play what's in my head" and rather, "how can I keep track of the song movement while I solo over it.
Answer: EDIT: Since I misinterpreted the question, which is about memorizing the changes/structure of the song:
You can still use some of those techniques below for building a mental map of the tune but just apply them to the chords. Figure the changes out by ear. Write them down. (Obligatorily adding another Adam Neely video on this as well :) Sing the arpeggios of the changes in order. Feel how they move into one another. What does the song "feel" or "smell" like? Feel out the "contours" of the changes. Are some sections static or do they have angular movement? Construct a kind of "painting" in your head so you're moving through a kind of "landscape" as opposed to just "Chord 1, Chord 2, Chord 3..." Another thing that will help is just outright memorizing a lot of tunes as you will start to build an internal repertoire of "what to expect next" as far as chords go. You admit you focus too much on your solo and not on the song; start focusing on the song and its structure instead. If the song has a melody, try to keep singing the melody in your head to keep track of where you are and it will also feed your solo as well. There's some jazz lore about the saxophonist Ben Webster when, in the middle of a solo, he just stopped playing. Someone asked him after, "What happened?" He replied, "I forgot the words to the song." He was singing the words along in his head while he was playing. So, "The song should structure your solo, not vice-versa" is a good rule of thumb. I know it's not a "magic bullet" for memorization but whatever kind of mental tool you can find will help you out.
Original answer:
This is actually something I struggle with as well. Developing the connection between your internal ear and your fingers is something very important. The always-wonderful Adam Neely has a video about this exact topic. Here's a few ways to help develop those connections:

Transcribe (learn by ear) solos or bits of solos you like. Learn to sing the bit first, just as Adam points out in the video, because if you can sing it properly, that means you're hearing it properly. Then learn to play it on your instrument one note at a time. This can be frustrating at first so start with bits and pieces and work your way up to whole solos (if you feel like it). And of course feel free to notate them afterwards so you can see how they're structured and understand how they might work!
Sing with your playing. This is actually good advice no matter what with improvisation because it keeps you "honest" about it. (Obviously horns can't "sing" with their playing per se, but they are still breathing with their playing which helps them form phrases, etc).
One exercise that I've heard tossed around (I believe it's out of Hal Crook's book) is to record yourself playing random chords on a given day. Then, the next day after you've forgotten what you played, attempt to improvise over the random chords with just your ear. You don't need to shred, you just need to be able to hear what notes you're improvising work or don't work.
Arpeggiate the chord changes to a song with your voice. Yes, it's tough, but you'll really start to hear the chord tones pop out at you. You can play the root note of the chord to help at first. Especially on a chord like G7b9, when you sing that b9 against the root, you will REALLY hear it, and not only that, you'll notice what it feels like as well. Singing tensions above the chords as well (i.e., 9, 11, 13, or even altered tensions like b13s and #9s) will help lock those in as well.

Just a few tips, not so much a definitive answer. In my experience, transcription and singing arpeggios/extensions are very powerful exercises. Plus, transcription means that you're always absorbing language to use, not just figuring out what note goes where.
Comment: Thank you for the reply. However, I think your points deal more with outputting what's in my head rather than keeping track of chord changes; which is my problem.
Comment: Attempted to fix it. Thanks for the clarification :)
Answer: IMO the best way to do this is to spend some time doing (or finding and studying) a technical analysis of the progression - understand how it works theoretically and make into an abstraction: Simple examples:

This tune is a I-IV-V blues in G.
This tune is a sequence of II-V-I's that move through every flat key and then
a turnaround back to F.
This tune based on Rhythm Changes in Bb.

By learning a piece's algorithm - an abstraction of the specifics - you no longer have to concern yourself with the details of each chord: You know the formula - you just have to follow that. By doing so, you will be able to quickly learn even fairly complex pieces and remember them, because you aren't getting bogged down in specifics.
Another way of saying that: You need to understand the music you have to play, not just play it by rote.
This is a tried and true method in any discipline that requires one to have large quantities of complex material ready for use at any time: Generalization and abstraction are the key to acquiring and maintaining large stores of information in your mind.

Another way (if it's possible in your situation) is to make yourself a cheat-sheet: a very concise chart that you keep in front of you somehow -
maybe even taped to your wrist or your instrument somewhere that you can see it - for the parts that you have to play and have difficulty with, and look a little ahead at your cheat-sheet when you're coming to the tough parts. Of course initially you're not keeping track in your head that way, but by doing so you should soon have the changes imprinted in your brain.
This is quicker and easier method than the first one, but is less effective and beneficial in the long run. Once you learn how to analyze and abstract a tune, it's a skill that will move you ahead no matter what sort of music or musical endeavor you're involved with.
Answer: It seems from what you say that you're only approaching a song from the soloing perspective. On guitar it's quite easy to separate chords and solos. In fact, it's what most of us mere mortals do!
However, there needs to be an absolute knowledge of the chord structure before an effective solo will appear. It's all very well widdling in pent minor - we've all done it - but if you have played the chord sequence through enough - learned it if you like - then as the song works its way through, there'll be a mental map of where it's going, with waypoints and landmarks which you'll recognise. Often the start points for another phrase. These are the helping hands while you formulate that brilliant solo whilst listening to the piece, which evaporate when you start your actual solo. I guess there's no bones to hang the flesh on, if that makes sense.
When playing suchlike on piano, there's often the left hand comping, or putting in the occasional chord, which helps keep track. A lot of jazz guitarists do the same with the odd chord now and again (not too odd, please!). But it all helps to 'keep on track'. Of course, every time you play a chord, that gives you at least a few actual start point notes - those contained within the chord itself.
Answer: I'm not sure it's possible (for everyone) to keep track of chords in their head while playing.  This is multitasking.  So, I'd ask (1) are you playing with others so you can hear the chords, (2) or are playing something from memory?
If you are trying to train yourself to hear a line (or more) while you play a line one thing that may help is singing one voice while you play.  For example while playing over Rhythm Changes I hum the bass roots to keep myself in check.  This isn't the same as hearing the entire song structure but if you can do this I think the next step is a bit easier.
After years of playing and listening I can recall a complete piece with all voices in my mind while I sit quietly, but like you when I play that goes away.  So, use a backing track.


How to create an EMPTY anchor-only link with l()?

Question: I'm trying to use l() to get something like , for ajax-calling purposes.  https://stackoverflow.com/questions/1698453/drupal-creating-anchor-only-link-with-l is very close to the right thing -- use an option in l() like 'fragment' => 'foo' to produce a link like  -- but I'm trying to get a clean '#'.  Is there any way to do this, or should I just put something in as part of the fragment and not worry about it?
Answer: PHP typecasting pop quiz time! (Full disclosure: I didn't win in our office).
As pointed out already, this is the code in l() that we're concerned with:
if (isset($options['fragment']) && $options['fragment'] !== '') {
  $options['fragment'] = '#' . $options['fragment'];
}

So here's the question: What value casts to an empty string but passes the following?
(isset($var) && $var !== '')

The answer is: FALSE!
So, we could try this:
l(t('My link'), NULL, array('fragment' => FALSE));

Which gives us:
My link

Thankfully we can strip that leading slash by passing along external => TRUE:
l(t('My link'), NULL, array('external' => TRUE, 'fragment' => FALSE));

Which gives us:
My link

Boom. The things we do to avoid concatenating html strings manually, eh?
Postscript:
I'm not sure I'd actually recommend printing a link like this from php under normal circumstances. Without your javascript, all that link is going to do it jump your user to the top of the page (which, to my slight surprise, is specced behaviour). It should probably point somewhere that works without javascript.
If the link really only makes sense with javascript around (like the controls for a js-only slideshow or something), I think it's better to add the link to the page with javascript. Alternatively, if you really want to put it in your source, make sure it's display:none'd by default. Drupal has the .js class on the html for then showing it when javascript is around.
Answer: If you could not use clean "#" with fragment, I would suggest you to use link.
When adding "javascript:" or "javascript:void(0)" to href attribute, the  tag will do nothing. Then you can bind "onclick" to the link for your ajax purpose.
You can implement this using l() function as below:
     l('link', 'javascript:',  array('external' => TRUE));

Comment: You should never ever use such shenanigans and just use event driven JavaScript! This is 2012 not 2004. Why is such a low quality answer up voted? Popular because it's easy? But it's extremely wrong. :(
Comment: @Serjas, `javascript:` and `javascript:void(0)` are the same. The only difference is "void(0)" :)
Comment: what about `javascript:void(0)`
Comment: I mean will l() convert ()?
Comment: @chx, as you are a drupal core maintainer, I hope you are not abusing not to use the second parameter to the l() function rather than path or fragment. Unfortunately, the function accepts "javascript" as a path :) If it is extremely wrong, why does Drupal accept it. Probably, it will be restricted in the later Drupal versions.
Comment: I agree with chx, this is a terrible solution. Really you should be pointing the link to a page that replaces the AJAX functionality in cases where JavaScript is disabled.
Comment: @Sam152, then, please see my comment on Clive's answer. Any idea? The whole world is using javascript actually, even nice frameworks such as jquery, prototype, etc.
Comment: chx++ (although now I'm afraid of how my response will be criticized...) ;)
Answer: Unfortunately the url() function (which l() calls internally) pretty much nukes any chance of an empty fragment with the following lines:
if (isset($options['fragment']) && $options['fragment'] !== '') {
  $options['fragment'] = '#' . $options['fragment'];
}

It checks to make sure the fragment isn't an empty string, which is what you'd need to pass to get the clean #. I think the easiest solution would be to pick the id of a suitable element somewhere in the page and use that for the fragment instead (or javascript:void as Sithu has mentioned).
However...the most accessible way (and subsequently, in many countries, legal way; think section 508 in the States, the DDA in the UK, etc.) would be to provide the content that's being loaded/adjusted by your link on a separate page, and use the URL for that page as the link's href instead. You would then use javascript to stop the event on the link from actually redirecting the page for those browsers which have it enabled.
That way you have fallback content for users without javascript, you stay legal, and you keep everyone and their dog happy :)
Comment: Great edit about fallback! If we use the ajax URL in the link's href, can the calling page be a renderable HTML if javascript is disabled? I ever had `print drupal_json_output($output)` in my ajax calling page.
Answer: You could't use clean #.
But it's possible to add space symbol after #:
  l('Link title', '# ', array('external' => TRUE));

Answer: I just had the same issue, but none of the solutions were satisfying, so i came up with my own one:
l('link', '', array('fragment' => ' ', 'html' => TRUE, 'external' => TRUE));

This produces a clean #
link

Comment: Close, this produces `link` for me.
Answer: I would use render type html_tag instead because I believe render link receive special attention from Drupal. The downside being there is no short-cut function for it, so we'll have to use a render array:
array (
  '#type' => 'html_tag',
  '#tag' => 'a',
  '#attributes' => array (
    'href' => '#',
  ),
);

Answer: This is basically the same answer I posted here... Setting fragment to a single space will convert to a #, and $current_path is included because otherwise the link will just be set to www.example.com/# instead of www.example.com/current-page#:
$current_path = check_url(drupal_get_path_alias($_GET['q']));
$link = l('link', $current_path, array('fragment' => ' '));

Comment: There is no need to get the path alias because l() will convert to alias for you. It is actually preferable to use a non-aliased path.


multiple cardview layouts in one recyclerview in a fragment

Question: I have figured out how to set up the RecyclerView.Adapter with multiple ViewHolders for what im wanting to do but i cannot figure out how to show multiple CardView layouts in a single Activity or Fragment. The layout of the CardViews always shows the onr for the last set of information retrieved in the Database. Is there a way to have multiple layouts for CardViews in a single Fragment?
Edit: Here is my adapter
public class TimeCardAdapter extends RecyclerView.Adapter {
    private ArrayList<ChecksGetterSetter> checksList = new ArrayList<>();

    private static final int TYPE_CHECKS = 0;
    private static final int TYPE_CHECKINFO = 1;

    public class ViewHolder extends RecyclerView.ViewHolder {
        public ViewHolder(View itemView) {
            super(itemView);
        }
    }

    public class ChecksViewHolder extends ViewHolder {
        @InjectView(R.id.CCtextviewDate) TextView tvcPayPeriod;
        @InjectView(R.id.CCtextviewHoursInfo) TextView tvcHours;
        @InjectView(R.id.CCtextviewOvertimeHours) TextView cOTHours;
        @InjectView(R.id.CCtextviewOvertimeHoursInfo) TextView tvcOTHours;
        @InjectView(R.id.CCtextviewPayInfo) TextView tvcRate;
        @InjectView(R.id.CCtextviewOvertimePay) TextView cOTRate;
        @InjectView(R.id.CCtextviewOvertimePayInfo) TextView tvcOTRate;
        @InjectView(R.id.CCtextviewGrossPayInfo) TextView tvcGrossPay;
        @InjectView(R.id.CCtextviewAfterTaxInfo) TextView tvcAfterTax;

        public ChecksViewHolder(View itemView) {
            super(itemView);
            ButterKnife.inject(this, itemView);
        }
    }

    public class CheckInfoViewHolder extends ViewHolder {
        @InjectView(R.id.CCItextviewSocialSecurityInfo) TextView tvSocialSecurity;
        @InjectView(R.id.CCItextviewMedicareInfo) TextView tvMedicare;
        @InjectView(R.id.CCItextviewFederalIncomeTaxInfo) TextView tvFederalIncomeTax;
        @InjectView(R.id.CCItextviewAllowancesInfo) TextView tvAllowances;
        @InjectView(R.id.CCItextviewDeductions) TextView deductions;
        @InjectView(R.id.CCItextviewDeductionsInfo) TextView tvDeductions;

        public CheckInfoViewHolder(View itemView) {
            super(itemView);
            ButterKnife.inject(this, itemView);
        }
    }

    @Override
    public int getItemViewType(int position) {
        int viewType;
        if(checksList.get(position).getPeriodStart() != null){
            viewType = TYPE_CHECKS;
        } else {
            viewType = TYPE_CHECKINFO;
        }
        return viewType;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        LayoutInflater mInflater = LayoutInflater.from(viewGroup.getContext());
        switch (viewType) {
            case TYPE_CHECKS:
                ViewGroup vgChecks = (ViewGroup) mInflater.inflate(R.layout.cardview_checks, viewGroup, false);
                return new ChecksViewHolder(vgChecks);
            case TYPE_CHECKINFO:
                ViewGroup vgCheckInfo = (ViewGroup) mInflater.inflate(R.layout.cardview_check_info, viewGroup, false);
                return new CheckInfoViewHolder(vgCheckInfo);
            default:
                ViewGroup vgTimeCard1 = (ViewGroup) mInflater.inflate(R.layout.cardview_checks, viewGroup, false);
                return new ChecksViewHolder(vgTimeCard1);
        }
    }

    @Override
    public void onBindViewHolder(ViewHolder viewHolder, int position) {
        switch (viewHolder.getItemViewType()) {

            case TYPE_CHECKS:
                ChecksViewHolder holder = (ChecksViewHolder) viewHolder;
                ChecksGetterSetter pos = checksList.get(position);

                if (pos.getPeriodEnd().equals("") || pos.getPeriodEnd() == null) {
                    holder.tvcPayPeriod.setText(pos.getPeriodStart());
                } else {
                    holder.tvcPayPeriod.setText(pos.getPeriodStart() + " - " + pos.getPeriodEnd());
                }
                holder.tvcHours.setText(pos.getHours());
                if (!pos.getOtHours().equals("0.0")) {
                    holder.tvcOTHours.setText(pos.getOtHours());
                } else {
                    holder.cOTHours.setVisibility(View.GONE);
                    holder.tvcOTHours.setVisibility(View.GONE);
                }
                holder.tvcRate.setText(pos.getRate());
                if (!pos.getOtRate().equals("$0.00")) {
                    holder.tvcOTRate.setText(pos.getOtRate());
                } else {
                    holder.cOTRate.setVisibility(View.GONE);
                    holder.tvcOTRate.setVisibility(View.GONE);
                }
                holder.tvcGrossPay.setText(pos.getGrossPay());
                holder.tvcAfterTax.setText(pos.getAfterTax());
                break;

            case TYPE_CHECKINFO:
                CheckInfoViewHolder infoHolder = (CheckInfoViewHolder) viewHolder;
                ChecksGetterSetter posi = checksList.get(position);

                infoHolder.tvSocialSecurity.setText(posi.getSocialSecurity());
                infoHolder.tvMedicare.setText(posi.getMedicare());
                infoHolder.tvFederalIncomeTax.setText(posi.getFederalIncomeTax());
                infoHolder.tvAllowances.setText(posi.getAllowances());
                if (!posi.getDeductions().equals("$0.00")) {
                    infoHolder.tvDeductions.setText(posi.getDeductions());
                } else {
                    infoHolder.deductions.setVisibility(View.GONE);
                    infoHolder.tvDeductions.setVisibility(View.GONE);
                }
                break;
        }
    }

    @Override
    public int getItemCount() {
        return checksList.size();
    }

    public ChecksGetterSetter getItem(int position){
        return checksList.get(position);
    }

    public void addItem(ChecksGetterSetter check) {
        checksList.add(check);
        notifyItemInserted(checksList.size() - 1);
    }

    public void deleteItem(int index){
        checksList.remove(index);
        notifyItemRemoved(index);
    }

    public TimeCardAdapter(List<ChecksGetterSetter> check) {
        if(check == null){
            throw new IllegalArgumentException("check must not be null");
        }
        this.checksList = new ArrayList<>(check);
    }
}

here is the information i want to populate each of the ViewHolders with
    private void getCheckInfo() {
        if (checkCursor.getCount() != 0) {
            while (checkCursor.moveToNext()) {
                hours = checkCursor.getDouble(checkCursor.getColumnIndex(ChecksDBAdapter.WORKED));
                overtimeHours = checkCursor.getDouble(checkCursor.getColumnIndex(ChecksDBAdapter.OVERTIMEWORKED));
                payrate = checkCursor.getDouble(checkCursor.getColumnIndex(ChecksDBAdapter.PAYRATE));
                overtimePayrate = checkCursor.getDouble(checkCursor.getColumnIndex(ChecksDBAdapter.OVERTIMEPAYRATE));
                beforeTax = checkCursor.getDouble(checkCursor.getColumnIndex(ChecksDBAdapter.BEFORETAXES));
                afterTax = checkCursor.getDouble(checkCursor.getColumnIndex(ChecksDBAdapter.AFTERTAXES));

                check = new ChecksGetterSetter(
                        "", "",
                        String.valueOf(decimalToTime(hours)),
                        String.valueOf(decimalToTime(overtimeHours)),
                        moneyFormat(payrate),
                        moneyFormat(overtimePayrate),
                        moneyFormat(beforeTax),
                        moneyFormat(afterTax)
                );
                adapter.addItem(check);
            }
        }
    }

    private void getAdditionalCheckInfo() {
        if (checkCursor.getCount() != 0) {
            while (checkCursor.moveToNext()) {
                socialSecurity = checkCursor.getDouble(checkCursor.getColumnIndex(ChecksDBAdapter.SOCIALSECURITY));
                medicare = checkCursor.getDouble(checkCursor.getColumnIndex(ChecksDBAdapter.MEDICARE));
                federalIncomeTax = checkCursor.getDouble(checkCursor.getColumnIndex(ChecksDBAdapter.FEDERALTAXES));
                deductions = checkCursor.getDouble(checkCursor.getColumnIndex(ChecksDBAdapter.DEDUCTIONS));
                allowances = checkCursor.getInt(checkCursor.getColumnIndex(ChecksDBAdapter.ALLOWANCES));

                checkInfo = new ChecksGetterSetter(
                        moneyFormat(socialSecurity),
                        moneyFormat(medicare),
                        moneyFormat(federalIncomeTax),
                        moneyFormat(allowances),
                        moneyFormat(deductions)
                );
                adapter.addItem(checkInfo);
            }
        }
    }

after it cycles through getCheckInfo() it will populate for the ViewHolder just fine but after getAdditionalCheckInfo() cycles it replaces the CardViews for the first one with the second one and just shows blank cards above them. what am i doing wrong?
Answer: You can use a unique view holder, you only need put a list of objects and populate in onBindView, see the example:
public class CustomAdapter extends RecyclerView.Adapter<MainSearchAdapter.ViewHolder> {

    private List<Object> data;

    public CustomAdapter(Lis<Object> data) {
        this.data = data;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_layout, parent, false);

        return new ViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Object object = data.get(position);

        holder.textView.setText("bla");
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public TextView textView;

        public ViewHolder(View itemView) {
           super(itemView);
           textView = (TextView) itemView.findViewById(R.id.text_view);
        }
   }


Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFArray objectAtIndex:]: index (14) beyond bounds (14)'

Question: I am new to be iOS developer. I am making an app in which i am getting response from JSON. But when i am click button for show next UITableView.
I have two questions for everyone.
1.)It's will shown empty value before. I must scroll down for show values.
2.)After scroll down debug error are show "Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFArray objectAtIndex:]: index (14) beyond bounds (14)"

Sorry for my bad english. I can speak english a little bit.
We must click button for go to next UITableView.
<code>- (IBAction)btnf10
{
    NSMutableDictionary *content = [NSMutableDictionary dictionary];
    [content setValue:[[AppSetting sharedInstance] token] forKey:@"ewitoken"];
    //[content setValue:gloablOnWherehouse.selectedWhereHouse forKey:@"model_Name"];
    [[EWIConnector connector] requestEWIService:@"special_selected_f10" requestData:content delegate:self];
}
</code>
And requestEWIServiceStart will check String.
<code>    - (void) requestEWIServiceStart:(EWIConnector *)connector{

        NSLog(@"start %@",connector.endpoint);
    }

    - (void) requestEWIServiceFinish:(EWIConnector *)connector responseData:(NSDictionary *)responseData{

        NSLog(@"finish %@",connector.serviceName);
        NSLog(@"response %@",responseData);

        if ([connector.serviceName isEqualToString:@"special_selected_f10"])
        {
            NSLog(@"finish %@",connector.serviceName);
            NSDictionary *content = responseData[@"content"];
            NSString *stAlertMes = [content objectForKey:@"alertMessage"];
            stAlertMes = [self getString:stAlertMes];
            NSLog(@"AlertMSG : %@", stAlertMes);
            if (![stAlertMes isEqualToString:@""]) {
                NSLog(@"ALERT MESSAGE : %@", stAlertMes);
                gloablOnWherehouse.arTableDataSelected = [[NSArray alloc] init];
            }
            else
            {
                NSLog(@"HAS DATA");
                gloablOnWherehouse.arTableDataSelected = [content objectForKey:@"DataList_SPI_DetailCollection"];
                [self.tableViewWhereHoseList reloadData];

                labelStatus.text = @"F11";

            }
        }
       else
    {
        NSLog(@"response %@",responseData);
    }
}
</code>
UITableView 2 for response data.
<code>- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    globlOnDisplayEffect = [GlobalVariable sharedInstance];
    globlOnDisplayEffect.arTableDataSelectedWhereHouse = [[NSArray alloc] init];
    [self.tableViewDetailList reloadData];

}

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return (globlOnDisplayEffect.arTableDataSelected)?[globlOnDisplayEffect.arTableDataSelected count]: 100;
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *simpleTableIdentifier = @"DisplayEffectQtyViewCell";
    DisplayEffectQtyViewCell *cell = [self.tableViewDetailList dequeueReusableCellWithIdentifier:simpleTableIdentifier forIndexPath:indexPath];
    if(cell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"DisplayEffectQtyViewCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];

    } else {
        if (globlOnDisplayEffect.arTableDataSelected) {
            NSMutableArray *myMutbleArray = [[NSMutableArray alloc] init];
            [myMutbleArray addObject:globlOnDisplayEffect.arTableDataSelected];

            if (myMutbleArray) {
                NSDictionary *myDic = [globlOnDisplayEffect.arTableDataSelected objectAtIndex:indexPath.row];
                NSDictionary *cont = [myDic objectForKey:@"DataList_SPI_DetailF10"];
                NSString *f10_cmpt = [self getString:[cont objectForKey:@"f10_cmpt"]];
                NSString *f10_dt = [self getString:[cont objectForKey:@"f10_dt"]];
                NSString *f10_item = [self getString:[cont objectForKey:@"f10_item"]];
                NSString *f10_lot = [self getString:[cont objectForKey:@"f10_lot"]];
                NSString *f10_model = [self getString:[cont objectForKey:@"f10_model"]];
                NSString *f10_of = [self getString:[cont objectForKey:@"f10_of"]];
                NSString *f10_semi = [self getString:[cont objectForKey:@"f10_semi"]];
                NSString *f10_tm = [self getString:[cont objectForKey:@"f10_tm"]];
                NSString *f10_uncmp = [self getString:[cont objectForKey:@"f10_uncmp"]];

                [cell setf10_cmpt:f10_cmpt setf10_dt:f10_dt setf10_item:f10_item setf10_lot:f10_lot setf10_model:f10_model setf10_of:f10_of setf10_semi:f10_semi setf10_tm:f10_tm setf10_uncmp:f10_uncmp];

            }
        }
    }
    return cell;

}
</code>
Comment: Add an exception breakpoint to see where you error happens.
Comment: When i'm exception breakpoint. It's error on
"DisplayEffectQtyViewCell *cell = [self.tableViewDetailList dequeueReusableCellWithIdentifier:simpleTableIdentifier forIndexPath:indexPath];" After i'm scroll down from blank cell to shown value on cell.
Answer: Index Bound of array, it's a common problem. There is no object in 14th position in your array.
Before loading tableview, NSLog all data using a loop in console which you have to show in Cell.
<code>  else
        {
            NSLog(@"HAS DATA");
            gloablOnWherehouse.arTableDataSelected = [content objectForKey:@"DataList_SPI_DetailCollection"];

           // [self.tableViewWhereHoseList reloadData];

            labelStatus.text = @"F11";

        }
</code>
And also check which table view you are loading and get it count. I think , it should be
<code> [globlOnDisplayEffect.arTableDataSelected count]>0 ?[globlOnDisplayEffect.arTableDataSelected count]:100.
</code>
Explain, why you will show 100 cell when [globlOnDisplayEffect.arTableDataSelected count]==0. And what is the data source for else ?
<code>- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

 // NSLog what you return....
return (globlOnDisplayEffect.arTableDataSelected)?[globlOnDisplayEffect.arTableDataSelected count]: 100;
}
</code>
Check you table cell condition also. **
Comment: Oh,sorry for wrong return value(100). I'm will write value for return is 1.
Now you're code can resolve my problem. But i'm have a question.
How can resolve first question. Because i must only scroll down for show data.
Comment: Please, fix it first. Hope second problem will be solved automatically. Your table cell is not getting data for cell, as a result it crashes. If you get solution, please, upvote and accept my answer. @รัฐพงศ์ ตุรงค์เรือง
Comment: I'm fix follow you comment. It's work (It's not error from array). But UITable can't response data until scroll down. Please help me.
Comment: in tablecell, if (globlOnDisplayEffect.arTableDataSelected) is always true man ! try to change condition. Print the cell object before going its inside
Comment: Can you show me an example? Because i'm new developer. I have a little experience.
Comment: NP. Think an example of table view simply. First get all value in array, suppose you get 10 data , so load 10 row table in view without data, and  try to NSLog the each value in cellforindex method you need.
Comment: Yes, My condition is always true. But i don't know to add anything on the new conditions for Print the cell object before going its inside.


App working in emulator but crashes on the phone

Question: Succesfully made an app but gives me errors when i run it on the phone
works fine on the emulator which is present in android studio
Main activity:
private static final String TWITTER_KEY = "smth";
private static final String TWITTER_SECRET = "smth";
private TwitterLoginButton loginButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET);
    Fabric.with(this, new Twitter(authConfig));
    setContentView(R.layout.activity_main);

    loginButton =(TwitterLoginButton) findViewById(R.id.twitter_login_button);

    loginButton.setCallback(new Callback<TwitterSession>()

                            {
                                @Override
                                public void success(Result<TwitterSession> result) {
                                    TwitterSession session= result.data;
                                    String user=session.getUserName();
                                    Intent tl=new Intent(MainActivity.this, TweetListActivity.class);
                                    Bundle b= new Bundle();
                                    b.putString("username",user);
                                    tl.putExtras(b);
                                    startActivity(tl);
                                }

                            @Override
                            public void failure(TwitterException exception) {
                                Log.d("TwitterKit", "Login with Twitter failure", exception);
                            }
                        }

);
TwitterApiClient twitterApiClient = TwitterCore.getInstance().getApiClient();
StatusesService statusesService = twitterApiClient.getStatusesService();
statusesService.show(524971209851543553L, null, null, null, new Callback<Tweet>() {
    @Override
    public void success(Result<Tweet> result) {

    }

    public void failure(TwitterException exception) {
        //Do something on failure

     }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    loginButton.onActivityResult(requestCode, resultCode, data);
}

TweetList activity:
String user;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.timeline);
    Intent tl=getIntent();
    Bundle b =tl.getExtras();

    if(null != b){
        user = b.getString("username");
    }
    final UserTimeline userTimeline = new UserTimeline.Builder()
            .screenName(user)
            .build();
    final TweetTimelineListAdapter adapter = new TweetTimelineListAdapter.Builder(this)
            .setTimeline(userTimeline)
            .build();
    setListAdapter(adapter);
}

activity main:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.rohil.aurus.MainActivity">

    <com.twitter.sdk.android.core.identity.TwitterLoginButton
        android:id="@+id/twitter_login_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"/>

</LinearLayout>

tweet_list.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView android:id="@id/android:empty"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_horizontal|center_vertical"
        android:text="empty"/>

    <ListView android:id="@id/android:list"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:drawSelectorOnTop="false"/>
</LinearLayout>

works fine on the emulator but crashes on the phone
Galaxy S4- 1920x1080p
Android 5.1.1
made the app for minimum sdk 21
Logcat:
 D/AndroidRuntime(29639): Shutting down VM
--------- beginning of crash
E/AndroidRuntime(29639): FATAL EXCEPTION: main
E/AndroidRuntime(29639): Process: com.rohil.aurus, PID: 29639
E/AndroidRuntime(29639): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.rohil.aurus/com.rohil.aurus.MainActivity}: java.lang.IllegalStateException: Must have valid session. Did you authenticate with Twitter?
E/AndroidRuntime(29639):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2358)
E/AndroidRuntime(29639):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2420)
E/AndroidRuntime(29639):    at android.app.ActivityThread.access$900(ActivityThread.java:154)
E/AndroidRuntime(29639):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
E/AndroidRuntime(29639):    at android.os.Handler.dispatchMessage(Handler.java:102)
E/AndroidRuntime(29639):    at android.os.Looper.loop(Looper.java:135)
E/AndroidRuntime(29639):    at android.app.ActivityThread.main(ActivityThread.java:5294)
E/AndroidRuntime(29639):    at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(29639):    at java.lang.reflect.Method.invoke(Method.java:372)
E/AndroidRuntime(29639):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
E/AndroidRuntime(29639):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
E/AndroidRuntime(29639):    at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:115)
E/AndroidRuntime(29639): Caused by: java.lang.IllegalStateException: Must have valid session. Did you authenticate with Twitter?
E/AndroidRuntime(29639):    at com.twitter.sdk.android.core.TwitterCore.getApiClient(TwitterCore.java:259)
E/AndroidRuntime(29639):    at com.rohil.aurus.MainActivity.onCreate(MainActivity.java:62)
E/AndroidRuntime(29639):    at android.app.Activity.performCreate(Activity.java:5990)
E/AndroidRuntime(29639):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
E/AndroidRuntime(29639):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2311)
E/AndroidRuntime(29639):    ... 11 more
W/ActivityManager( 3214):   Force finishing activity 1 com.rohil.aurus/

https://drive.google.com/file/d/0Byu333mD4mcSYi01X2N1Sjg3X1k/view?usp=docslist_api
Comment: `Must have valid session. Did you authenticate with Twitter?` well did you?
Comment: Please post your log cat messages which are generated during running application on the mobile so that anyone can help you.Also post your manifest file.
Comment: First, add please full logcat with error. Second, are  you sure you run it on emulator, maybe you just looked at Layout Editor, which fact is built into android studio - sorry I needed to eask
Comment: I ran full emulator, logged into twitter, and even went to the next activity
Comment: Post your logcat **in the question**. An ephemeral link does not a good question make.
Comment: Added my Logcat in the question, thanks
Answer: The Twitter API requires authentication. With your emulator you probably did this at some point during development. Since the authentication key persists, you probably made changes to surpass this step and now, when you install on a fresh device, the authentication has not occurred and therefore you get this error.
If you check your code, or review Twitter's documentation, you will find where you by-pass this step at this point. Twitter's Oauth docs are here: https://dev.twitter.com/oauth


Moving webservice with http and https

Question: I have implemented services calling with http.
now services layers is moving to https.
At client side do i need to change any thing or
rename all url http to https
Need small clarification on this.
Comment: There is no clarification. You just rename your protocol. You could have easily tried it, before asking on Stackoverflow?
Comment: on server side they installing ssl certificate.  to make data transmission secure. "Https" do i need to any thing on client side in order to send request securely.
Answer: There is nothing special that you need to do. Just change "http://" to "https://" and your connection will be secured by SSL.
You can, optionally, add steps to validate the authenticity of the certificate being used (eg CA validation). But simply adding the "s" will ensure that the traffic is encrypted.
Answer: You should not change http scheme to https on client application. The way is that when your client app comes to your http (80) port your should redirect it to https (443) port by putting Location header in HTTP response.
In next versions of your client app you may have to change your protocol directly to https in order to avoid unnecessary traffic and server requests.

Moving webservice with http and https


WPF window is under top/left placed taskbar in Maximized state

Question: I am working on WPF application and I faced problem that when WindowStyle=Noneand WindowState = WindowState.Maximized the application goes under top or left placed taskbar.
When taskbar is placed bottom or right all works normal.
I know about Left and Top properties of window, but they are ignored in Maximized state.
Also there is Microsoft.Windows.Shell.WindowСhrome that gives ability to drag, double click to maximize and restore, snap and unsnap. (it is need to be added as dll reference)
I want to achieve that my application don't hide or go under taskbar and works correctly with behavior that WindowСhrome provide.
MainWindow.xaml
    <Window x:Class="WpfAppTestFullScreen.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        WindowStyle="None"
        Title="MainWindow" Height="350" Width="525"
        Left="100" Top="100">
    <WindowChrome.WindowChrome>
        <WindowChrome CaptionHeight="{Binding ActualHeight,ElementName=topBarGrid}"/>
    </WindowChrome.WindowChrome>
    <Grid x:Name="mainGrid" Background="Yellow">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="*"></RowDefinition>
        </Grid.RowDefinitions>
        <Grid x:Name="topBarGrid" Grid.Row="0" >
            <Border BorderBrush="Black" BorderThickness="1" >
                <DockPanel x:Name="panelForWindowControls"
                           VerticalAlignment="Stretch"
                           DockPanel.Dock="Right"
                           LastChildFill="False"
                           >
                    <Button Name="buttonExit"
                            Width="43" Height="28"
                            Margin="0" Click="buttonExit_Click"
                            DockPanel.Dock="Right" Content="x"
                            WindowChrome.IsHitTestVisibleInChrome="True"
                     />
                    <Button Name="buttonMax"
                            Width="43" Height="28"
                            Margin="0" Click="buttonMax_Click"
                            DockPanel.Dock="Right" Content="[]"
                            WindowChrome.IsHitTestVisibleInChrome="True"
                            />

                    <Button Name="buttonMin"
                            Width="43" Height="28"
                            Margin="0" Click="buttonMin_Click"
                            DockPanel.Dock="Right" Content="_"
                            WindowChrome.IsHitTestVisibleInChrome="True"
                            />
                </DockPanel>
            </Border>
        </Grid>
        <Grid x:Name="bodyGrid"  Grid.Row="1">
            <Button Content="FullScreen" x:Name="FullScreenButton"
                Height="50" Width="200"
                HorizontalAlignment="Center"  VerticalAlignment="Center"
                Click="FullScreenButton_Click" />
        </Grid>
    </Grid>
</Window>

MainWindow.xaml.cs
    using System.Windows;

namespace WpfAppTestFullScreen
{
    ///
    /// Interaction logic for MainWindow.xaml
    ///
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            MaxHeight = SystemParameters.MaximizedPrimaryScreenHeight;
            MaxWidth = SystemParameters.MaximizedPrimaryScreenWidth;
        }

        private void FullScreenButton_Click(object sender, RoutedEventArgs e)
        {
            if (WindowState == WindowState.Maximized)
            {
                WindowState = WindowState.Normal;
            }
            else
            {
                WindowState = WindowState.Maximized;
            }
        }

        private void buttonMax_Click(object sender, RoutedEventArgs e)
        {
            if (WindowState == WindowState.Maximized)
            {
                WindowState = WindowState.Normal;
            }
            else
            {
                WindowState = WindowState.Maximized;
            }
        }

        private void buttonMin_Click(object sender, RoutedEventArgs e)
        {
            WindowState = (WindowState == WindowState.Minimized) ? WindowState.Normal : WindowState.Minimized;
        }
        private void buttonExit_Click(object sender, RoutedEventArgs e)
        {

        }

    }
}

Here is screenshot of problem:
Comment: @szabolcs-dézsi  I don't think so, because width of the app is right. You can see that there is free space on the right. But position of app is wrong.
Comment: Does setting `MaxWidth` to `SystemParameters.WorkArea.Width` help?
Answer: A better approach would be to use a couple of native methods from the User32.dll
(taken from this blog post)
How it works:

Add a hook for WindowMessages (WindowProc) so you can receive window messages from the system.

Every window has an associated window procedure — a function that processes all messages sent or posted to all windows of the class. All aspects of a window's appearance and behavior depend on the window procedure's response to these messages.

You will get signaled (0x24 = WM_GETMINMAXINFO) that the window size is about to be changed

Sent to a window when the size or position of the window is about to change. An application can use this message to override the window's default maximized size and position, or its default minimum or maximum tracking size.

You get the monitor that the window is currently located on (MonitorFromWindow) and update the bounds.

An application can override the defaults by setting the members of this structure.

The system will take care of the rest.

So, no matter how the Window is resized (drag to top of screen, windows key + arrows, maximize button, etc.) it will stay within the boundary of your workarea.
Native Methods and Types:
(just copy this class into your project)
public static class Native
{

    [DllImport("user32")]
    internal static extern bool GetMonitorInfo(IntPtr hMonitor, MONITORINFO lpmi);

    [DllImport("user32")]
    internal static extern IntPtr MonitorFromWindow(IntPtr handle, int flags);

    public static void WmGetMinMaxInfo(IntPtr hwnd, IntPtr lParam, int minWidth, int minHeight)
    {
        MINMAXINFO mmi = (MINMAXINFO)Marshal.PtrToStructure(lParam, typeof(MINMAXINFO));

        // Adjust the maximized size and position to fit the work area of the correct monitor
        int MONITOR_DEFAULTTONEAREST = 0x00000002;
        IntPtr monitor = Native.MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);

        if (monitor != IntPtr.Zero)
        {

            Native.MONITORINFO monitorInfo = new Native.MONITORINFO();
            Native.GetMonitorInfo(monitor, monitorInfo);
            Native.RECT rcWorkArea = monitorInfo.rcWork;
            Native.RECT rcMonitorArea = monitorInfo.rcMonitor;
            mmi.ptMaxPosition.x = Math.Abs(rcWorkArea.left - rcMonitorArea.left);
            mmi.ptMaxPosition.y = Math.Abs(rcWorkArea.top - rcMonitorArea.top);
            mmi.ptMaxSize.x = Math.Abs(rcWorkArea.right - rcWorkArea.left);
            mmi.ptMaxSize.y = Math.Abs(rcWorkArea.bottom - rcWorkArea.top);
            mmi.ptMinTrackSize.x = minWidth;
            mmi.ptMinTrackSize.y = minHeight;
        }

        Marshal.StructureToPtr(mmi, lParam, true);
    }

    ///
    /// POINT aka POINTAPI
    ///
    [StructLayout(LayoutKind.Sequential)]
    public struct POINT
    {
        ///
        /// x coordinate of point.
        ///
        public int x;
        ///
        /// y coordinate of point.
        ///
        public int y;

        ///
        /// Construct a point of coordinates (x,y).
        ///
        public POINT(int x, int y)
        {
            this.x = x;
            this.y = y;
        }
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct MINMAXINFO
    {
        public POINT ptReserved;
        public POINT ptMaxSize;
        public POINT ptMaxPosition;
        public POINT ptMinTrackSize;
        public POINT ptMaxTrackSize;
    };

    ///
    ///
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
    public class MONITORINFO
    {
        ///
        ///
        public int cbSize = Marshal.SizeOf(typeof(MONITORINFO));

        ///
        ///
        public RECT rcMonitor = new RECT();

        ///
        ///
        public RECT rcWork = new RECT();

        ///
        ///
        public int dwFlags = 0;
    }

    ///  Win32
    [StructLayout(LayoutKind.Sequential, Pack = 0)]
    public struct RECT
    {
        ///  Win32
        public int left;
        ///  Win32
        public int top;
        ///  Win32
        public int right;
        ///  Win32
        public int bottom;

        ///  Win32
        public static readonly RECT Empty = new RECT();

        ///  Win32
        public int Width
        {
            get { return Math.Abs(right - left); }  // Abs needed for BIDI OS
        }
        ///  Win32
        public int Height
        {
            get { return bottom - top; }
        }

        ///  Win32
        public RECT(int left, int top, int right, int bottom)
        {
            this.left = left;
            this.top = top;
            this.right = right;
            this.bottom = bottom;
        }

        ///  Win32
        public RECT(RECT rcSrc)
        {
            this.left = rcSrc.left;
            this.top = rcSrc.top;
            this.right = rcSrc.right;
            this.bottom = rcSrc.bottom;
        }

        ///  Win32
        public bool IsEmpty
        {
            get
            {
                // BUGBUG : On Bidi OS (hebrew arabic) left > right
                return left >= right || top >= bottom;
            }
        }
        ///  Return a user friendly representation of this struct
        public override string ToString()
        {
            if (this == RECT.Empty) { return "RECT {Empty}"; }
            return "RECT { left : " + left + " / top : " + top + " / right : " + right + " / bottom : " + bottom + " }";
        }

        ///  Determine if 2 RECT are equal (deep compare)
        public override bool Equals(object obj)
        {
            if (!(obj is Rect)) { return false; }
            return (this == (RECT)obj);
        }

        /// Return the HashCode for this struct (not garanteed to be unique)
        public override int GetHashCode()
        {
            return left.GetHashCode() + top.GetHashCode() + right.GetHashCode() + bottom.GetHashCode();
        }

        ///  Determine if 2 RECT are equal (deep compare)
        public static bool operator ==(RECT rect1, RECT rect2)
        {
            return (rect1.left == rect2.left && rect1.top == rect2.top && rect1.right == rect2.right && rect1.bottom == rect2.bottom);
        }

        ///  Determine if 2 RECT are different(deep compare)
        public static bool operator !=(RECT rect1, RECT rect2)
        {
            return !(rect1 == rect2);
        }
    }
}

Your Window:
public partial class MainWindow : Window
{
    public MainWindow()
    {
        SourceInitialized += Window_SourceInitialized;

        InitializeComponent();
    }

    void Window_SourceInitialized(object sender, EventArgs e)
    {
        IntPtr handle = new WindowInteropHelper(this).Handle;
        HwndSource.FromHwnd(handle)?.AddHook(WindowProc);
    }

    private IntPtr WindowProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    {
        switch (msg)
        {
            case 0x0024:
                Native.WmGetMinMaxInfo(hwnd, lParam, (int)MinWidth, (int)MinHeight);
                handled = true;
                break;
        }

        return (IntPtr)0;
    }

    private void FullScreenButton_Click(object sender, RoutedEventArgs e)
    {
        WindowState = WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized;
    }

    private void buttonMax_Click(object sender, RoutedEventArgs e)
    {
        WindowState = WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized;
    }

    private void buttonMin_Click(object sender, RoutedEventArgs e)
    {
        WindowState = WindowState == WindowState.Minimized ? WindowState.Normal : WindowState.Minimized;
    }

    private void buttonExit_Click(object sender, RoutedEventArgs e)
    {
        Close();
    }
}

Comment: Left and Top position aren't count when `WindowState = WindowState.Maximized`
Comment: @vasa911 That's what I meant by *"you might have to do a bit of manual work to get this working"*. Borderless Windows completely ignore the actual Workarea (like the option Fullscreen Borderless Window you get in some games). You can't rely on WindowState.Maximized when working with a Borderless Window.
Comment: @vasa911 There is a solution with a bit of PInvoking if you don't mind calling a bit of native code - interested?
Comment: I'm totally interested. And Actually that PInvoking code do all that I need. Thank you, you saved me.
Comment: Glad I could help, if that answers you question please accept it by clicking the checkmark next to the score indicator at the top-left of my answer :)
Comment: One thing I want to mention, that with code from above the `MinWidth` and `MinHeight` properties of Window are ignored. It is need to set them in ` WmGetMinMaxInfo()` . Something like that                 `mmi.ptMinTrackSize.x = minWidth;`
`mmi.ptMinTrackSize.y = minHeight;`
Comment: Good catch, yes if your app needs a minimum size you need to set it there too, I'll update that in my example for future reference.
Comment: I have also faced this issue. Could you gave some sample code of PInvoking to make left and top position work as well?


Analyzing 7-point items with parametric tests?

Question: I realize this question has been asked in various permutations (and I've reviewed the posts), but I can't find a good answer.
I have DVs that are 7-point Likert ITEMS. The items were presented horizontally with equal spacing 1 2 3...7 with verbal anchors corresponding to the bottom (1) and top (7) ends (disagree strongly to agree strongly).
Most of the analyses I want to do are repeated-measures type -- so I want to determine whether the degree of agreement with one item differs from another. So I'm wondering if I use RM ANOVA, or Friedman's, or is there another method I should be looking at? But I also want to do some multiple regression type analyses and tests of mediation.
The sample size is large > 2000.
The problem is that I can't find a good article/resource that backs me up one way or another. I know it is discrete data, but the way it is presented and the sample size makes me wonder if I can argue for doing parametric tests? I don't see how tests performed on ranks would be better, since there would be so many ties in this type of data. And then there is the big downside that I can't say one mean is higher than another...
I've read a few articles comparing t-tests to WMW but usually these simulations with very small samples so it is hard to know how it applies to my data. It seems that WMW may be marginally better if the data are severely non-normal, but I can't be sure I'm interpreting that correctly.
My 4 main DV's are not terribly out of shape but not perfectly normal...one is negatively skewed (mean 4.75, md 5), another is a bit flat so more approaching uniform.
Any guidance on what direction to take would be much appreciated. Particularly if there is any book or article that I could cite to justify my choice of method.
Thank you!
Comment: So you have 4 likert scales. Are they related? Why did you collect 4?
Answer: Welcome to the site.
With a Likert scale DV that has 7 options, you want some sort of ordinal analysis, you have no guarantee that the distance between 1 and 2 is the same as between 2 and 3 (or any other pair); with repeated measure data you want to account for the dependency in the data.
One method that does both is a nonlinear multilevel model. In SAS see PROC GLIMMIX (probably; might need NLMIXED). In R see nlme or lme4 (I believe both of those have options for ordinal dependent variables).
If you are willing to assume that the Likert scale is actually continuous (I don't generally recommend this, with only 7 points, but it could be OK), you would want a linear multilevel model (same libraries in R, but in SAS see PROC MIXED.  RM ANOVA makes some pretty stringent assumptions, including sphericity (which includes compound symmetry and is unlikely to be met).
Comment: In R the `ordinal` package handles ordinal data well and can do multi-level models. It also comes with nice vignettes and tutorials.
Comment: Thanks for the responses! I have SPSS -- any suggestions on what I could do with it? Also question on the RM ANOVA comment about assumptions -- if I analyze the multivariate results rather than the univariate, would that help the issue?


Duvida com a ide Dbeaver

Question: Estou utilizando o DBeaver com o SGBD oracle.
Queria fazer uma média de tempo de execução para comparar na hora das otimizações, porém estou em duvida, o que significa

<code>"688 row(s) fetched - 3ms (+20ms)"
</code>

com esse 3ms fora dos parênteses e o 20 dentro e formas de otimizar consultas, pois ainda sou novo nisso.
Answer: Essa função foi implementada como uma solução para a issue #1478:
https://github.com/dbeaver/dbeaver/issues/1478
Segundo o código-fonte, a parte fora dos parênteses é o execution time e a de dentro é o fetch time. O execution time é o tempo que o banco de dados leva para identificar os registros que devem ser retornados com base na sua consulta. O fetch time é quanto o banco demorou para entregar os dados.
Logo, se você fizer SELECT * FROM ANO_MODELO o banco não terá quase nenhum trabalho para identificar os registros que devem ser retornados, uma vez que você quer a tabela toda. Então, você teria um menor execution time porém um maior fetch time, pois a quantidade de registros é maior e requer mais tempo para ser buscada.
Abaixo está o trecho de código que detalha a implementação (fonte GitHub):
<code>    if (statistics == null || statistics.isEmpty()) {
        return "";
    }

    long fetchTime = statistics.getFetchTime();
    long totalTime = statistics.getTotalTime();
    if (fetchTime <= 0) {
        return " - " + RuntimeUtils.formatExecutionTime(totalTime);
    } else {
        return " - " + RuntimeUtils.formatExecutionTime(statistics.getExecuteTime()) + " (+" + RuntimeUtils.formatExecutionTime(fetchTime) + ")";
    }
}
</code>

Duvida com a ide Dbeaver


Replace no SQL - Caractere para manter uma parte do texto

Question: Preciso modificar uma parte no texto de uma tabela. Os registros de um email são email@example.com e preciso alterar todos para jf.jus.br. Só que a primeira parte do email não muda (o xxx).
Posso fazer um
update
  TABELA
set
  email = REPLACE (email, '%.jf.gov.br', '%jf.jus.br').

Na verdade não sei qual o caractere coringa para manter íntegra a sigla do usuário (que vem antes da @).
Comment: Olá Josie, qual o seu Banco de Dados (MySQL, SQL Server, Oracle, etc)? Se possível atualize as tags incluindo o banco de dados específico.
Answer: PostgreSQL; MS SQL Server 2012; Oracle 11g; MySQL
CREATE TABLE tabela(email VARCHAR(320));

INSERT INTO tabela VALUES ('firstname.lastname@example.com');
INSERT INTO tabela VALUES ('firstname.lastname@example.com');

UPDATE
tabela
SET
email = replace(email, 'jf.gov.br', 'jf.jus.br');
SELECT email FROM tabela;

SQLFiddle
Note que sequer é necessário o WHERE pois o replace somente irá substituir se encontrar.
Porém se quiser poderá colocar a fim de evitar "pegadinhas" poderá fazer:
UPDATE
tabela
SET
email = replace(email, 'jf.gov.br', 'jf.jus.br');
SELECT email FROM tabela;
WHERE RIGHT(email,9) = 'jf.gov.br';
SELECT email FROM tabela;

O será genérico e provavelmente funcionará na maioria dos bancos de dados. No entanto o Oracle 11g seria um exemplo de exceção pois, no mesmo em vez de RIGHT(email,9) deverá usar substr(email,-9).
Comment: O problema de fazer uma *update* sem o `WHERE`, ainda que seja algo artifical, é de haver uma lista ou usuário do tipo `email@example.com`, com o `WHERE RIGHT` ou `REGEXP $` eliminamos qualquer pegadinha desse tipo.
Comment: @AnthonyAccioly concordo, só que não acredito que haverá um caso desses. E fiz questão de mostrar o `where` para cobrir isto (caso o OP considerar necessário).
Answer: No MySQL uma solução possível seria buscar através de REGEXP por todos os emails terminados em @jf.gov.br.
UPDATE  Tabela
SET     email = REPLACE(email, '@jf.gov.br', '@jf.jus.br')
WHERE   email REGEXP '@jf.gov.br$';

O caractere $ é o marcador de fim da string.
Exemplo funcional no SQL Fiddle.

Fonte: SOen - Updating email addresses in MySQL (regexp?)


Agrupar valor de um array em PHP

Question: Tenho o seguinte array:
Array
(
[0] => stdClass Object
    (
        [anomes] => 201601
        [codreg] => 41
        [nomreg] => PR
        [codcin] => 1
        [nomcin] => OUTROS
        [valven] => 6835.7000
        [qtdven] => 1078.8000
    )

[1] => stdClass Object
    (
        [anomes] => 201601
        [codreg] => 42
        [nomreg] => SC
        [codcin] => 1
        [nomcin] => OUTROS
        [valven] => 3129.0000
        [qtdven] => 366.6200
    )

[2] => stdClass Object
    (
        [anomes] => 201601
        [codreg] => 42
        [nomreg] => SC
        [codcin] => 2
        [nomcin] => PECAS
        [valven] => 346.9100
        [qtdven] => 73.6600
    )

)

e gostaria de agrupá-lo pelo codreg, implementei o seguinte:
$saida    = array();

foreach ($dadf513 as $row) {

    if(!isset($saida[$row->nomreg])) {
        $saida[$row->nomreg] = array(floatval($row->valven));
    } else {
        array_push($saida[$row->nomreg], floatval($row->valven));
    }

    $arrayFinal[$row->nomreg] = [
        'name' => $row->nomreg,
        'data' => $saida[$row->nomreg]
    ];
}
print_r($arrayFinal);

e objetive o resultado:
Array
(
[PR] => Array
    (
        [name] => PR
        [data] => Array
            (
                [0] => 6835.7
            )

    )

[SC] => Array
    (
        [name] => SC
        [data] => Array
            (
                [0] => 3129
                [1] => 346.91
            )

    )

)

Até aqui beleza, minha dúvida é a seguinte, como passar o valor 0 no [data], quando não existir nenhum valor? Para ficar da seguinte forma:
Array
(
[PR] => Array
    (
        [name] => PR
        [data] => Array
            (
                [0] => 6835.7
                [1] => 0
            )

    )

[SC] => Array
    (
        [name] => SC
        [data] => Array
            (
                [0] => 3129
                [1] => 346.91
            )

    )

)
Comment: Não ficou claro qual é a relação do seu agrupamento, me parece que houve mais alterações do que apenas fazer um `map` agrupando pelo código.
Comment: @IsraelMerljak o array inicial é resultado de um select do banco, depois disso fiz o code abaixo
Comment: A pergunta não está muito clara. O que acontece se tiver 3 objetos com `SC` e 1 `PR` ? O que acontece se tiver 3 `SC`  2 `PR` e outro distinto ?
Answer: Tendo uma variável com a array desejada, chamando de $input, você poderia fazer da seguinte forma:
$arr = array();
foreach($input as $value)
  $arr[$value->nomreg][] = isset($value->valven) ? $value->valven : 0;

Dessa forma, seu resultado sairia mais ou menos da seguinte forma:
array(2) {
  ["PR"]=>
  array(1) {
    [0]=>
    int(0)
  }
  ["SC"]=>
  array(2) {
    [0]=>
    float(3129)
    [1]=>
    float(346.91)
  }
}

Para acessar os dados:
foreach($arr as $key => $value) {
  // $key irá retorna a chave/name - por exemplo "PR" e "SC"
  // $value irá retornar os valores
}

A array gerada teria um padrão um pouco diferente do que o mostrado por você, mas seria gerado de forma mais simples e fácil, e ainda permitindo você ter os mesmo dados, com fácil acesso.
Answer: Primeira Opção
Não ficou muito claro o que você deseja, e a transformação dos dados originais para o seu array "filtrado" não me pareceu exatamente o que você deseja pela sua descrição. Creio que o resultado que você procura seja algo assim:
Array (
    [41] => Array ( // Agrupa todos com codreg 41
        [0] => stdClass Object
        (
            [anomes] => 201601
            [codreg] => 41
            [nomreg] => PR
            [codcin] => 1
            [nomcin] => OUTROS
            [valven] => 6835.7000
            [qtdven] => 1078.8000
        )
    )
    [42] => Array ( //agrupa todos com codreg 42
        [0] => stdClass Object
        (
            [anomes] => 201601
            [codreg] => 42
            [nomreg] => SC
            [codcin] => 1
            [nomcin] => OUTROS
            [valven] => 3129.0000
            [qtdven] => 366.6200
        )

        [1] => stdClass Object
        (
            [anomes] => 201601
            [codreg] => 42
            [nomreg] => SC
            [codcin] => 2
            [nomcin] => PECAS
            [valven] => 346.9100
            [qtdven] => 73.6600
        )
    )
)

Para tal você precisaria de uma função assim:
function groupByCodReg($inputArray) {
    $resultMap = [];

    foreach($inputArray as $data) {
        if(!isset($resultMap[$data->codreg])) {
            $resultMap[$data->codreg] = [];
        }

        $resultMap[$data->codreg][] = $data;
    }

    return $resultMap;
}

Segunda Opção
Talvez o que você queira é agregar os valores dos arrays em uma chave comum para utilizar em algum gráfico. Daí faria sentido o que você tentou fazer com os dados.
Dessa forma o resultado esperado seria assim:
array(2) {
    ["PR"]=> array(2) {
        [0]=> float(6835.7)
        [1]=> float(0)
    }
    ["SC"]=> array(2) {
        [0]=> float(3129)
        [1]=> float(346.91)
    }
}

Para tal você poderia utilizar algo tipo:
function aggregateValvenByNomreg($inputArray) {
    $resultMap = [];

    foreach($inputArray as $data) {
        if(!isset($resultMap[$data->nomreg])) {
            $resultMap[$data->nomreg] = [];
        }

        $resultMap[$data->nomreg][] = $data->valven;
    }

    // completa arrays com 0
    $maiorComprimento = getLengthier($resultMap);
    foreach($resultMap as $key => $value) {
        while(count($resultMap[$key]) < $maiorComprimento) {
            $resultMap[$key][] = 0.0;
        }
    }

    return $resultMap;
}

function getLengthier($array) {
    $max = 0;

    foreach($array as $data) {
        $length = count($data);
        if($length > $max) $max = $length;
    }

    return $max;
}

Segue um link do Repl.it com o código funcionando para você verificar.
  >>ExemploAqui<<

Agrupar valor de um array em PHP


Can subClasses listen to superClass dispatched events?

Question: onI've got some issues with listening to events in Flex4 (actionscript3).
In the code below, the event dispatched in method1 class A, isn't detected in method2 class C. I tryed using bubbles=true for the dispatched event but it didn't change anything.
Do you have any suggestoins?
Class A extends EventDispatcher{
    public function method1():void{
        dispatch(new Event("onEvent"));
    }
}

Class B extends A{
    ....
}

Class C extends B{
    public function method2():void{
        addEventListener("onEvent", onEventResult);

        method1();

        function onEventResult(event:Event):void{
            ...
        }
    }
}

Class D{
    function mainMethod():void{
        var c:C = new C();
        c.methode2();
    }
}

Comment: it should works, just fix the compile errors, e.g. listener name
Comment: There are no compiling errors. When I run the application in debug mode with Flash Builder, I arrive to the statement where the event is dispatched and then nothing happens, because I suppose the event isn't caught.
Comment: it works for me (your code) and should works by default, add _trace_ to be sure, may be some problems with debugger
Answer: I believe that it's not enough to say, in class C,: addEventListener("onEvent", onEventResult);
The only place your class A event can 'bubble up' to is the stage. So you must target the stage with your 'addEventListener' method.
Try stage.addEventListener("onEvent", onEventResult);
But of course, from your code, there's no evidence that an instance of any of these classes is actually on a stage. I'm assuming that you're just not showing that.
Comment: None of the classes is on a stage. So I suppose it's not going to work.
Comment: And are any of them instantiated? You have to actually USE the class in order to get its functions to work!


Data padrão para vencimento - PHP

Question: Pesquisei por esta questão aqui no portal e, apesar de constar perguntas parecidas, não achei nada no sentido que preciso. No google também não encontrei nada que auxilie exatamente em meu problema.
Baseando-se na data da primeira parcela, preciso calcular automaticamente a data de vencimento de n parcelas, sendo estas com o dia fixo para todas elas.
Exemplo:
Primeira parcela: 25/09/2016
Ao incrementar 30 dias a esta data, o dia de vencimento para cada mês poderá variar, de acordo com o tamanho do mês. Além disso, pode acontecer o caso de algum mês ser "pulado", como no mês de fevereiro.
Daí então, preciso que ele realize algo no sentido abaixo:
Primeira parcela: 30/01/2016
A segunda parcela deverá ser: 29/2/2016
A terceira parcela deverá ser: 30/03/2016
A quarta parcela deverá ser: 30/04/2016
E assim sucessivamente.
O que vocês me dizem? Podem me auxiliar nessa questão?
Qualquer sugestão é bem vinda.
Abçs
Answer: Seria uma lógica verificando sempre a data gerada é válida:
<code><?php

function parcelas($data, $numero)
{
    $parc = array();
    $parc[] = $data;
    list($dia, $mes, $ano) = explode("/", $data);
    for($i = 1; $i < $numero;$i++)
    {
        $mes++;
        if ((int)$mes == 13)
        {
            $ano++;
            $mes = 1;
        }
        $tira = $dia;
        while (!checkdate($mes, $tira, $ano))
        {
            $tira--;
        }
        $parc[] = sprintf("%02d/%02d/%s", $tira, $mes, $ano);
    }
    return $parc;
}

$data = "29/01/2015";

var_dump(parcelas($data, 13));
</code>
Exemplo
Comment: Olá Virgilio. Era exatamente isso que eu precisava! Muito obrigado.

Data padrão para vencimento - PHP


How to Remove Arrays of Element in Firebase Cloud Firestore using Ionic 4

Question: In My Cloud Firestore database structure looks like this. Now, I'd like to delete index positions based on Index 0, Index 1 like this.
const arrayLikedImagesRef = {imageurl: image, isliked: true};
  const db = firebase.firestore();
  const deleteRef = db.collection('userdata').doc(`${phno}`);
  deleteRef.update({
    likedimages: firebase.firestore.FieldValue.arrayRemove(arrayLikedImagesRef)
  });
});

Answer: As explained here, "bad things can happen when trying to update or delete array elements at specific indexes". This is why the Firestore official documentation indicates that the arrayRemove() function will take elements (strings) as arguments, but not indexes.
As suggested in this answer, if you prefer using indexes then you should get the entire document, get the array, modify it and add it back to the database.
Answer: You can't use FieldValue to remove array items by index.  Instead, you could use a transaction to remove the array items.  Using a transaction ensures you are actually writing back the exact array you expect, and can deal with other writers.
For example (the reference I use here is arbitrary, of course, you would need to provide the correct reference):
db.runTransaction(t => {
  const ref = db.collection('arrayremove').doc('targetdoc');

  return t.get(ref).then(doc => {
    const arraydata = doc.data().likedimages;

    // It is at this point that you need to decide which index
    // to remove -- to ensure you get the right item.
    const removeThisIndex = 2;

    arraydata.splice(removeThisIndex, 1);
    t.update(ref, {likedimages: arraydata});
  });
});

Of course, as noted in the above code, you can only be sure you are about to delete the correct index when you are actually inside the transaction itself -- otherwise the array you fetch might not line up with the array data that you originally selected the index at.  So be careful!

That said, you might be asking what to do given that FieldValue.arrayRemove doesn't support nested arrays (so you can't pass it multiple maps to remove).  In that case, you just want a variant of the above that actually checks values (this example only works with a single value and a fixed object type, but you could easily modify it to be more generic):
const db = firebase.firestore();
const imageToRemove = {isliked: true, imageurl: "url1"};

db.runTransaction(t => {
  const ref = db.collection('arrayremove').doc('byvaluedoc');
  return t.get(ref).then(doc => {
    const arraydata = doc.data().likedimages;
    const outputArray = []
    arraydata.forEach(item => {
      if (!(item.isliked == imageToRemove.isliked &&
            item.imageurl == imageToRemove.imageurl)) {
           outputArray.push(item);
          }
    });
    t.update(ref, {likedimages: outputArray});
  });
});

(I do note that in your code you are using a raw boolean, but the database has the isliked items as strings.  I tested the above code and it appears to work despite that, but it'd be better to be consistent in your use of types).
Comment: Thank You So much you saved my life, From past One week I'm trying to solve this but I can't Thanks for the Help.


Real world experience in scaling and tuning performance

Question: The website I'm working is allegedly going to have a massive hit rate soon after launch. The client is talking about the possibility  of around 2500 hits per second over a day or so.
Ignoring the fact that this hit rate is probably wild client optimism and apart from getting the largest servers possible, what is the best way that Drupal should be configured to support a large hit rate.
I've read Scaling the drupal.org Infrastructure, Drupal performance blog, Best Practices for Scaling Drupal and many other pages, but what I'm looking for is real experience of doing this, what works, what doesn't, and what to expect.
Answer: Markdorison's answer is basically the accepted method of attacking this problem. I'll take that a little further.
When you have Pressflow for D6 or Drupal for D7, Memcached and Varnish all working nicely together you'll need to custom code your VCL file. There are free ones available  that make starting points but you always need to play with them.
To get Varnish to work optimally make sure you start it with -s malloc xG rather than the default of -s file /path/to/file.
Also with Varnish have Varnish cache static items for as long as you can.
If you have more than one web server remove the ETag from the header sent to Varnish in VCL. I also remove Expires and simply rely on Age and max-age in the headers so get browsers back to the site.
Version 1.5 (as of 3rd March 2011) is still the fastest version of Memcached module from Drupal.org. I typically deploy it using a single bin per server to lower tcp traffic for connections to multiple bins at large scale)
Configure the caching in "Performance" to external and set a max age which will send the correct headers to a caching proxy such as Varnish.
If you can't get certain pages to cache properly in Varnish check out blog posts on the web that detail how to inspect the requests. Here is an example post I wrote a while back: What is stopping Varnish and Drupal Pressflow from caching anonymous users page views
You should pick InnoDB (or one of it's other names from other providers like XtraDB) for MySQL and move all tables into it. Then check out this blog post for basic tuning advice http://www.mysqlperformanceblog.com/2007/11/01/innodb-performance-optimization-basics/
Having a large buffer pool is fundamentally important. When load testing the site turn on the slow query log. You probably want to at first capture queries taking longer than 50msec then tune the queries and repetitively reduce the slow log capture time down until you have most queries running using indexes, and executing fairly quickly.
Other basics involve having APC in for PHP. If you go for fast CGI rather than mod_php do spend some time trying to make the APC cache shared across the php instances by configuring a good wrapper script. Also make sure that the APC cache is in a memory mapped file to squeeze every last bit out of PHP.
Comment: For memory mapped apc it depends on the compile flags...http://php.net/manual/en/apc.configuration.php
Comment: "If you go for fast CGI rather than mod_php do spend some time trying to make the APC cache shared across the php instances by configuring a good wrapper script. Also make sure that the APC cache is in a memory mapped file to squeeze every last bit out of PHP." : Ok, how there are done? Thanks
Answer: I would recommend starting with Pressflow (if using Drupal 6), Memcache, Varnish, and some form of Content Distribution Network (CDN) such as Akamai. The end result should be as few of those users as possible actually hitting your origin server.
If you have parts of the page that you are not able to cache for non-anonymous users (things that are specific to that user, "Welcome userX" etc.), you can explore options to populate these pieces of the page such as asynchronous callbacks or edge side includes.
If you have a smaller group of internal users (such as a group of editors) that need to be able to view an uncached version of the site, I would recommend exposing an uncached version of your site at a different URL (protected behind a VPN or equivalent if possible).
Comment: Richard: My pleasure. Let me know if you have any follow-up questions.
Answer:
Server side

Install Varnish for caching pages for anonymous users.
Install a persistent cache system (Memcached, APC, Memcache).
Use a CDN such as Akamai to serve static files (JavaScript, CSS, images).

Code Side

Use Pressflow, it allows Varnish to serve cached page for anonymous users.
Clean Drupal's watchdog table. Every time a watchdog error gets logged, it consumes CPU resources on the web server and database server. It also increases load time significantly.
Implement static and persistent cache strategies until the slow query log comes up clean.
Avoid PHP errors that occur within nested foreach loops at all costs.
Uninstall unused modules.
Turn on caching for Drupal core blocks and Views.

Database

Make sure the tables are properly indexed for faster searching.
Do not store unnecessary records, a 100 node database will be always accessed faster than a 3 million node database.
Answer: I would also listen to this Lullabot podcast about the way they set up the Grammys.com website for a traffic explosion over the course of a week. It was a pretty educational explanation.
http://www.lullabot.com/podcasts/podcast-92-grammycom
Comment: Totally agree with you.
Answer: While it is very difficult to predict patterns, if you have a fair idea of the traffic levels. Load test your solution. There are a host of different options and a lot will not be possible to predict until you have live traffic, but if you load test as much as possible at least you will have a fair degree of confidence that your setup can handle traffic.
All the tuning in the world won't help if you don't test it first.
This is was a presentation at DC SF about how the economist did it.
http://sf2010.drupal.org/conference/sessions/performance-testing-economist-online-using-grinder
Comment: The link to the presentation is genuinely very useful. Thanks
Answer: For high-traffic websites you should use multiple servers and load balancer or use simply CDN. Also it's very important to cache as much as possible to minimise load on the web servers.
Using Content Delivery Network (CDN) helps to spread out the resources over several domains (domain sharding) which reduces load on the web server.
Using CDN helps with distributed caching and remote acceleration, also helps to mitigate DDoS attacks, because of multiple end-points. It helps with security, because cached content is more more difficult to exploit.
Example providers: Fastly, Rackspace, Akamai, Azure, CloudFlare, Amazon, MaxCDN, Verizon.
Here are some more suggestions:

With CDN, use cookieless domains for static components to be cached (like sstatic.net). Since some proxies might refuse to cache the components that are requested with cookies.
Warm your caches after clearing caches (using wget, Cache Warmer, Drush ECL).
Use performance monitoring (e.g. New Relic or Yottaa which have integration for Drupal).
Use monitoring tool for your website (e.g. Nagios).
Install Varnish and Varnish HTTP Accelerator Integration module, then configure it.
Varnish + Authcache: Check this Example VCL for Authcache Varnish config file.
Consider Pound or NGINX in front of Varnish. See: Why Pound is awesome in front of Varnish.
NGINX can work as reverse proxy and load balancer, so it can replace Pound and Varnish.
Consider a commercial version of Varnish or NGINX to utilise features not available in the "community" open source version.
Consider hardware loadbalancer/caching to replace Varnish and Pound (e.g. BIG-IP F5).
Use tools like ab, JMeter for TTFB, load and stress testing on your web application.

So your web architecture from the user point of view can look like:

User (local browser caching).
NGINX or Pound + Varnish (load balancer, reverse proxy as HTTP accelerator).
Apache (web server).
PHP-FPM (PHP FastCGI Process Manager).
MariaDB (database).

For Drupal optimization suggestion, check: How do you improve Drupal performance?
Answer: Enable two extensions :

Zend OPcache
wincache

Your performance will work better.
If you are looking to twig the Zend OPcache and Wincache in Microsoft Azure, at first create a folder name 'ini' under'D:\home\site\'. Also, create 2 files, '.user.ini' and 'settings.ini'
Add following configuration in each file :
.user.ini
[PHP]
post_max_size = 32M
memory_limit = 512M
zend.enable_gc = On
upload_max_filesize = 32M
opcache.enable=1

setting.ini
wincache.ocenabled = 1
wincache.ocachesize = 255

Also, add an App Setting to your Web App with the key PHP_INI_SCAN_DIR and value d:\home\site\ini
After changing PHP_INI_SYSTEM restart your web app. If want to know more about twigging configuration, please check Microsoft documentation.
After above setting, my Drupal (Drupal 8.3) site load within 3 seconds.
Answer: You could also examine redistributing the load over multiple servers with the aide of a DNS based or software/hardware load balancing solution. This would also bake in fault tolerance.
Comment: That's not a good answer as it doesn't address how to achieve this. as mentioned in the OQ it is real world experience of scaling that I'm after.
Comment: If the powers that be decide we can run drupal at work then I will be happy to provide the 5+ page blog post outlining our hardware and config.
Comment: Excellent. It Could be a useful reference. Post it anyway...
Comment: Did you get permission to repost your outline?


substituir a imagem externa incorporada pelo usuário pela nova versão do host local

Question: Bom dia,
Estou utilizando um plugin chamado Image Teleporter, ele pega todas as imagens que o usuario vai enviar em anexo e salva automaticamente na biblioteca do wordpress.
Gostaria de saber como faço para subistituir a imagem que o usuario enviou em anexo, pela que está na biblioteca do wordpress.
O motivo disto é validar a imagem, visto que nem sempre o usuario vai enviar com uma url segura.
Obrigado
Answer: O plugin em questão está descontinuado, sendo assim não funciona mais.
Porém eu utilizo um outro plugin para fazer basicamente a mesma coisa.
https://br.wordpress.org/plugins/import-external-attachments/
Ele salva as imagens de posts e pages na bliblioteca de mídia do WordPress.


What does sup mean?

Question: I found this formula regarding calories burned:

Rate per Pound (Cal/lb-min)=A+BV+CV.sup.2 +KDV.sup.3 where:
V=Running Speed (mph)--limited to a minimum of 3 mph and a maximum of
  14 mph
A=0.0395
B=0.00327
C=0.000455
D=[0.00801(W/154).sup.0.425 ]/W
W=Weight (lbs)
K=0 or 1 (0=Treadmill; 1=Outdoors)

But what do the .sup.2 and .sup.3stand for? What does it mean?
Comment: I expect it is meant to indicate that what follows is an exponent. So `(W/154).sup.0.425` means $(W/154)^{0.425}$; `KDV.sup.3` maans $KDV^3$, etc.
Answer: It means superscript (usually an exponent). For example, the first equation is supposed to read:
$$\text{Rate per pound (Cal/lb-min)} = A + BV + CV^2 + KDV^3$$
In my opinion, nobody really writes like that unless they have no way to insert a superscript, which I suspect is the case.
Comment: Okay, that makes sense. I, as a programmer, would have have gone for `pow` for 'to the power'. Ah well, thanks!
Comment: Presumably, that .sup. notation corresponds to some computer language.  Back from the days when you didn't get a ^ character to use.
Answer: I suppose it means $CV^2$ and $KDV^3$...

What does sup mean?


SBO tables Relationship (AR INVOICE-INCOMING Payment)

Question: am making a query that bring Incoming Payments details  , that include payment means , details of payment means , and then some  UDFS from the related A/R invoice(s) , in addition to some UDF from an object that relate to a UDF in the AR INVOICE ,
now every time am running my query it show no result.
Am sure there is something I missing here or incorrect but so far couldn't find it .
if any one can help me with this i will be thankful
here is  the query :
SELECT T1.[baseAbs] AS INVOICENO, T0.[DocDate],t0.[trsfrdate],t0.[trsfrref], T0.[CardName],T0.[Doctotal],T4.[VoucherNum] ,
T0.[Comments], T1.[DocNum] AS PAYMENTNO, T2.[Phone1],
T0.[CashSum], T0.[CreditSum], T0.[CheckSum], T0.[TrsfrSum],
T3.[DueDate] AS CHECKDATE, T3.[CheckNum] AS CHECKNO, T3.[Details] AS MAYBEBANKNAME
, t5.[U_UnitCode],t5.[U_Type],t7.[WhsName],t7.[city] ,
t8.U_FloorNo
FROM ORCT T0
inner JOIN RCT2 T1 ON T0.[DocEntry]  = T1.[DocNum]
inner JOIN OINV T5 ON T5.[docnum] =T1.[BaseAbs]
INNER JOIN RCT1 T3 ON T0.[DocNum] = T3.[DocNum]
INNER JOIN RCT3 T4 ON T0.[DocNum] = T4.[DocNum]
INNER JOIN OCRD T2 ON T0.[CardCode] = T2.[CardCode]
INNER JOIN INV1 T6 ON T5.[DocEntry] = T6.[DocEntry]
INNER JOIN OWHS T7 ON T6.[WhsCode] = T7.[WhsCode]
INNER JOIN [dbo].[@AUND] T8 ON T5.[U_UnitCode] = T8.[Code]

Comment: It is really difficult to answer as we don't know how the data is...may you can try using outer joins may be inner joins are filtering the data also check the primary key and foreign key relationships
Comment: are you sure the table `RCT2` has the column `baseAbs`?
Comment: @JustDoIt , well i had update the query relationships , and used fields after i had some more understanding of the tables relationships , and it works now  , thx
Answer: the query is now working fine now , the problem was in inner join , it should been replaced to left join ,
here is the fixed one :
select T0.DocNum as 'Payment Number',T0.DocDate 'Payment Date',T0.CardCode,
T0.CardName 'Customer Name',T1.BankCode 'Bankcode',T3.BankName 'Bank Name', T2.Phone1 ,
T0.CreditSum,
T0.CashSum,
T0.TrsfrSum,
t0.CheckSum,
t1.CheckNum as 'Check Number',
t1.DueDate as 'check date',
t6.VoucherNum as 'Voucher Number',
t0.TrsfrRef as 'Transfer No',
t0.TrsfrDate AS 'Transfer Date',
ousr.USER_code as 'user code',
 T5.DocNum, t11.U_P_BuildingName as 'Building Name',
CASE when T5.DocNum is null then 'On Account' else 'Paid For Invoice' END AS 'Payment Status',
CASE when T5.DocStatus = 'O' then 'Open' else 'Closed' END AS ' Invoice Status',
T4.SumApplied as 'Amount Paid on Invoice',T9.U_FloorNo,T5.U_UnitCode,T5.U_Type,
t0.DocTotal as 'Payment Total',t5.DocTotal as'Invoice Total' , t8.City,
t0.Comments as'Remarks'
from ORCT T0
left join rct1 T1 on T0.DocNum=T1.DocNum
left join ocrd T2 on T2.CardCode=T0.CardCode
left outer join ODSC T3 on T3.BankCode=T0.BankCode
left join RCT2 T4 on T0.DocNum = T4.DocNum
left join RCT3 T6 on T0.DocNum = T6.DocNum
left join OINV T5 on T4.DocEntry = T5.DocEntry and T5.ObjType = T4.InvType
left join oitm t11 on t5.u_unitcode = t11.ItemCode
LEFT JOIN OWHS T8 ON T11.U_P_BuildingNum  = T8.WhsCode
LEFT JOIN [dbo].[@AUND] T9 ON T5.[U_UnitCode] = T9.[Code]
 INNER JOIN  OSLP T10  ON T5.[SlpCode] = T10.[SlpCode]
inner join ousr on ousr.USERID = t0.usersign
where
T4.InvType <> '14' and T0.[Canceled] = 'N'  and t0.docnum=200001

Answer: I think there's a few issues with your query, starting with the join from ORCT to RCT2.
I've created similar queries in the past, here's one which I know works, maybe you can use it to adjust yours. For one thing, you'll definitely need to adjust a lot of those inner joins to outer joins, as a lot of the relations between Payments and it's parent business objects (like Invoices) are very loose and may not always apply.
Note that the query below is looking specifically for Invoices in the RCT2 table (this is the "lines" section of the Incoming Payment object), hence the J002.InvType = 13 condition.
SELECT *
FROM [ORCT] J001
LEFT OUTER JOIN [RCT2] J002 ON J002.DocNum = J001.DocNum AND J002.InvType = 13
LEFT OUTER JOIN [OINV] J003 ON J003.DocEntry = J002.DocEntry
LEFT OUTER JOIN [OACT] J004 ON J004.AcctCode = J001.CashAcct
LEFT OUTER JOIN [RCT1] J005 ON J005.DocNum = J001.DocNum


How do I remove a system CSS file in a theme?

Question: I am trying to remove Drupal CSS files (such as ajax-progress.module.css) from my custom theme YML. Here is what I tried:
name: Mercante
type: theme
description: Tema para o site Mercante.co
core: 8.x
stylesheets-remove:
  - core/themes/stable/css/system/components/ajax-progress.module.css
libraries-override:
  system/base:
    css:
      theme:
        css/components/ajax-progress.module.css: false

Drupal's documentation about that is scarce at best...
Update: another version that also does not work:
name: Mercante
type: theme
description: Tema para o site Mercante.co
core: 8.x
stylesheets-remove:
  - @stable/css/system/components/ajax-progress.module.css
libraries-override:
  system/base:
    css:
      component:
        /core/themes/stable/css/system/components/ajax-progress.module.css: false
        /core/themes/stable/css/system/components/autocomplete-loading.module.css: false

Comment: Reference link: https://www.drupal.org/node/2642122
Answer: You can try with the unset method that drupal provides for css alter hook. Try the following code in your custom module
function hook_css_alter(&$css) {
unset($css[drupal_get_path('module','system').'/system.theme.css']);}

Comment: But I guess the "correct" way to remove a CSS is through libraries-override isn't it? Even stylesheets-remove didn't work.
Answer: You are correct. This is what I have and it is working:
libraries-override:
  core/normalize:
    css:
      base:
        assets/vendor/normalize-css/normalize.css: false

Comment: I think you have wrong paths. You have to use the paths defined in the library and not absolute paths.
Comment: Do you think there is any difference since I am removing something from system/base?
Answer: Quote from https://www.drupal.org/node/2473869

stylesheets-remove:
  - core/assets/vendor/jquery.ui/themes/base/dialog.css

In cases where a Drupal core asset is being removed (for example, a
  CSS file in jQuery UI) the full file path is needed. In cases where
  the file is part of a library that belongs to a module or theme, a
  token can be used. Note that when using the token it needs to be
  quoted because @ is a reserved indicator in YAML.
stylesheets-remove:
  - '@bartik/css/style.css'

As you are removing a stylesheet from the stable theme you should use the token @stable
Comment: I tried that, also not working.
Answer: The only way I managed to do it:
name: Mercante
type: theme
description: Tema para o site Mercante.co
core: 8.x
base theme: false
libraries-override:
  system/base:
    css:
      component:
        /core/modules/system/css/components/align.module.css: false


Is the solution of a PDE always the convolution of the Green function?

Question: If we are given Poisson's equation in a space:
$$\nabla ^2 u=F$$
The solutions (those who admit Fourier transform) are given by:
$$u(x)=\int_\mathbb{R^n} G(x,y)F(y)dy$$
Where $G$ is the Green function (fundamental solution). In a distributional sense, the solution is:
$$u=G\ast F$$
Where the convolution $\ast$ is defined by:
$$\langle G\ast F,u\rangle=\langle G\otimes F,u ^\sharp\rangle$$
This seems to agree with wath we've seen.
But if instead of the whole space, we restric our equation to a domain $D$. With Dirichlet  boundary conditions: $u\vert_{\partial D}=h$. The solution is:
$$u(x)=\int_D G(x,y)F(y)dV + \int_{\partial D} \frac{\partial G}{\partial n}(x,y) h(y)dS$$
How can this agree with the convolution? The surface integral doesn't seem right (I know the proof of this formula, just that this isn't completely clear).
Furthermore, does this mean that even if we know the Green function and the inhomogeneous term, we can't know the solution since we have to come up with the type of integral we need?
Comment: Well, depending how you interpret things, I'll say the obvious: the without-boundary case allows $\mathbb R^n$ to operate as a _group_, and no boundary terms, either. The "domain" case wrecks the group structure, and loses the no-boundary property. (Most boundary conditions are not stable under translation...) Specifically, different sorts of boundary conditions _must_ give different solution formulas...
Comment: Green's functions depend on boundary conditions.
Comment: @paulgarrett I know, but I expected $G$ to change, not the integral.
Answer: I would say you actually have the boundary terms in $R^N$ case, but it is just disappears because your data function $f$ is compact supported. Moreover, I suggest you work out the convolution solution for the case that $f$ is only integrable and Holder continuos, then you will have a better understanding how the "boundary" of $R^N$ disappears.


I need help computing the following limit using only squeeze theorem and basic limit properties

Question: I was able to compute the limit of the following using l'Hopital's rule, and found it to be $\frac{\pi}{4}$, but apparently there is a way to evaluate the limit using the squeeze theorem, apparently you have the fact that the area of a sector of a circle with radius 1 squeezes between the area of a larger triangle and smaller one for small angles
Here is the limit:
$\displaystyle \lim_{n \rightarrow \infty} \dfrac{\tan\left(\dfrac{\pi}{n}\right)}{n\sin^2\left(\dfrac{2}{n}\right)}$
Answer: An idea:
$$\frac{\tan\frac\pi{n}
}{n\sin^2\frac2n}=\left(\frac{\frac2n}{\sin\frac2n}\right)^2\cdot\frac{\sin\frac\pi n}{\frac\pi n}\cdot\frac1{\cos\frac\pi n}\cdot\frac\pi4$$
And now use that
$$\frac{\sin\left( f(n)\right)}{f(n)}\xrightarrow[n\to\infty]{}1\;\;\text{whenever}\;\;\lim_{n\to\infty}f(n)=0$$
Comment: I typed wrong and cannot delete a stupid comment.
Answer: The inequalities you get from the unit circle are, for $0\leq t<\pi/2$,
$$
\sin t \leq t \leq \tan t.
$$
In particular, as $\tan t=\sin t/\cos t$, we have $\sin t\geq t\cos t$. Now
$$
 \dfrac{\tan\left(\dfrac{\pi}{n}\right)}{n\sin^2\left(\dfrac{2}{n}\right)}\geq\dfrac{\dfrac\pi n}{n\,\dfrac{4}{n^2}}=\frac\pi4.
$$
And
$$
\dfrac{\tan\left(\dfrac{\pi}{n}\right)}{n\sin^2\left(\dfrac{2}{n}\right)}
=\dfrac1{\cos\dfrac\pi n}\,\dfrac{\sin\left(\dfrac{\pi}{n}\right)}{n\sin^2\left(\dfrac{2}{n}\right)}\leq\dfrac1{\cos\dfrac\pi n}\,\dfrac{\dfrac\pi n}{n\,\dfrac4{n^2}\,\cos^2\dfrac2n}=\dfrac\pi4\,\dfrac{1}{\cos\dfrac\pi n\,\cos^2\dfrac2n}\to\dfrac\pi4.
$$