ContentFrame.Navigate works for navigation items but not AutoSuggestBox

Question: I have a UWP app with a NavigationView. I have been referring to this documentation which has working samples for everything except more in depth usage of the AutoSuggestBox. https://learn.microsoft.com/en-us/windows/uwp/controls-and-patterns/navigationview
What I am trying to attempt is to update the ContentFrame of the MainPage NavigationView on a QuerySubmitted, I've attempted to do this with a ContentFrame.Navigate, however, this just ends up with the ContentFrame going completely blank. I am very confused as there is not much out there about AutoSuggestBox to go by that's relevant.
My current code looks like this:
private async void AutoSuggestBox_QuerySubmittedAsync(AutoSuggestBox sender, AutoSuggestBoxQuerySubmittedEventArgs args)
{
    searchResultsClass.searchQuery = suggestBox.Text;
    Debug.WriteLine(searchResultsClass.searchQuery);
    await searchResultsClass.SearchAsync();
    this.ContentFrame.Navigate(typeof(SearchResults));
}

SearchResults.xaml, which is identical to my other working views:
<Page
    x:Class="TestApp.Views.SearchResults"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:TestApp.Views"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <GridViewHeaderItem Content="Search results for ''" FontSize="36"/>
    </Grid>
</Page>

Answer: Cannot reproduce your issue on my side. ContentFrame.Navigate can work well with QuerySubmitted event handle. The AutoSuggestBox is as follows in XAML:
<NavigationView.AutoSuggestBox>
    <AutoSuggestBox x:Name="ASB" QueryIcon="Find" QuerySubmitted="ASB_QuerySubmitted"/>
</NavigationView.AutoSuggestBox>

And  the result:

So that please add a break-point on  this.ContentFrame.Navigate(typeof(SearchResults)); code line, and to debug your project to check if it can go through successfully to this step .
If you still have issues please upload a minimal reproduced project.
Updated
For testing you project, the issue comes to be that the SearchResults page lacks of the constructor method. For example:
public SearchResults()
{
    this.InitializeComponent();
}
public async Task SearchAsync()
{
   ...
}

By default, each navigation creates a new instance of the specific Page (or subclass) requested, and disposes the previous page instance.  Details please reference Page class. So that create an instance SearchResults in the MainPage in your code snippet may make no sense and will not have influences with the showed navigated SearchResults page.
If you want to pass the text of the AutoSuggestBox to another page you should Pass information between pages by the navigate method.
Comment: Alright thanks, I added a breakpoint, seems to be going through fine, still didn't do anything. I created a new project to reproduce the issue and slimmed it down to try and get rid of anything that could be doing it, but still, the same problem. Here's a link to said minimal project, I've probably missed something incredibly obvious,
Comment: Sorry, internet took ages to upload the project to Google Drive. [Here's the link.](https://drive.google.com/file/d/1BihjN8PVnJXzxO86YG30BA556nZLWQKx/view?usp=sharing) Continuing the last sentence before I got interrupted by edit times, I've probably missed something incredibly obvious, apologies if I have.
Comment: @Mtngoats by testing comes to the reason, please check the updated answer.


Using Where predicate to filter detail.List with another list

Question: I'm trying to get a set of Master-Detail records on the basis of a list of strings that I need to match with each detail's reference number column for each master. So, for example, I have this as a list of strings:
string[] listToFilterFor = new [] { "2729113", "2732623", "2734483", "2735355", "2752260" };

Anf the DAL function to filter:
public async Task<IQueryable<BILL_INFO>> GetBills(IDictionary<string, object> filterCriteria, string operationGuid)
{
    var callerInfo = Shared.CommonAcross.Helper.GetCaller();
    Logger.Info($"{LayerName} -> {callerInfo.MethodName} -> Started");

    try
    {
        IList<BILL_INFO> intermResult;

        using (var context = new FinanceConnection())
        {
            var result = context.BILL_INFOS
                                .Include(i => i.MASTER_ACCOUNT)
                                .Include(i => i.MASTER_PAY_MODE)
                                .Include(i => i.MASTER_BANK)
                                .Include(i => i.MASTER_CREDIT_CARD_TYPE)
                                .Include(i => i.MASTER_EDIRHAM_CARD_TYPE);

            if (filterCriteria != null && filterCriteria.Any())
            {
                #region Keys

                var billNumberKey = "BillNumber";
                var cashierNumberKey = "AssignedCashiers";
                var payModeIdKey = "PayModeId";
                var depositIdKey = "DepositId";
                var dateFromKey = "DateFrom";
                var dateToKey = "DateTo";
                var accountsKey = "Account";
                var accountGroupsKey = "AccountGroups";
                var referenceNumber = "ReferenceNumber";
                var referenceNumbers = "ReferenceNumbers";

                #endregion

                if (filterCriteria.ContainsKey(billNumberKey) && filterCriteria.TryGetValue(billNumberKey, out var actualFilterBillNumber))
                    result = result.Where(where => where.BILL_NUMBER.Contains(actualFilterBillNumber.ToString()));

                if (filterCriteria.ContainsKey(referenceNumbers) && filterCriteria.TryGetValue(referenceNumbers, out var actualReferenceNumbers))
                {
                    result = result.Include(i => i.BILL_INFO_DETAIL);
                    result = result.Where(where => where.BILL_INFO_DETAIL.Any(p=>p.));
                }

                #region From/To Dates

                DateTime? tempDateFrom = null;
                DateTime? tempDateTo = null;

                if (filterCriteria.ContainsKey(dateFromKey) && filterCriteria.TryGetValue(dateFromKey, out var actualDateFrom))
                {
                    tempDateFrom = ((DateTime?)actualDateFrom)?.Date;
                }

                if (filterCriteria.ContainsKey(dateToKey) && filterCriteria.TryGetValue(dateToKey, out var actualDateTo))
                {
                    tempDateTo = ((DateTime?)actualDateTo)?.Date.AddDays(1).AddMilliseconds(-1);
                }

                if (tempDateFrom.HasValue && tempDateTo.HasValue)
                {
                    result = result.Where(where => where.BILL_DATE != null && where.BILL_DATE >= tempDateFrom && where.BILL_DATE <= tempDateTo);
                }
                else if (tempDateFrom.HasValue && !tempDateTo.HasValue)
                {
                    result = result.Where(where => where.BILL_DATE != null && where.BILL_DATE >= tempDateFrom && where.BILL_DATE <= tempDateFrom);
                }
                else if (!tempDateFrom.HasValue && tempDateTo.HasValue)
                {
                    result = result.Where(where => where.BILL_DATE != null && where.BILL_DATE >= tempDateTo.Value.Date && where.BILL_DATE <= tempDateTo);
                }

                #endregion
            }

            intermResult = await result.OrderByDescending(o => o.BILL_DATE).Take(10000).ToListAsync();
        }

        Logger.Info($"{LayerName} -> {callerInfo.MethodName} -> Returning");
        return intermResult.AsQueryable();
    }
    catch (Exception exp)
    {
        Logger.Error($"{LayerName} -> {callerInfo.MethodName} -> Exception [{exp.Message}]", exp);
        throw;
    }
}

Task:
I need to go through the master records (BILL_INFOS) and look into each master's detail records (BILL_INFO_DETAILS) and try to match AnyOf listToFilterFor against BILL_INFO_DETAIL.REFERENCE_NUMBER
Comment: You have to get BillInfos, whose details match any of listToFilterFor, orget specific details which were matching??
Comment: @Kacper Master record (BillInfos with details that satisfy the cruteria)
Comment: Can you show, What does Bill_Info entity look like? Is Bill_Info_Details another entity?
Answer: If i understand this correct, i apologize if i have not. Could you use an includes statement.
BILL_INFO.where(x => listToFilterFor.Includes(x.BILL_INFO_DETAILS.REFERENCE_NUMBER)
Comment: The `string[] listToFilterFor` does not have an `.Include()` method
Comment: you will need to .toList() the array first
Comment: Did that but the x.BILL_INFO_DETAILS is a collection and I cannot access the property REFERENCE_NUMBER that way
Comment: sorry, i was thinking of javascript it's actually .contains()
Comment: Can you use the selectMany operator?
Answer: I finally sorted this one out as here were composite primary keys involved and a proper tuple was not possible. I found the solution through this question: Cannot create a relation between two tables with three primary keys
I was able to extract a subset.


unrealircd run at boot

Question: I have UnrealIRCD installed on my CentOS server. I'm not too familiar with startup scripts, so I'm wondering if it's possible to have it start when the vps starts up, or if it crashes, as well as start the Anope services, too.
Thanks.
Answer: The correct (official) way to run unreal is via cron (the user you want to run as).
Open the crontab for the user that you wish to run unreal as, eg:
crontab -u user -e

And add this line:
0,10,20,30,40,50 * * * *   /home/user/ircd/Unreal3.2/ircdcron/ircdchk >/dev/null 2>&1

Adjust the path to match where your install of Unreal is.  If you have problems using VI as your default editor, google "linux editor environment variable."   If you have other problems, check the file /home/user/ircd/Unreal3.2/ircdcron/ircdchk - it should have been automatically generated to match the correct directory at install time.
Answer: most simple way to do this would be placing the commands into the /etc/rc.local file.
This will run after the system has been booted.
Please keep in mind that unrealIRC does not run as root, and the rc.local file will be executed as root.
Answer: To make the jump that Goez did not make for you, here is the full command (using su) to run a command as a particular user, and in this instance, running UnrealIRCd as user "ircd":
su -c"/path/to/unreal/unreal start" ircd

unrealircd run at boot


Moving a change to other servers

Question: Is there a way a person can ensure that if he makes a change to a drupal 8 website via the UI (e.g. Adding/modifying a field to a content type, creating/editing a view) that this can be automatically applied to another developers localhost on the git pull or on a staging/production server?
Currently (I have moved from Drupal 7) I am doing this manually which is a pain. I've been told that Features is the way to go from Drupal 8 (and Drupal 7 apparently).
Answer: Features in D8 is the way to sync features across multiple sites. And was the default in D7 to import and export database changes. Which in D8 is solved by Configuration management.
Please read the docs (thoroughly): Managing your site's configuration.
You routinely have to drush cex after you've made changes via the UI. This will export database values into multiple (hundreds/thousands) *.yml files. Then your colleagues will have to drush cim after they pulled the latest *.yml files to get the changes imported into their DB.

For a general overview please see Web development structure on multiple devices.
Answer: In D8, this is done by configuration synchronization (the config_sync module).
The entirety of the configuration (fields, views, formats, block layout, etc) can be exported to YAML files, and imported on another installation (which should be using a copy of the original database).
There are several ways to do this, but since you already mention git, one of the cleaner ways to do it is to run drupal config:export in Drupal Console, and add the resulting directory (which should be in sites/default/config by default, but this path can be changed) to your git repository, and import it with drupal config:import on the other installation after pulling.
(Content, even taxonomy and content blocks, isn't exported unfortunately, which may break your block layout and taxonomy filters in views.)

Moving a change to other servers


Apache vhost always show me the same content on different subdomains

Question: I have two subdomains on my VPS, i have registered the two subdomains in my DNS pointing to the same IP address.
the version installed is Server version: Apache/2.4.7 for Ubuntu 12.04.
I've enabled the sites with the a2ensite command and i have enable the module vhost_alias. restart and reloaded many times
stable.example.com
<VirtualHost *:80>
    ServerName stable.example.com

    DocumentRoot /var/www/stable/web

    <Directory /var/www/stable/web>
            Options Indexes FollowSymLinks Includes
            AllowOverride All
            order allow,deny
            Allow from all
    </Directory>
</VirtualHost>

beta.example.com
<VirtualHost *:80>

    ServerName beta.example.com

    DocumentRoot /var/www/beta/web

    <Directory /var/www/beta/web>
            Options Indexes FollowSymLinks Includes
            AllowOverride All
            order allow,deny
            Allow from all
    </Directory>
</VirtualHost>

my trouble is pointing my browser to any url always i get the same content and to add more confusion when i execute service apache2 reload in the two subdomains i get the content from beta.example.com and when execute service apache2 restart in the two subdomains i get the content of stable.example.com.
I have spent about 5 hours trying to fix this
update
event i try with the VirtualDocumentRoot
<Virtualhost *:80>
    VirtualDocumentRoot "/var/www/%1/web"
    ServerName stable.example.com
    ServerAlias *.example.com
    UseCanonicalName Off
    <Directory "/var/www/*">
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>
</Virtualhost>

with the same behavior explained before this update
update 2
I dont have virtualhost overlap, every vhost has unique name and unique DocumentoRoot, even i have the <VirtualHost _defaut_:80> defined.
i check with apachectl -S:
VirtualHost configuration:
*:80                   is a NameVirtualHost
         default server XXX.XXX.XXX.XXX (/etc/apache2/apache2.conf:220)
         port 80 namevhost XXX.XXX.XXX.XXX (/etc/apache2/apache2.conf:220)
         port 80 namevhost beta.example.com (/etc/apache2/sites-enabled/beta.conf:1)
         port 80 namevhost stable.example.com (/etc/apache2/sites-enabled/stable.conf:1)
ServerRoot: "/etc/apache2"
Main DocumentRoot: "/var/www"
Main ErrorLog: "/var/log/apache2/error.log"
Mutex watchdog-callback: using_defaults
Mutex rewrite-map: using_defaults
Mutex default: dir="/var/lock/apache2" mechanism=fcntl
Mutex mpm-accept: using_defaults
PidFile: "/var/run/apache2/apache2.pid"
Define: DUMP_VHOSTS
Define: DUMP_RUN_CFG
User: name="www-data" id=33
Group: name="www-data" id=33

Comment: maybe you have virtualhost overlap, and think you missing the directive NameVirtualHost *:80 read this http://wiki.apache.org/httpd/TroubleshootingVhosts and you are missing the default virtual host http://httpd.apache.org/docs/2.2/vhosts/examples.html
Comment: the directorive `NameVirtualHost` is deprecated `AH00548: NameVirtualHost has no effect and will be removed in the next release`
Comment: Did you try removing the default server configuration in httpd.conf?
Comment: @edvinas.me yes i removed it
Comment: can you post apache2.conf as the problem is due to something in that config file.
Answer: I had this problem running multiple virtual hosts locally - using :
NameVirtualHost *

Instead of:
NameVirtualHost *:80

In the http-vhosts.conf file fixed it for me.
Comment: You could do without NameVirtualHost as well, if you use
Answer: Update
This is likely caused by apache2.conf
default server XXX.XXX.XXX.XXX (/etc/apache2/apache2.conf:220)

You should post your apache2.conf
httpd.conf (or apache.conf or apache2.conf depending on distribution)
Make sure you have these:
LoadModule vhost_alias_module modules/mod_vhost_alias.so

NameVirtualHost *:80

Make sure there is no other NameVirtualHost directive in main config.
httpd-vhosts.conf
<VirtualHost *:80>
    ServerName stable.mydomain.com
    DocumentRoot /var/www/stable/web
    UseCanonicalName on
    <Directory /var/www/stable/web>
        Options Indexes FollowSymLinks Includes
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

<VirtualHost *:80>

    ServerName beta.mydomain.com

    DocumentRoot /var/www/beta/web
    UseCanonicalName on
    <Directory /var/www/beta/web>
        Options Indexes FollowSymLinks Includes
        AllowOverride All
        order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

Also make sure that you default httpd.conf configuration does not include any defined servers, as vhosts might be overlapping with that.
Comment: i append the `UseCaninicalName on` without success
Comment: I am afraid appending will not fix this as it is clear the problem is caused by some other part of your config. I would guess it is `port 80 namevhost XXX.XXX.XXX.XXX (/etc/apache2/apache2.conf:220)` So please use default apache2.conf with only php setup and my vhost configs.


Predicting the year computers will be able to do 1 exaFLOPS using historical data (time series forcasting using prediction interval)

Question: Put simply, I need to make a prediction interval (or confidence interval?) for the x value when y reaches a certain number given historical data for x versus y.
Long Version: I have data on the speed of computers in FLOPS from the 1950s up until 2012 and need to make a prediction interval for the predicted year we should reach an exaflop (10^18 FLOPS). My problem is that prediction intervals require means and standard errors, and all I have is a single year that my initial regression predicted along with the data used to predict that value. Now, It's clear that that single predicted value is not sufficient to make any significant statistical inferences on. So, what I think I need to do is use my historical data to construct a confidence interval for the year a computer should reach an exaflop so that I can run a hypothesis test, where the Null Hypothesis is that the year we should reach an exaflop is 2020 and the Alternative Hypothesis is that the year we should reach an exaflop is >2020.
The sort of end result I'm thinking of is something along the lines of being able to say "I am 95% Confident that the true year a computer should be able to do an exaflop is between 2020 and 2035", in addition to the statements for the hypothesis test.
My issue now is that what I THINK I need to do is construct many regression lines on the data to get a mean predicted year for the exaflop and the accompanying standard error so that I can do the prediction interval. Is this possible? If so how do I do it?
If there exists a better, easier way to predict the year of an exaflop given my historical data please let me know what it is and how to do it. Help is greatly appreciated.
EDIT: After researching time series forecasting, I've become aware that what I'm trying to do is construct a prediction interval on a time series. I haven't found a reasonable and accepted way to carry this out yet. Help is still needed and appreciated.
Comment: Some of that exists here:  https://docs.google.com/file/d/0B83UyWf1s-CdZnFoS2RiU2lJbEU/edit
Answer: Many years late, but FWIW:
The simple solution here is to construct a linear regression of speed or log(speed) vs time. With this fitted model, you can construct a prediction interval. Here's an example with some made-up numbers:
<code>#Time in years
time <- seq(1970, 2015, 5)

#flops on log base 10 scale
logflops <- c(0.96, 2.02, 3.1, 4.3, 4.97, 6.05, 7.1, 8.01 ,8.96, 9.98)

#construct linear model
lm_logflops <- lm(logflops ~ time)

#define time point at which we want a prediction
newdata <- data.frame(time = 2020)

#generate prediction with prediction interval
predict(lm_logflops, newdata, interval = 'predict')

   fit      lwr      upr
 11.00467 10.70386 11.30547
</code>
This makes some simplifying assumptions that I think are reasonable in this case: the trend is linear (with log-transformed flops), and there is no periodicity. You could construct more complex models if either of those assumptions is violated.


Pseudo field show/hide setting per node

Question: I have created a pseudo field using hook_entity_extra_field_info() and displaying markup using hook_entity_view().
How can I create a checkbox setting in node create form so that I can show / hide this pseudo field per node?
Comment: There was a similar question about a pseudo a field a while ago. You need to store the data of that selection per node, so why not just make a it an actual field? You can easily check that in a template and do stuff based on it.
Comment: I am displaying a url based on current node id in pseudo field markup. If I create an actual field then how to manipulate / override its markup.
Comment: You get the fully created form structure for the field in form alter, you can still customize it there if you want. You could also implement your own widget that extends from the default, for a cleaner, reusable approach But you get a things like storage handling for free if all you need to customize is the default value.
Answer: In hook_ENTITY_TYPE_view which you use to render your pseudo field there already is the $entity available. Which in your case must be a node object. You simply can get any field value from there.
So all you need to do is to add a Drupal default checkbox/boolean field to your content type, from the UI probably, hide it from display, and then output your pseudo field depending on its value, per node.
/**
 * Implements hook_entity_extra_field_info().
 */
function MYMODULE_entity_extra_field_info() {

  $extra['node']['article']['display']['foo_bar'] = [
    'label'       => t('My pseudo field'),
    'description' => t('My pseudo field description.'),
    'weight'      => 0,
    'visible'     => TRUE,
  ];

  return $extra;
}

/**
 * Implements hook_ENTITY_TYPE_view().
 */
function MYMODULE_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {

  if ($entity->bundle() == 'article') {

    // Get the choice.
    $editors_choice = $entity->field_editors_choice->first()->getValue();
    $editors_choice = isset($editors_choice['value']) ? $editors_choice['value'] : FALSE;

    // And fire accordingly.
    if ($display->getComponent('foo_bar') && $editors_choice) {
      $build['foo_bar'] = [
        '#markup' => 'This is my custom content',
      ];
    }
  }
}

Pseudo field show/hide setting per node


Sendmail & IpTable Rules

Question: I need to setup IpTable Rules for a server with nginx, ssh and sendmail.
Now, the problem is, with my rules I can not send emails to other hosts anymore.
Emails to localhost do work, but sending to different servers does not, when the firewall is up.
I tried opening both Incoming and Outgoing Port 25 and DNS lookup ports, but nothing worked.
Any ideas?
Update:
Here are my rules:
#! /bin/sh
# firewall iptable rules

interface="eth0"

# first, deny all
iptables -P INPUT DROP
iptables -P OUTPUT DROP
iptables -P FORWARD DROP

# open loopback device completely
iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT

# open ssh ports
iptables -A INPUT -p tcp -i $interface --dport 22 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT
iptables -A OUTPUT -p tcp -o $interface --sport 22  -m state --state ESTABLISHED,RELATED -j ACCEPT

# open browser ports
iptables -A INPUT -p tcp -i $interface --dport 80 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT
iptables -A OUTPUT -p tcp -o $interface --sport 80  -m state --state ESTABLISHED,RELATED -j ACCEPT

Answer: If you want to allow your Linux box to send emails via port 25, you should allow it by adding a rule like:
$ iptables -A OUTPUT -p tcp --dport 25 -j ACCEPT

Similarly for DNS traffic:
$ iptables -A OUTPUT -p udp --dport 53 -j ACCEPT

If there is no such explicit rules, the traffic will be denied by default as the default policy is set to DROP.
Update:
Don't forget to allow the related/established connections using:
$ iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
$ iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

Answer: Add the following rules to your IPTables:
iptables -A INPUT -p tcp --dport 53 -j ACCEPT
iptables -A INPUT -p udp --dport 53 -j ACCEPT
iptables -A OUTPUT -p tcp --dport 53 -j ACCEPT
iptables -A OUTPUT -p udp --dport 53 -j ACCEPT
iptables -A INPUT -p tcp --dport 25 -j ACCEPT
iptables -A OUTPUT -p tcp --dport 25 -j ACCEPT

Comment: This question already has an accepted answer, to which yours really doesn't add anything useful.

Sendmail & IpTable Rules


Rabbit Mq fails to start

Question: Just installed RabitMq on a brand new CentOs6.6 server ( rabbitMq 3.4.1, erlang says 17 ), and it fails to start.
Starting rabbitmq-server: FAILED - check /var/log/rabbitmq/startup_{log, _err}
rabbitmq-server.

startup log
Stack trace:
[{inet_gethost_native,ensure_started,0,
                     [{file,"inet_gethost_native.erl"},{line,548}]},
{inet_gethost_native,getit,2,
                     [{file,"inet_gethost_native.erl"},{line,487}]},
{inet,gethostbyname_tm_native,4,[{file,"inet.erl"},{line,1094}]},
{inet,gethostbyname,3,[{file,"inet.erl"},{line,459}]},
{erl_epmd,port_please1,3,[{file,"erl_epmd.erl"},{line,81}]},
{rabbit_networking,record_distribution_listener,0,[]},
{rabbit_networking,boot,0,[]},
{rabbit,'-run_step/3-lc$^1/1-1-',2,[]}]

BOOT FAILED
===========

Error description:
{could_not_start,rabbit,
   {bad_return,
       {{rabbit,start,[normal,[]]},
        {'EXIT',
            {rabbit,failure_during_boot,
                {boot_step,networking,
                    {could_not_start_server,inet_gethost_native}}}}}}}

Let me know if you need any other info.  Any help would be appreciated, I think this sever is cursed.  Last time i get a new server around Halloween.
It looks like it running status.  I have a line for my host, there is one with the ip address to, but removing that didn't help, in etc/hosts.
Status of node rabbit@host4 ...
Error: unable to connect to node rabbit@host4: nodedown

DIAGNOSTICS
===========

attempted to contact: [rabbit@host4]

rabbit@host4:
  * connected to epmd (port 4369) on host4
  * epmd reports: node 'rabbit' not running at all
                  no other nodes on host4
  * suggestion: start the node

current node details:
- node name: 'rabbitmqctl-29678@host4'
- home dir: /var/lib/rabbitmq

I have this process running too.  If it helps.
root@host4 [981 19:09:47 ~]# ps aux|grep rabbit
rabbitmq 16068  0.0  0.0  10828   528 ?        S    16:13   0:00 /usr/lib64/erlang/erts-6.2/bin/epmd -daemon

also
    running hostname -f shows me the correct hostname.  For example
  host4.mysite.com

IN reply I ran those commands: rabbit was not running and would not connect as the app_start.
Here is the results of rpm -qa --queryformat '%{NAME}\n' |grep erlang
erlang-mnesia
erlang-otp_mibs
erlang-reltool
erlang-snmp
erlang-erl_docgen
erlang-examples
erlang-erts
erlang-cosEvent
erlang-ic
erlang-debugger
erlang-stdlib
erlang-cosProperty
erlang-jinterface
erlang-typer
erlang-compiler
erlang-asn1
erlang-cosNotification
erlang-cosFileTransfer
erlang-parsetools
erlang-wx
erlang-dialyzer
erlang
erlang-solutions
erlang-hipe
erlang-ssl
erlang-ssh
erlang-percept
erlang-odbc
erlang-webtool
erlang-megaco
erlang-syntax_tools
erlang-public_key
erlang-edoc
erlang-cosTransactions
erlang-erl_interface
erlang-observer
erlang-common_test
erlang-kernel
erlang-runtime_tools
erlang-orber
erlang-eldap
erlang-sasl
erlang-os_mon
erlang-inets
erlang-diameter
erlang-tools
erlang-crypto
erlang-cosTime
erlang-eunit
erlang-test_server
erlang-gs
erlang-ose
erlang-xmerl
erlang-cosEventDomain
erlang-et

I do have ip_tables, so I thought it might be a firewall issue but I can successfully telnet to the host name rabbit is using with 4369 as the port.
When I run nmap -p 5672
Starting Nmap 5.51 ( http://nmap.org ) at 2014-11-03 20:30 CST
Nmap scan report for host4 (127.0.0.1)
Host is up (0.000049s latency).
Other addresses for host4 (not scanned): xxx.xxx.xxx.xxx
rDNS record for 127.0.0.1: localhost.localdomain
PORT     STATE  SERVICE
5672/tcp closed amqp

Nmap done: 1 IP address (1 host up) scanned in 0.06 seconds

What's the best way to remove this thing, when I do yum remove rabbitmq-server and instal an older version say 3.3.5 I get this error message
Crash dump was written to: erl_crash.dump
Failed to create aux thread
Aborted (core dumped)

Comment: Can you resolve hostnames?
Comment: Yes i can ping the hostname etc.
Comment: Show us what `hostname -f` displays.
Comment: P.S. It is always good idea to post RabbitMQ and erlang version you use.
Comment: @zaq178miami - updated
Comment: @ArtisiticPhoenix, try to run `hostname -f`. Does it run successfully?
Comment: @zaq178miami - yes it shows me the correct host.
Comment: Please do the following: /usr/sbin/rabbitmqctl stop_app /etc/init.d/rabbitmq-server restart /usr/sbin/rabbitmqctl status If `rabbitmq-server` is not up, re-run it using `/usr/sbin/rabbitmqctl start_app`. Also, please run this: rpm -qa --queryformat '%{NAME}\n' |grep erlang Please paste the outputs of the `rpm` command and the `rabbitmqctl status` (after the 3 steps listed above). How did you install `erlang` and how did you install `rabbitmq-server`? source / rpm ? Edit #1: Please verify that the server's host name is written correctly in `/etc/hosts` on the line of `127.0.0.1`, also check `/e
Comment: This is true thanks for the help first off.  I'll post the results of the rpm grep deal.  The other commands just told me rabbit is not running and gave same error message.
Comment: Please check Edit #1 in my answer.
Comment: @ltai  -  not setup using ssl yet, basically a fresh install from rpms, we do have ip_tables on, but selinux appears to be disabled ( that's what sestatus says )
Comment: @ItaiGanot should have mentioned the status is identical to the one I originally put.
Comment: The reason why I'm so familiar with this subject is that I installed my first RabbitMQ server about two days ago, I'd like to refer you to my question, read my answer there and if you go through the steps there I'm sure it will work, as I used the same set of commands to install 4 more machine like that,
http://stackoverflow.com/questions/26697628/rabbitmq-unable-to-enable-rabbitmq-priority-queue-plugin-particularly-but-why/26697726?noredirect=1#comment41989984_26697726
Comment: I would try to disable iptables just for the test
Comment: I tried that through WHM last night actually, had no effect.  I've installed rabbit a few times :) but I'm on a loss on this one.  Thanks for all the help.
Answer: For future reference I have solved the issue, with some help from the RabbitMq community which pointed me in this direction, by a simple statement.

This suggests Erlang VM cannot create a thread. Do you have any resource or security restrictions in place?

This was directly in response to 2 items.
 Failed to create aux thread

Not sure why it didn't occur to me before, because I did see this in the erlang dump
 processes: 13064032
 processes_used: 13064032

However I am not sure how the number of erlang processes convert to system process, but regardless I thought it was a bug or programming incompatibility.  It just didn't make a whole lot of sense because the installation went smoothly on my virtual development server.  As well as our old CentOs 5.1 server.  Also as this was a new, sever with > 3x the speed of our old one, I thought hitting resources limits was not an issue.  I just needed someone to say it to make it click in my mind.
Anyway, after some researching I ran this command
#su rabbitmq
bash-4.1$ ulimit -a
=============================
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 128218
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) 131072
open files                      (-n) 4096
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 100
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

The important thing here is this part:
 max user processes              (-u) 100

Checking my development box ( which has a functional RabbitMq installation with the management plugin ) I further saw this.
 Erlang processes   206

So it doesn't really take a genius to figure out that 206 is more then 100  so after some more research I discovered the default value for this setting is typically 1024, and that i can change it in /etc/security/limits.conf  In that file I found
 *               hard    nproc           100

So I just upped that to the 1024 amount for the rabbitmq user
 rabbitmq                 hard    nproc           1024

And it fired right up!  After starting it and checking the status, I see this
 {processes,[{limit,1048576},{used,147}]},

I believe the limit here is system wide? Still not really sure how the erlang process and these other process numbers relate.
So in conclusion 100 process is not enough for erlang to work.  This is a cloud hosted SSAE 16 dedicated webserver, typically the hosting company sets these up for use for resellers, ie. you can farm out parts of the server to host you're clients websites. This is most likely why they set a default limit so low.  We use this type of server because we do a lot of database querying and report writing, and it offers a fair amount of power for what we pay.  So while the hardware meets our needs, the configuration doesn't fit our use case as well.
Hopefully this can help someone in the future.

Rabbit Mq fails to start


Multiple linear regression with very large cost

Question: So, I'm trying to enter the Data Science world but struggling with a very simpel exercise. I'm using a dataset to get personal medical costs from a bunch of personal info. The database look like this:

Right now, this is my code:
<code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

data = pd.read_csv('./data.csv')

sex = {'female': 0, 'male': 1}
smoker = {'no': 0, 'yes': 1}
region = {'southwest': 0, 'southeast': 1, 'northwest': 2, 'northeast': 3}

def filterData(data):
    data['smoker'] = [smoker[item] for item in data['smoker']]
    data['sex'] = [sex[item] for item in data['sex']]
    data['region'] = [region[item] for item in data['region']]
    data['charges'] = [round(item, 2) for item in data['charges']]

    return data

data = filterData(data)

x = data[['age', 'sex', 'bmi', 'children', 'smoker']]
x.insert(0, 'coefficient', np.ones(len(data.index)))
y = data['charges']

theta = np.zeros(len(x.columns))

alpha = 0.00003
iters = 1000

def getMSE(x, y, theta):
    predY = np.sum(x * theta, 1)
    meanSquare = np.power((predY - y), 2)
    MSE = np.sum(meanSquare) / (2 * len(x))

    return MSE

def gradientDescent(x, y, theta, alpha, iters):
    cost = []

    for iteration in range(iters):
        predY = np.sum(x * theta, 1)
        loss = predY - y
        gradient = 0
        for j in range(len(theta)):
            for m in range(len(x)):
                gradient += loss[m] - x[m][j]
            theta[j] -= (alpha/len(x)) * gradient

        cost.append(getMSE(x, y, theta))

    return theta, cost

x = np.array(x)
y = np.array(y)
theta = np.array(theta).T

MSE = getMSE(x, y, theta)
theta, cost = gradientDescent(x, y, theta, alpha, iters)

print(theta)
plt.plot(list(range(iters)), cost, '-r')
plt.show()

</code>
I think that some of the methods are not working properly, because even after the model training, my cost curve looks like this:

I tried to change the iters and learning rate but nothing seems to make it better
Comment: Some of these values for `# charges` are huge, as is the spread. Consider what happens if you normalize your data before running regression on it. It'll make the loss more understandable. The shape of the curve should wind up the same, but the y-axis will certainly be smaller.
Comment: Hm, ok, I understand. But the methods are right?
Comment: Your gradient descent function has problems. Just from skimming it, the first two I noticed are (1) Why is your loss $\hat{y} - y$ instead of $(\hat{y} - y)^2$? (2) You need to reset `gradient` more often, or you update $\theta_2$ based on $\theta_1$, you update $\theta_3$ based on $\theta_1$ and $\theta_2$, etc.
Comment: (1) The loss function in referent to the derivative of each theta term, in this case it's not predY - y? (2) For `gradient`, I should reset every `j` in theta loop?
Answer: The shape of your curve looks correct. The y values in your data are pretty large and you have done no normalization. This would probably work much better if you first center the data by
$$
\frac{x - \mu}{\sigma}
$$
for both the data columns and the labels. After you make predictions, you can then bring the data back to the original scale by storing the normalization values and doing $\hat{y}\sigma_y + \mu_y$


GWT DialogBox Has Gaps In Border For Larger Messages

Question: Working with GWT v2.5.1, I'm creating a DialogBox and filling it using HTML by calling dialog.setHTML(...) with this:

could not start.

These preferences must all be set before I can start

I have no custom CSS.  What appears on the screen is this:

You'll notice that there are big gaps in the left and right borders.  Looking at the CSS for the dialogTopLeft and dialogTopRight classes, they extract the border from images/corner.png and the shown length of the border exactly matches the size of that image.  In other words, the dialog is too big.
I tried removing the "no-repeat" directive on the background CSS attribute (using Chrome Inspector) but that repeats the entire border image, including the rounded corner at the top, and so does not appear contiguous.
I can't be the first person who's tried to put more than a single line into a DialogBox...
What's the trick to making the borders "repeat" and fill in the holes?
Answer: Wrap the HTML in HTMLPanel befor passing it to the DialogBox
DialogBox dialog = new DialogBox();
HTMLPanel panel  = new HTMLPanel("
could not start.

These preferences must all be set before I can start
");
dialog.add(panel);
dialog.center();

Answer: Thanks to @Moh for placing me on the right path.
The proper way to do this is to set only the dialog title using setHTML() and then create the body as a new panel and add it to the dialog.
DialogBox dialog = new DialogBox();
dialog.setHTML("" + title + "");
dialog.add(new HTMLPanel(message));

Adding buttons is left as an exercise for the reader...
Answer: GWT Dialoge box already have pre defined CSS.
you have to override or have to set your own style names using set Methods.
like..
dialogBox.setStyleName("yourcss");

Default css names starts with,
.gwt-DialogBox{}

Comment: I know it can be styled.  I want to know why it's not working out-of-the-box.


rails4 // ActionController::UnknownFormat

Question: Some bots or other external requests cause an ActionController::UnknownFormat error when redirecting
Is there a catch-all method to add somewhere in application_controller to handle those errors ?
A config spec to add a default method in request (if none specified) ?
Below an example of trace :
An ActionController::UnknownFormat occurred in main#index:

  ActionController::UnknownFormat
  app/controllers/main_controller.rb:17:in `index'

-------------------------------
Request:
-------------------------------

  * URL        : http://ownedurl.com/
  * HTTP Method: GET
  * IP address : 82.xxx.xxx.xxx
  * Parameters : {"controller"=>"main", "action"=>"index"}
  * Timestamp  : 2015-06-07 20:54:32 +0200
  * Server : servername
  * Rails root : /var/www/ownedurl.com/releases/208
  * Process: 29726

A get request would obviously work; yet it makes it occurs.
Experiences on this one appreciated
thx a lot
Answer: This will handle a request without format :
rescue_from ActionController::UnknownFormat, with: :raise_not_found
def raise_not_found
    render(text: 'Not Found', status: 404)
end

Answer: You can supply the :format to your routes itself to tell it what are the formats are valid and which are not.
Read some discussions on this and this answer.
Comment: good point. main#index is actually the root of the app. what's the syntax to specify the format in it ?
Comment: @Ben did you check ?/
Comment: I'll check tomorrow. Added `root :to => 'main#index', :defaults => { :format => 'html' }`. Thing is, I don't know how to address a request without format with curl or other similar tool


Parse json response in object c from http get request

Question: i'm trying to parse the response i get from a http get request in object c, i have do this:
    NSString *returnValue = [[NSString alloc] initWithData:oRespondeData encoding:NSUTF8StringEncoding];
    SBJsonParser *jParser = [[SBJsonParser alloc] init];
    NSDictionary *JSONresponse = [jParser objectWithString:returnValue];

then i search for a specific key:
NSArray *jSon1 = [JSONresponse objectForKey:@"links"];

and in the array there is only one element, and if i log it i have this:
NSLog(@"%@",[jSon1 objectAtIndex:0]);

log:
(
"Video.720p.X264-..",
"",
"http://video/dl/Video.720p.X264-.."
)

how i can get the url with http? i have tried everything, i have also tried to trim the string to delete the whitespaces, but seems that it's not a nsstring because i receive
[__NSArrayM stringByTrimmingCharactersInSet:]: unrecognized selector sent to instance

how i can do?
Comment: What versions of iOS are you supporting?
Comment: i'm doing it in Mac OS X, not iphone...
Answer: [jSon1 objectAtIndex:0]
is returning an array of 3 separate strings, so if yo'ure trying to get the 3rd string you could do:
NSArray *links = [jSon1 objectAtIndex:0];
NSString *httpUrl = [links objectAtindex:2];
Hopefully i understand your question correctly.


ExpandableListView with different images for each groupHeader

Question: I'm gettin some difficulties while setting different icons for each groupHeader while using expandableListAdapter, here's the codes.
at main, Im calling it at onCreate()
expListView = (ExpandableListView) findViewById(R.id.lvExp);

// preparing list data
prepareListData();

listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);

// setting list adapter
expListView.setAdapter(listAdapter);

my Adapter code:
package info.androidhive.slidingmenu;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class ExpandableListAdapter extends BaseExpandableListAdapter {

    private Context _context;
    private List<String> _listDataHeader; // header titles
    // child data in format of header title, child title
    private HashMap<String, List<String>> _listDataChild;

    private ArrayList<Integer> groupImages;

    public ExpandableListAdapter(Context context, List<String> listDataHeader,
            HashMap<String, List<String>> listChildData) {
        this._context = context;
        this._listDataHeader = listDataHeader;
        this._listDataChild = listChildData;
    }

    @Override
    public Object getChild(int groupPosition, int childPosititon) {
        return this._listDataChild.get(this._listDataHeader.get(groupPosition))
                .get(childPosititon);
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public View getChildView(int groupPosition, final int childPosition,
            boolean isLastChild, View convertView, ViewGroup parent) {

        final String childText = (String) getChild(groupPosition, childPosition);

        if (convertView == null) {
            LayoutInflater infalInflater = (LayoutInflater) this._context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.list_item, null);
        }

        TextView txtListChild = (TextView) convertView
                .findViewById(R.id.lblListItem);

        txtListChild.setText(childText);
        return convertView;
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return this._listDataChild.get(this._listDataHeader.get(groupPosition))
                .size();
    }

    @Override
    public Object getGroup(int groupPosition) {
        return this._listDataHeader.get(groupPosition);
    }

    @Override
    public int getGroupCount() {
        return this._listDataHeader.size();
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded,
            View convertView, ViewGroup parent) {
         String headerTitle = (String) getGroup(groupPosition);
            if (convertView == null) {
                LayoutInflater infalInflater = (LayoutInflater) this._context
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = infalInflater.inflate(R.layout.list_group, null);
            }

            TextView lblListHeader = (TextView) convertView
                    .findViewById(R.id.lblListHeader);
            lblListHeader.setTypeface(null, Typeface.BOLD);
            lblListHeader.setText(headerTitle);

            ImageView imageView = (ImageView)     convertView.findViewById(R.id.imgIconeProblema);
       LINE 99 -> int imageId = this.groupImages.get(groupPosition);
            imageView.setImageResource(imageId);

            return convertView;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }
}

and finally, my prepareList()
private void prepareListData() {
    listDataHeader = new ArrayList<String>();
    listDataChild = new HashMap<String, List<String>>();

    groupImages = new ArrayList<Integer>();
    groupImages.add(R.drawable.acessibilidade);
    groupImages.add(R.drawable.aguaeesgoto);
    groupImages.add(R.drawable.arvore);
    groupImages.add(R.drawable.bempublico);
    groupImages.add(R.drawable.buraco);
    groupImages.add(R.drawable.dengue);
    groupImages.add(R.drawable.educacao);
    groupImages.add(R.drawable.iluminacao);
    groupImages.add(R.drawable.lixo);
    groupImages.add(R.drawable.obras2);
    groupImages.add(R.drawable.pedestreeciclista);
    groupImages.add(R.drawable.pichacao);
    groupImages.add(R.drawable.queimada);
    groupImages.add(R.drawable.saude);
    groupImages.add(R.drawable.social);
    groupImages.add(R.drawable.transito);
    groupImages.add(R.drawable.transporte);

    // Adding child data

    listDataHeader.add("Acessibilidade");
    listDataHeader.add("Água e esgoto");
    listDataHeader.add("Árvore");
    listDataHeader.add("Bem público");
    listDataHeader.add("Buraco");
    listDataHeader.add("Dengue");
    listDataHeader.add("Educação");
    listDataHeader.add("Lixo");
    listDataHeader.add("Iluminação e energia");
    listDataHeader.add("Obra");
    listDataHeader.add("Pedestre e Ciclista");
    listDataHeader.add("Pichação");
    listDataHeader.add("Poluição");
    listDataHeader.add("Queimada");
    listDataHeader.add("Saúde");
    listDataHeader.add("Social");
    listDataHeader.add("Transporte");
    listDataHeader.add("Trânsito");

    // Adding child data
    List<String> acessibilidade = new ArrayList<String>();
    acessibilidade.add("Falta de sinalização para deficientes físicos, visuais e auditivos");
    acessibilidade.add("Dispositivo de acessibilidade em mau estado");
    acessibilidade.add("Falta de acessibilidade");
    acessibilidade.add("Pulp Fiction");

    List<String> aguaeesgoto = new ArrayList<String>();
    aguaeesgoto.add("Falta de saneamento básico");
    aguaeesgoto.add("Esgoto a céu aberto");
    aguaeesgoto.add("Falta de água");
    aguaeesgoto.add("Tratamento de esgoto inadequado");
    aguaeesgoto.add("Vazamento de água");
    aguaeesgoto.add("Bueiro entupido");
    aguaeesgoto.add("Bueiro sem tampa");
    aguaeesgoto.add("Água encanada com má qualidade");
    aguaeesgoto.add("Alagamento");

    List<String> arvore = new ArrayList<String>();
    arvore.add("Árvore caída");
    arvore.add("Poda de árvore necessária");
    arvore.add("Poda de árvore irregular");
    arvore.add("Arborização necessária");

    // Adding child data
    List<String> bempublico = new ArrayList<String>();
    bempublico.add("Bem público em mau estado de conservação");
    bempublico.add("Vandalismo em bem público");
    bempublico.add("Atendimento ruim em serviço público");
    bempublico.add("Má administração de bem público");
    bempublico.add("Falta de sinalização em bem público");

    List<String> buraco = new ArrayList<String>();
    buraco.add("Buraco no asfalto");
    buraco.add("Buraco no chão");
    buraco.add("Rua esburacada");

    List<String> dengue = new ArrayList<String>();
    dengue.add("Foco de dengue");
    dengue.add("Terreno baldio");

    List<String> educacao = new ArrayList<String>();
    educacao.add("Ensino precário");
    educacao.add("Escola em mau estado");
    educacao.add("Falta de funcionários na escola");
    educacao.add("Falta de material escolar");
    educacao.add("Falta de professores em escola");
    educacao.add("Falta de vagas em escola");

    List<String> lixo = new ArrayList<String>();
    lixo.add("Lixo ou entulho");
    lixo.add("Veículo abandonado");

    List<String> iluminacaoeenergia = new ArrayList<String>();
    iluminacaoeenergia.add("Falta de iluminação");
    iluminacaoeenergia.add("Poste de luz em mau estado");
    iluminacaoeenergia.add("Poste de luz queimado");
    iluminacaoeenergia.add("Fiação irregular");
    iluminacaoeenergia.add("Iluminação pública irregular");
    iluminacaoeenergia.add("Lâmpada acesa durante o dia");
    iluminacaoeenergia.add("Lâmpaga apagada à noite");

    List<String> obra = new ArrayList<String>();
    obra.add("Obra pública irregular");
    obra.add("Obra públuca necessária");
    obra.add("Obra pública parada");
    obra.add("Obra pública atrasada");
    obra.add("Obra pública mau executada");
    obra.add("Obra particular abandonada");
    obra.add("Obra particular irregular");

    List<String> pedestreeciclista = new ArrayList<String>();
    pedestreeciclista.add("Calçada obstruída por poste mobiliário urbano");
    pedestreeciclista.add("Tempo de travessia insuficiente do semáforo de pedestres");
    pedestreeciclista.add("Falta de sinalização para pedestres");
    pedestreeciclista.add("Calçada para pedestre em mau estado");
    pedestreeciclista.add("Falta de faixa de pedestre");
    pedestreeciclista.add("Semáfoto de pedestre quebrado");
    pedestreeciclista.add("Calçada obstruída por estabelecimento");
    pedestreeciclista.add("Calçada obstruída por veículo");
    pedestreeciclista.add("Necessidade de bicicletário ou paraciclo");
    pedestreeciclista.add("Ciclovia mal sinalizada");
    pedestreeciclista.add("Necessidade de ciclovia");
    pedestreeciclista.add("Ciclovia em mau estado");
    pedestreeciclista.add("Ciclovia irregular");

    List<String> pichacao = new ArrayList<String>();
    pichacao.add("Pichação");

    List<String> poluicao = new ArrayList<String>();
    poluicao.add("Poluição do ar");
    poluicao.add("Poluição sonora");
    poluicao.add("Poluição visual");

    List<String> queimada = new ArrayList<String>();
    queimada.add("Queimada");

    List<String> saude = new ArrayList<String>();
    saude.add("Atendimento de saúde precário");
    saude.add("Falta de profissionais de saúde");
    saude.add("Falta de leitos");
    saude.add("Instalações de saúde precárias");
    saude.add("Controle de zoonoses necessário");
    saude.add("Epidemia");
    saude.add("Infestação");

    List<String> social = new ArrayList<String>();
    social.add("Moradores de rua");
    social.add("Pedintes");
    social.add("Ponto de venda ou consumo de drogas");
    social.add("Invasão ou assentamento em propiedade particular");
    social.add("Ocupação de local público");

    List<String> transporte = new ArrayList<String>();
    transporte.add("Ponto de parada sem abrigo");
    transporte.add("Veículo de transporte público em mau estado");
    transporte.add("Longo tempo de espera por transporte público");
    transporte.add("Superlotação no transporte público");
    transporte.add("Má conduta do motorista ou funcionário do transporte público");
    transporte.add("Falta de segurança no transporte público");
    transporte.add("Interrupção no serviço ou trajeto do transporte público");
    transporte.add("Transporte público sem ventilação adequeada");
    transporte.add("Estação em mau estado");
    transporte.add("Ponto de parada em mau estado");
    transporte.add("Falta de transporte público");
    transporte.add("Falta ou deficiência de sinalização no transporte público");

    List<String> transito = new ArrayList<String>();
    transito.add("Falta de sinalização de trânsito");
    transito.add("Placa de sinalização de trânsito em mau estado");
    transito.add("Congestionamento");
    transito.add("Semáforo de trânsito quebrado");
    transito.add("Semáforo de trânsito necessário");
    transito.add("Via de trânsito em mau estado");
    transito.add("Veículo estacionado em local proibido");
    transito.add("Trânsito de veículos proibidos");
    transito.add("Falta de fiscalização de trânsito");

    listDataChild.put(listDataHeader.get(0), acessibilidade); // Header, Child data
    listDataChild.put(listDataHeader.get(1), aguaeesgoto);
    listDataChild.put(listDataHeader.get(2), arvore);
    listDataChild.put(listDataHeader.get(3), bempublico);
    listDataChild.put(listDataHeader.get(4), buraco);
    listDataChild.put(listDataHeader.get(5), dengue);
    listDataChild.put(listDataHeader.get(6), educacao);
    listDataChild.put(listDataHeader.get(7), lixo);
    listDataChild.put(listDataHeader.get(8), iluminacaoeenergia);
    listDataChild.put(listDataHeader.get(9), obra);
    listDataChild.put(listDataHeader.get(10), pedestreeciclista);
    listDataChild.put(listDataHeader.get(11), pichacao);
    listDataChild.put(listDataHeader.get(12), poluicao);
    listDataChild.put(listDataHeader.get(13), queimada);
    listDataChild.put(listDataHeader.get(14), saude);
    listDataChild.put(listDataHeader.get(15), social);
    listDataChild.put(listDataHeader.get(16), transporte);
    listDataChild.put(listDataHeader.get(17), transito);

}

without knowing why, i'm gettin the error
"java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.util.ArrayList.get(int)' on a null reference at info.androidhive.slidingmenu.ExpandableListAdapter.getGroupView (ExpandableListAdapter.java: 99)
line 99 is marked above.
Thanks
Answer: I think, you are not initializing groupImages in ExpandableListAdapter so it is null. Pass groupImages from MainActivity to ExpandableListAdapter (like listChildData and ListDataHeader).
public ExpandableListAdapter(Context context, List<String> listDataHeader,
        HashMap<String, List<String>> listChildData, ArrayList<Integer> groupImages) {
    this._context = context;
    this._listDataHeader = listDataHeader;
    this._listDataChild = listChildData;
    this.groupImages = groupImages;
}

Comment: You deserve a medal!

Now it is working perfectly, I'm just getting and outofboundsExcep. but its ok!

You helped me a lot!

Thank you so much!
Comment: I am glad it worked ;) and i guess outofboundsExcep is due to `listDataHeader` contains 18 entries where as `groupImages` contains only 17, try adding the missing one.
Comment: I'm going to check!

Glad you've helped!
Comment: All ok!

Thanks you so much again!
Comment: Welcome :) Please accept the answer (check mark at the left) if it has helped you to solve the answer.
Comment: Sorry for that, I'm new here :P

and yes, you helped!


KineticJS leaving behind ghost

Question: So i recently added Kinetic.JS v4.6.0 to my app, and tested out a simple rectangle drag and drop.
Works fine on the web browser, but as soon as i use it on a mobile, it bugs out and leaves a ghost of the rectangle after dragging.
I'm basically using the same script as the demo, without the touchStart/touchEnd events, i'm also using JQuery 1.9.1 and JQueryMobile-1.3.2.
How can i get rid of this effect, i've tried clearing the layer on touchStart and drawing the stage again on touch End but the ghost stays there.
Edit
My device is a Galaxy S2 running 4.2.2 and the ghosting happens, but the app works fine on the Ipad.
/index.JS
$( window ).on( "pageinit", function ( event ) {
stage = new Kinetic.Stage( {
    container: "container",
    width: 500,
    height: 500
} );

MapLayer = new Kinetic.Layer()

var Rect = new Kinetic.Rect( {
    x: 0,
    y: 0,
    width: 100,
    height: 50,
    fill: 'green',
    stroke: 'black',
    strokeWidth: 4,
    draggable: true
} );

MapLayer.add( Rect );
stage.add( MapLayer );

Index.HTML

<title>Mobile OneStop</title>

( I might do a badly drawn paint image to show this off if people do not understand)
Edit
https://i.stack.imgur.com/y2odJ.jpg -
Ive changed a lot of the code since posting this, but the issue still remains.
Comment: Did you try on multiple devices? Also, do you receive the ghosting on one his demos? Canvas animation uses a lot of CPU and choppiness may vary.
Comment: Tested on my Galaxy S2 and it doesnt work, tested on an Ipad and it works, trying to test on other android devices now. Does android have problems with HTML5 Canvas or something?
Comment: You could take a screen capture on your GS2 and post it here. That would help.
Comment: added a screenshot, the background layer still moves,  i read that this issues is common on android 4.1 and up and only applies to the first object in the canvas, anything added after that it works fine
Answer: Managed to stop the ghosting from happening, I have just put a huge white rectangle behind the  objects i need to be drawn, not elegant but it gets the job done.

KineticJS leaving behind ghost


Count ou Count()

Question: Tendo uma lista, qual melhor forma de saber o número de itens nessa lista e qual a diferença?
if (minhaLista.Count > 0) ;

ou
if (minhaLista.Count() > 0) ;

Comment: Tá de olho, hein =D
Comment: @jbueno sempre.
Comment: Boa pergunta...
Answer: A melhor forma é sempre usar Count, ela é incrementada sempre que um item é adicionado à lista e decrementada sempre que um item é removido.
A diferença entre os dois é que Count é uma propriedade de List e Count() é um método de extensão do namespace System.Linq.
No caso de List's, o método Count() verifica se o objeto é realmente um ICollection e depois retorna a propriedade Count (em outros casos ele pode executar algum algoritmo para obter a contagem). Usando diretamente a propriedade você acaba evitando esta verificação.
Aqui você pode encontrar o fonte do método (repare na terceira linha)
public static int Count<TSource>(this IEnumerable<TSource> source)
{
    if (source == null) throw Error.ArgumentNull("source");
    ICollection<TSource> collectionoft = source as ICollection<TSource>;
    if (collectionoft != null) return collectionoft.Count;
    ICollection collection = source as ICollection;
    if (collection != null) return collection.Count;
    int count = 0;
    using (IEnumerator<TSource> e = source.GetEnumerator()) {
        checked {
            while (e.MoveNext()) count++;
        }
    }
    return count;
}

Answer: De maneira geral sempre que puder usar a propriedade Count é melhor porque o acesso é direto. A expectativa é que ela sempre seja O(1).
Count() é um método de extensão do LINQ, portanto só pode usar em objetos que implementem IEnumerable que poderá executar algum algoritmo para obter a contagem. Se o objeto em questão implementar a interface ICollection ele fará justamente a leitura da propriedade Count, o resultado será o mesmo e o tempo de resposta quase idêntico, mas bem ligeiramente mais lento por ter uma indireção. Mas ambos terão complexidade O(1). Note que isto não é garantido usando este método, depende do contexto.
O fonte dele pode ser visto no Reference Source do .NET Framework. Veja também do .NET Core (.NET 5 pra frente) (tem que fuçar nos arquivos parentes já que ali está mais organizado.
Comment: Vou usar o link do source na minha resposta. Espero que não se importe =)
Comment: Claro que não, ele público.
Answer: O Count é uma propriedade manipulada pela sua lista, que é incrementada conforme você aplica um Add na lista, ou seja, você tem um acesso direto ao valor ao usa-la.
O Count() é um método de extensão que vem do namespace System.Linq, sua implementação consiste em varrer o IEnumerable e efetuar a contagem (ou tentar buscar a propriedade Count, caso seja uma implementação vinda de ICollection), ou seja, no fim eles acabam usando a mesma propriedade nesse cenário. Aqui está a implementação dele:
  public static int Count<TSource>(this IEnumerable<TSource> source) {
        if (source == null) throw Error.ArgumentNull("source");
        ICollection<TSource> collectionoft = source as ICollection<TSource>;
        if (collectionoft != null) return collectionoft.Count;
        ICollection collection = source as ICollection;
        if (collection != null) return collection.Count;
        int count = 0;
        using (IEnumerator<TSource> e = source.GetEnumerator()) {
            checked {
                while (e.MoveNext()) count++;
            }
        }
        return count;
    }

O melhor a se usar é o Count neste caso.
Comment: Count() não faz a contagem em listas, o próprio código mostra isso
Comment: Eu estava justamente corrigindo isto agora...
Comment: Show! +1 agora.

Count ou Count()


Pre/Post Likert survey analysis

Question: Online anonymous Likert survey was sent containing 13 items, the survey was sent before and after an intervention. I would like to analyze the % respondents who responded agree/strongly agree to the items both pre and post-intervention.
The total $n$ is small and do not match up as pre-intervention $n=14$, post-intervention $n=18$. I have been struggling to find the correct analysis ... I've come across McNemar vs. Wilcoxon vs paired t-test.
Comment: Having mismatched respondents pre- and post- will be problematic.   Your best bet will probably be to include only those respondents who participated in both surveys.  I assume you able to identify the pre- answers to the post- answers for the same respondent?
Comment: "analyze the % respondents who responded agree/strongly agree to the items".  This is somewhat ambiguous.  Are you interested in analyzing each item individually, or counting the 13 items together?
Comment: Based on the survey design, I will not be able to match the pre and post answers for the same respondent. I am analyzing each item separately ie: For Item 1, is there a significant increase in respondents who agree and strongly agree post-intervention compared to pre-intervention.
Answer: Because you can't match the pre answers with the post answers, there's no way to pair the responses, and so there's no way to use tests designed for paired responses (such as those you mention: McNemar, paired-sign rank, and paired t-test).
Probably the best approach is to use a test of association designed for independent samples.  Because you are measuring the same individuals in the two groups, this may be a violation of the independence assumption of the test.  But I don't know any way to adjust for this.  This violation should be noted in the methods or results.
This approach will probably have lower power than if you had recorded the identity of the respondents in order to pair the results.
Because you are condensing the responses of a single Likert item into two categories (SA/A vs. N/D/SD), this becomes a nominal variable with two levels *  ** .
This leaves you with a 2 x 2 contingency table.  Appropriate analyses are chi-square test of association, Fisher's exact test, or G-test of association.  Please be sure you understand the assumptions and interpretation of the test you choose to use.
I also strongly suggest you report a measure of effect size.  For a 2 x 2 table, the most common measure of effect size is phi.  This statistic is fairly common, and may be more meaningful to the reader than the p-value in this case.
Because your observations aren't paired, you can include all observations.  The unequal sample sizes won't be problematic.

** You can think of it as either an ordinal variable with two categories or a nominal variable with two categories.  It won't matter.
*** I probably recommend against condensing your data in this manner.  If you leave your responses as an ordinal variable (SD, D, N, A, SA), appropriate tests might include Cochran-Armitage test, Mann-Whitney test, or Kendall correlation.
Answer: There are some other posts on this site about similar problems. While it would clearly be better to know the pairing, everything is not lost, so I clearly disagree with @Peter Flom.
I have one answer to Analysing pre-and-post intervention study with anonymous responses  which uses permutations (in a case with exactly the same people pre/post.) That analysis should be possible to extend (I will try so, later.) Some other relevant posts is t-test for partially paired and partially unpaired data  with many good answers.
Answer: I'm sorry, but, while I agree with @Sal 's answer above, I'm even more skeptical. If you have some of the same people before and after but don't know who is who, then I'd say you on such dangerous ground that the best course may be to abandon the analysis.
It's certainly true, as Sal notes, that not being able to pair will greatly lower power. But, in addition, any results you report (beyond the simple %ages) will be misleading. Any effect size estimates, p values or other results will simply not be correct.

Pre/Post Likert survey analysis


CORS is not working with ionic

Question: I am trying to send a json to a php script on a server and even though I have included header in php script to have CORS the console throws error
error message

XMLHttpRequest cannot load http://www.awesomegag.0fees.us/updata.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access. The response had HTTP status code 403.

my code :
php
<code><?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Content-Type: application/json; charset=UTF-8");
if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400');    // cache for 1 day
}

// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS");

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers:            {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

    exit(0);
}
echo"hello";
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
?>
</code>
My app.js
<code>.controller('datactr',   ['$scope','$http','ApiEndpoint',function($scope,$http,ApiEndpoint) {
$scope.submit=function(){
          console.log("step1");

    $http({
      method:'POST',
      url:'http://www.awesomegag.0fees.us/updata.php',
      data:{
        'name':$scope.name
      }

    }).success(function(data,status,header,config){
      console.log("step2");
      console.log(data);
    })
 });
</code>
I tried to make it work using proxy method by making path /api and proxyUrl to updata.php address in ionic.project and then replace url in http service to /api. I get a 500 internal server error.
Can anyone help ?

Update: I have moved to a different server where everything works fine.I guess it is some problem with the server but have no idea how to fix it.
Comment: "The response had HTTP status code 403." That's what you should address. It's probably hitting before you event get to executing your PHP.
Comment: HTTP code 403 is forbidden so I changed the file permission to rwxrwxrwx and it resulted in same error.
Answer: Looks like that your server doesn't allow OPTIONS method.
Modern browser do "pre-flight" request for cross origin request to make sure that it is allowed to do so before sending GET/POST request.

Solution: Enable OPTIONS command. Example for Apache http://httpd.apache.org/docs/trunk/mod/mod_allowmethods.html
Comment: I tried to use GET method instead of a POST I get a 500 internal server error.What does that mean?
Comment: you posting a data so POST is the way don't use GET for this case.
Comment: how do you enable OPTIONS method?
Comment: That will depend on your server, if it is apache then use the link above.
Comment: I am using free web hosting from 0fees.net .But even without changing the settings in apache it should work with the php header right? source : http://enable-cors.org/server_php.html
Comment: try change the second line to header('Access-Control-Allow-Methods: GET, POST,OPTIONS');
Comment: I chaned it.But it still shows the same 403 forbidden error.Do you suggest moving to another server? please suggest one if you do so.
Comment: try it on your local server, if it is work then the issue is with server configuration.
Comment: It works fine with my localserver.I guess there is problem with the webserver.

CORS is not working with ionic


Scrapy - change settings at runtime based on attribute provided

Question: I'm having fun with scrapy, working on this project, a spider for facebook's posts.
I would like to change the CONCURRENT_REQUESTS parameter in settings.py at runtime, if a boolean attribute is provided
I tried overwriting the from_crawler method as follows, but it seems not to work
@classmethod
def from_crawler(cls, crawler, **kwargs):
    settings = cls(crawler.settings)
    if 'conc' in kwargs:
        settings.set('CONCURRENT_REQUESTS',32)
    return settings

Can you please show me how to it properly, and also how to change the __init__. Should I move all that the attribute parsing in from_crawler?
Thx!
Comment: Possible duplicate of [Update scrapy settings based on spider property](https://stackoverflow.com/questions/42134570/update-scrapy-settings-based-on-spider-property)
Comment: have you tried something like `scrapy crawl spider -s CONCURRENT_REQUESTS=32`?
Answer: CONCURRENT_REQUESTS setting used in scrapy.core.downloader.total_concurrency.
Settings itself are immutable. But scrapy.core.downloader object is mutable.
You can dynamically change this value from spider methods.
class FacebookSpider(scrapy.Spider):
.......
    def __init__(self, *args, **kwargs):
        if 'conc' in kwargs:
            self.crawler.engine.downloader.total_concurrency = 32

....
Answer: Based on this informative issue#4196 combined with the telnet console it is possible to do it, even post-execution.
Attach a telnet client to the port (e.g. 1234) & password logged when scrapy crawl command is launched, and issue the following interactive Python statements to modify the currently running downloader:
$ telnet  127.0.0.1  6023  # Read the actual port from logs.
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
Username: scrapy
Password: <copy-from-logs>

>>> engine.downloader.total_concurrency
8
>>> engine.downloader.total_concurrency = 32
>>> est()
Execution engine status

time()-engine.start_time                        : 14226.62803554535
engine.has_capacity()                           : False
len(engine.downloader.active)                   : 28
engine.scraper.is_idle()                        : False
engine.spider.name                              : <foo>
engine.spider_is_idle(engine.spider)            : False
engine.slot.closing                             : False
len(engine.slot.inprogress)                     : 32
len(engine.slot.scheduler.dqs or [])            : 531
len(engine.slot.scheduler.mqs)                  : 0
len(engine.scraper.slot.queue)                  : 0
len(engine.scraper.slot.active)                 : 0
engine.scraper.slot.active_size                 : 0
engine.scraper.slot.itemproc_size               : 0
engine.scraper.slot.needs_backout()             : False

The same interactive statements above can be written as code in Crawler.parse() method.
Answer: I just noticed that since I can just use the "-s CONCURRENT_REQUESTS=32" at runtime. Another option would have been to overwrite the update_settings method, here's a reference for anybody who runs into this issue:
Update scrapy settings based on spider property


menu sobrepor todo o document

Question: Tenho o seguinte jQuery:
$("div.menuMin img").click(function(){

    $("div.menuMin").css("display","none");

    $("div.menu")
         .css("position","absolute")
         .css("display","block")
         .css("width","100vw")
         .css("height","100%")
         .css("top","0")
         .css("left","0")
         .css("z-index",100000);
      $("div.menu div.sessoes")
           .css("height","100%")
        $("div.menu div.sessoes ul.menu")
             .css("width","100%")
             .css("height","100%")
             .css("backgroud-color","red")
             .css("z-index",100000);
          $("div.menu div.sessoes ul.menu li")
               .css("width","100%")
               .css("display","block","!important");
            $("div.menu div.sessoes ul.menu li a")
                 .css("font-size","12px")

});

Que fecha um botão de menu e abre o menu.
Isso está ocorrendo. Mas não estou conseguindo colocar toda a div.menu por cima do body ou do document todo na vertical (100vh).
Na horizontal, sem problemas (100vw). Mas na vertical não vai.
Meu HTML

<?php echo $constantes->getCabecalhoAdmin(); ?>

<?php require_once("_requeridos/menu.php"); ?>

<?php require_once("principalConteudo.php"); ?>

<?php require_once("_requeridos/final.php"); ?>

Onde estou errando?
Eis o CSS
@charset "utf-8";
/* CSS Document */

div.menu {
    height: 50px;
}
div.menu div.sessoes ul.menu {
    width:100%;
    height:70px;
    color:rgb(255,255,255);
    background-color: rgb(36,81,60);
}
div.menu div.sessoes ul.menu li {
    width:19.5%;
    float:left;
    cursor:pointer;
    text-align:center;
    border-left:.1px solid  rgb(0,0,0);
    transition: 0.5s ease-in;
}
div.menu div.sessoes ul.menu li.last {
    border-right:.1px solid rgb(0,0,0);
}

div.menu div.sessoes ul.menu li:hover {
    background-color: rgb(25,57,42);
}
div.menu div.sessoes ul.menu li a{
    display:block;
    width:100%;
    line-height:70px;
    letter-spacing: 1.5px;
    text-transform: uppercase;
    font-size:1.7vw;
    color:rgb(255,255,255);
}

Alguma coisa meio que trava o menu em 187px de altura e não consigo achar.
Eis uma print:
Answer: Me esqueci que o 100% só é possível para objetos parents posicionados. kkk.
Solução:
Bastava apenas adicionar relatividade ao body que estava sem
body {
  position: relative;
  ...
}

menu sobrepor todo o document


Uso o delphi 10.4 e qdo aperto a tecla F7 pra debugar aparece varias abas ( SysInit, CPU, System... e outras e não consigo debugar. Como resolver?

Question: Ao debugar meus programas em delphi 10.4 pela tecla F7, aparecem varias abas (System, CPU, SysInit e outras que não permitem entrar no debug do código fonte em si! Meu Windows é windows 10! Alguém sabe como resolver isso? no delphi 7 rodava o debug normal, mas troquei de  SO e de ide e deu esse erro.
Comment: Use F8 para prosseguir para próxima linha quando debuga código, F7 vai entrar na função da linha.
Comment: Eu ja tentei a F8 pra debugar! Até vai de linha em linha mas somente ate a linha Application.Run ai o programa executa e não exibe mais as linhas de codigo! Por exemplo se eu clicar num button que executa uma função ele não entra no código pra debugar. Como faço pra resolver isso?
Comment: Você adiciona um break point no OnClick do Butto. Verifique se não vai ficar um X sobre o ponto vermelho do break point, se ficar, quer dizer que o Break Poijnt não vai ser alcançado e a IDE não vai parar nesse  caso você pode tentar remover e adicionar de novo, adicionar o breakp point em outra linha ou em último caso reiniciar a IDE.
Comment: Então, da forma que vc indicou dá certo, mas não tem como fazer o debug sem precisar dos breaks @Diego_F?  Tipo como era no DELPHI 7? Porque durante pesquisas sobre o assunto vi que outras pessoas fazem o debug sem precisar de breaak point!  Sua ajuda já abre o caminho, mas se pudesse me tirar essa dúvida  ficaria perfeito! Abraço;
Comment: Eu normalmente executo meus projetos usando F9(não sei se é este que está usando) se usar F7 ele começa com o debug desde a primeira linha do source file.
Agora se tem como debugar um botão, por exemplo, sem fazer uso de break point, desculpe, mas eu desconheço.
Comment: Mano @Diego_F. vc ajudou bastante! Com sua dica já consigo debugar meus projetos!  O que estranhei é que no delphi 7 fazia o debug pelo F7 sem precisar colocar um break, tipo era só clicar num objeto do form  e  sair apertando o F7 pra ir linha a linha!  Tou fuçando agora o DELPHI 10, por isso as dúvidas! Mas valeu amigo!
Comment: Mano @Diego_F, amigo preciso de mais uma ajuda! Nem sei se pode ser por esse mesmo tópico, mas é que nã tou consguindo gravar na tabela que uso! tipo o usuario clica num botao e contabiliza +1 no campo do serviço inducado!  fazendo o debug o campo recebe o valor, aparece no db grid a altrração, depois  dou o .post. Mas qdo abro a tabela novamente não ta salvo o registro! Volta sempre ao que era antes Uso um DM.FDTcONECTION + TFDTTABLE. Podes me ajudar?
Comment: Acredito que seja necessário outro tópico, pois é um problema diferente.
Quando for criar lembre-se não postar código em imagens, detalhar bem seu problema e o que já fez para tentar resolver, além de colocar um MVC.
Para mais detalhes o [Guia de Sobrevivẽncia Resumido](https://pt.meta.stackoverflow.com/questions/8089/guia-de-sobreviv%c3%aancia-do-sopt-vers%c3%a3o-curta?noredirect=1&lq=1) e o [Manual de como não fazer perguntas](https://pt.meta.stackoverflow.com/questions/5483/manual-de-como-n%c3%83o-fazer-perguntas?noredirect=1&lq=1) podem te ajudar.
Comment: O movimento de perguntas com a tag Delphi não é muito ativo no Stack Overflow em Português  se comparadas a tecnologias voltadas para Web, por exemplo, então dependendo da sua urgência talvez seja melhor perguntar direto no Stack OverFlow em Inglês mesmo.
Comment: oi! Resolvi da seguinte maneira: criei um campo na tabela e coloquei como indice so pra ter uma key! masn na hora de mostrar a atualização não exibo esse campo! é uma gambiarra mas deu certo!
Answer: Por padrão o delphi vem configurado como teclas de debug
F7=stepinto
F8=stepover
F9=continue
Quando usar o F7? quando você está com o cursor parado em cima de uma function ou procedure e você quer ver o que será executado ali dentro, ai nesse caso ele te joga pra dentro da rotina.
Quando usar o F8? Quando você precisa passar passo a passo dentro de uma mesma rotina, ignorando o conteúdo de functions ou procedures que são executados naquele bloco de código, mantendo o foco no mesmo. Ou ainda você pode usar o F8 pra chamar o debug da aplicação passando pela inicialização do app.
Quando usar o F9? O uso do F9 no processo de debug ele ignora todos os outros passos que vem a seguir e retoma o fluxo normal de execução do debug. Ou ainda quando você precisa chamar o debug da aplicação e não quer passar pela inicialização do app.
Existem alguns casos que esse problema reportado por você podem acontecer, principalmente quando em seu código existe chamadas para bibliotecas, ou packages compiladas, aonde o debug deixa de ser possível e a partir dai o delphi começa a monitorar a instancia do seus dados que foram enviados para essa rotina.


Is there a standard procedure or regression model in marketing for explaining click rates on ads?

Question: I have an experiment where people click on different ads online. My measure is click counts.
I end up finding that I should use models for count data such as Poisson, Quasi-Poisson, or Negative Binomial regression.
Is there a standard in marketing regarding what model should be used for click counts?
Thanks
Comment: in my data I have NO zeros. Maybe there is a recommended model with / without zero inflation and also one for low and one for high n...
Answer: You can use Poisson regression and in more general form, Poisson process when data is following a Poisson distribution. In terms of Bayesian inference, you can make your own likelihood model, and then by conjugating your Poisson prior by likelihood, derive your posterior distribution.
Here I borrow an example from glm function in R:
<code> ## Dobson (1990) Page 93: Randomized Controlled Trial :
 counts <- c(18,17,15,20,10,20,25,13,12)
 outcome <- gl(3,1,9)
 treatment <- gl(3,3)
 print(d.AD <- data.frame(treatment, outcome, counts))
 glm.D93 <- glm(counts ~ outcome + treatment, family=poisson())
 anova(glm.D93)
 summary(glm.D93)
</code>
Also, some slides about Poission Rregression with some example are here and here


Cannot send emails from tomcat application

Question: I'm having some trouble with our servers, we run in a ubuntu 18.04 as VM from Vmware ESXI 6.5 with a pfSense firewall as another vm, we have multiple tomcat instances running with no problem.
In the last few days, out of nothing, the application with java stopped sending emails and returning "COULD NOT CONVERT SOCKET TO TLS". I tried to replicate in another vmware server of mine, hosted at home, with same estructure, but it had the same problem.
Someone told me it could be the cacerts from java. Tried to apply update-ca-certificates, and update-ca-certificates. In my home server, it worked, all emails sent with no problem, but when I applied this in my production vmware server (hosted by IBM bare metal) it didn't worked.
The most unusual, it happens with any smtp server (gmail, and others). We use all emails with TLS and port 587.
Any ideas to solve this kind of problem, or any workaround ?
Thanks
Comment: @PiotrP.Karwasz actually, the java on version 201, do not allow connections with TLS 1.0 and 1.1, so I had to edit my java.security file to be able to solve the problem. Gmail still uses TLS 1.1
Comment: There are a few possible answers here: https://stackoverflow.com/questions/16115453/javamail-could-not-convert-socket-to-tls-gmail
Comment: Thanks for the tip, We had tried some things, this configurations included, but no success. What is weird, it's one server has solved with the update-ca-certs, and the production one didn't.
Comment: You are on the right track: by default JavaMail client requires a trusted TLS server certificate. Use `keytool -list` to check the contents of the `cacerts` file on the server: for GMail it should contain a certificate for `i:OU = GlobalSign Root CA - R2, O = GlobalSign, CN = GlobalSign`. Check also whether the server isn't using an alternative truststore (`javax.ssl.truststore` system property).
Answer: The problem was with the last versions of Java.
I had installed openjdk 1.8.0_292, since _291, doesn't allow TLS 1.0 and 1.1, protocol that Gmail has by default until today.
So, to be able to solve my problem without install another versions of java, I had edited the file
/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/security/java.security
And commented that part:
#jdk.tls.disabledAlgorithms=SSLv3, TLSv1, TLSv1.1, RC4, DES, MD5withRSA, \
#DH keySize < 1024, EC keySize < 224, 3DES_EDE_CBC, anon, NULL, \
#include jdk.disabled.namedCurves

And add this part right after:
jdk.tls.disabledAlgorithms=SSLv3, RC4, DES, MD5withRSA, \
DH keySize < 1024, EC keySize < 224, 3DES_EDE_CBC, anon, NULL, \
include jdk.disabled.namedCurves1

As you can see, the java had explicity disabled some protocols, returning the COULD NOT CONVERT SOCKET TO TLS error. Hope this help others who may find that problem.
PS: This is not right at all, it just worked for me so we could work while find another alternative. Here in Brazil we use some smtp server the didn't upgrade to v1.3 yet.
Comment: What!? Please use TLv1.2 or TLSv1.3 instead of re-enabling these old protocol versions!
Comment: This is not something I can choose, Gmail stmp is not accepting v1.2 or v1.3 yet. It's expected they update that, but I cannot wait without using the smtp until they fix that.
Comment: How you come to the conclusion that Gail is not accepting the current and previous version? Gmail currently talks TLS 1.3 to me just fine.
Comment: I couldn't connect using 1.3, I asked for a support for the companie who integrates our system to the smtp of gmail, and he told we would not be able to connect. We also use another smtp here in Brazil called Locaweb, also still using 1.1, because they didn't updated their protocols yet.


How to add checkboxes dynamically to the table in javascript

Question: I have a problem in how to add checkboxes dynamically to the javascript code. I have different scenario. I am getting data through ajax So I need to add table thead in the javascript rather than the html. But now I want to add Checkboxes to my thead. Indeed I added them but I don't know how to check them all with one checkbox. I write also code for that to select all but thats only working when my thead is in the html. Below is my code and it will give you a clear view. Try to read it in the editor because its a more compicated :)
//Javascript
$(document).ready(function() {

  $(document).ready(function() {
    $.ajaxSetup({
      headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      }
    });
  });

  $('select[name="class_id"]').on('change', function() {
    var classID = $(this).val();
    if (classID) {

      $.ajax({

        url: '/attendance/ajax/' + classID,
        type: "GET",
        dataType: "json",
        success: function(data) {

          var markup = '';
          markup += '
<input type="checkbox" id="options">	#	 Student ID<input type="text" class="form-control" disabled>	 Student Name<input type="text" class="form-control" disabled>	 Attendance<input type="text" class="form-control" disabled>	 Date<input type="text" class="form-control" disabled>	 Actions
';

          $.each(data, function(key, value) {

            markup += '
 <input class="checkBoxes" type="checkbox" name="checkBoxArray[]">	 <input type="hidden" value="' + value.id + '" name="id[]">' + value.id + '	 <input type="hidden" value="' + value.student_id + '" name="student_id[]">' + value.student_id + '	 <input type="hidden" value="' + value.first_name + '" name="first_name[]"><input type="hidden" value="' + value.last_name + '" name="last_name[]">' + value.first_name + ' ' + value.last_name + '<input type="hidden" value="' + value.attendance + '" name="attendance[]">' + value.attendance + '	' + '<input type="hidden" value="' + value.created_at + '" name="created_at[]">' + value.created_at + '	' + ' <button title="Edit" class="btn btn-outline-primary"></button> 	' + '
';

          });
          $('table[id="studentsData"]').html(markup);
        }
      });
    }
  });
});

//For selecting all checkboxes
$(document).ready(function() {

  $('#options').click(function() {

    if (this.checked) {
      $('.checkBoxes').each(function() {
        this.checked = true;
      });
    } else {
      $('.checkBoxes').each(function() {
        this.checked = false;
      });
    }

  });

});

Answer: The issue is the execution of event handlers on DOM elements.
The browser renders and executes code from top to bottom (in most cases).
This means that you execute $('#options').click() before you add all checkboxes via Ajax request.
Therefore you are trying to attach an event handler to elements which are not present at that moment of time.
To make it work, you have to add an event listener to the parent element
$('table[id="studentsData"]').on('click', '#options', function() {})

Source:
http://api.jquery.com/on/
The second argument is a selector you are going to target
Comment: But let me clear one thing more. I have also something like for searching in the table. But now my table thead is in javscrpit so it also cannot work. What i can do for that ? Tell me if you wanna see some code
Comment: Could you please open up a new question for this with a short code example and a jsbin / jsfiddle / codepen demo.

I know this does not answer your specific question but if you are adding more complexity I would look for a plugin / lib which already does the job.
Have a look at the following if that might work for you:
DataTables: https://www.datatables.net/
tablesort: http://tristen.ca/tablesort/demo/
List.js: https://listjs.com/docs/
Comment: Ok I am going to make a new question for that and explain it then i will give you the link for that :)
Comment: https://stackoverflow.com/questions/55557371/how-to-make-seach-work-in-javascipt-inlaravel
Comment: This is the link. Pls check this out


Number of pages in Timber pagination

Question: I am using version 2 of Timber and I am now adding pagination to my archives.
Timber, by default, returns 9 pages in the array for pagination. However, I'd rather only want to show first page, the last one and in between the current one with 2 surrounding pages.
The situation as I would like to see it:
For page 1:
1 | 2 | 3 | ... | 300 | Next >
For example page 7:
< Back | 1 | ... | 5 | 6 | 7 | 8| 9 | ... | 300 | Next >
However the default of Timber (at least for V2) is:
For page 1:
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 ... | 300 | Next >
For page 7:
< Back | 1 | ... | 4  | 5 | 6 | 7 | 8 | 9 | 10 | ... | 300 | Next >
Because the array with post.pagination.pages always contains 9 entries.
I am using the following pagination.twig for that in my templates.
{% if posts.pagination.pages is not empty %}

            {% if posts.pagination.prev %}

                    « {{ __( 'Vorige', 'my-site' ) }}

            {% endif %}

            {% for page in posts.pagination.pages %}

                    {% if page.link %}

                            {{ __( 'Pagina', 'my-site' ) }} {{ page.title }}

                    {% else %}

                            {{ __( 'Pagina', 'my-site' ) }} {{ page.title }}

                    {% endif %}

            {% endfor %}

            {% if posts.pagination.next %}

                    {{ __('Volgende', 'my-site') }}»

            {% endif %}

{% endif %}

I tried finding a good filter or action to change the settings for this, but unfortunately I can't seem to find one. It looks like version 1 did support this. with pagination() though. However I can't find an alternative for this for V2.
Answer: The answer by Radek put me on the right trail
use Timber\Pagination;

$context['pagination'] = Pagination::get_pagination( [
    'mid_size' => 2,
    'end_size' => 1,
    'show_all' => false,
] );

Answer: According to the docs:
https://timber.github.io/docs/v2/reference/timber-pagination/#get_pagination
you could easily pass the arguments here so those are from WordPress docs:
https://developer.wordpress.org/reference/functions/paginate_links/#parameters
Finally you can use that like this:
use Timber\Pagination;

...

$context['pagination'] = Pagination::get_pagination([
    'mid_size' => 1,
    'end_size' => 1,
    'show_all' => false,
]);

Comment: Unfortunately this is deprecated in 2.0 according to the code

https://github.com/timber/timber/blob/2.x/src/Timber.php#L1646
Comment: Ah wait... it's simply been moved.

use Timber\Pagination
Pagination::get_pagination([ ... ]);

Thanks :-)
Comment: Ah sorry, you are right. I posted correct link to docs but code from v1. I have edited the code as well. :-)

Number of pages in Timber pagination


Creating a DataSet from XML that has 1 table and 0 rows

Question: I am currently creating a DataSet from an XML stream using this
DataSet dataSet = new DataSet();
dataSet.ReadXml(xml);

I tried this,
<?xml version="1.0" standalone="yes"?>
<NewDataSet>

</NewDataSet>

Which creates a DataSet where Tables[0] is a table called "NewDataSet" with 1 column called "Table" and 1 row where the value of "Table" is "".  I then tried just this,
<?xml version="1.0" standalone="yes"?>
<NewDataSet>
</NewDataSet>

But this creates a DataSet with no tables. How do I create a DataSet with 1 table called "Table" with 1 column, but now rows?
Answer: You can't. ReadXml and WriteXml read/write only data, not structure of the whole dataset/datatable/columns/etc-schema.
My suggestion is to first read the schema from a seperate schema file with the function ReadXmlSchema and than read the data file.
Your schema could look like this:
<?xml version="1.0" standalone="yes"?>
<xs:schema id="MyDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
  <xs:element name="MyDataSet" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
    <xs:complexType>
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element name="MyDataTable">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="MyDataColumn" type="xs:string" minOccurs="0" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:choice>
    </xs:complexType>
  </xs:element>
</xs:schema>


ASP.NET MVC: The correct way to handle a cancel button

Question: I'm wanting to have a simple cancel button so on confirmation of, say, the deletion of a product, they can change their mind and click cancel before the actual delete action is started.
I figure that on clicking the button you are wanting to redirect the user to the previous page. I understand that a common way to handle this is with javascript
<code>onclick="javascript:history.back(1);"
</code>
Is this acceptable? If the user has javascript disabled, what happens then?
So instead, I figured that I would submit the form and an action would redirect the user to the previous page. Is this how it should be done? And if so, what is the C# code to do this?
Thanks for any help :)
Comment: In that case, `onclick="javascript:return(confirm('Are you sure you want to delete?'))` is probably going to be better.  It will keep them on the same page when they cancel instead of returning to a previous page.
Comment: Are you trying to stop a delete in progress or are you popping up a confirmation when the user clicks delete or what?
Comment: edited question. I meant that the user can click a cancel button when a confirmation popup is displayed
Comment: Thanks, that's a good point.

I would still like to know about the problem with disabling JS though.
Answer: the only way you can do this without javascript is if you make a second form that POSTs to a different action (that will just redirect you) that just has a single submit button with cancel text.
If you are doing a web application, it is pretty much expected that javascript is a requirement. As far as I'm concerned, anyone who chooses to live without javascript nowadays is choosing to live with a broken internet, and it has been a very long time since browsers did not support it. The whole idea is just silly to me, sort of like the people who block cookies.
Answer: Might be better if you do a jQuery postback to a controller event which can then send a cancel event to the object doing the processing.
if you make your processing object run async then you can have a cancel method which would then set say a flag which is checked each time around the processing loop or whatever it is you have.
I think just going back is a little dangerous in that the opperation may not actually stop.
Comment: as specified in the first paragraph edit, processing has not started yet


Prove for all convergent sequence $\phi\rightarrow x_0$, the set $\{x_0\}\cup \phi(\mathbb{N})$ is compact

Question: Prove for all convergent sequence $\phi\rightarrow x_0$, the set $A=\{x_0\}\cup  \phi(\mathbb{N})$ is compact
My work
Let $U=\{\bigcup_\alpha U_\alpha:\alpha\in\sum\}$ a open covers of $A$, then for some $U_\alpha$, we have $x_0\in U_\alpha$. Then for $\epsilon>0$ we have $B(x_0,\epsilon)\subset U_0$.
Here i'm little stuck, because my space $(X,\tau)$ not necessarily is a metric space. I'm a little confused here. Can someone help me?
Comment: In fact $B(x_0,\epsilon)$ contains all but finitely many $\phi(n).$
Comment: If you consider balls, then it's no longer general topology, but metric spaces instead.
Comment: is general topology, because is a general space @Adayah
Comment: Balls don't make sense in general topological spaces. So if your space doesn't have a metric, it was incorrect of you to even write $B(x_0, \epsilon)$.
Comment: Definitions are tools to be used. State the def'n of  convergence and use it. Always  use the definitions.
Answer: Recall the definition of convergence in a general topological space: $L$ is a limit of a sequence if for every neighborhood of $L$ the sequence is eventually in that neighborhood. It doesn't depend on balls or distances.
So once you have chosen an $U_\alpha$ that contains $x_0$, it will also contain all but finitely many elements of the sequence. Finitely many additional $U_\alpha$s will cover the rest.