Duvida sobre laço while em C?

Question: Eu preciso saber porque que o 0 tem que ser digitado duas vezes para que o programa pare de percorrer o laço.
E acontece a mesma coisa quando uso o do-while.
#include <stdio.h>
#include <stdlib.h>
void main(){
    int num = 1, maior, menor, resultado, count = 0;
    while(num != 0){
        scanf("%d\n", &num);
        if(count == 0){
            maior = num;
            menor = num;
            count = 1;
        }else{
            if (num > maior && num != 0) {
                maior = num;
            }
            if (num < menor && num != 0) {
                menor = num;
            }
        }
    }
    printf("%d, %d\n", maior, menor);
    system("pause");
}

Comment: se colocou todo o programa, porque `count` não faz sentido e maior e menor não teve declaração também
Comment: não coloquei o programa todo, porque achei que nao fazia sentido, mas posso mudar.
Comment: menor nunca pode ser 0! já tem um erro conceitual não precisa do count nesse caso
Answer: É um erro meio bobo no scanf foi colocado um quebra de linha (\n) e não precisa dando esse problema:
#include <stdio.h>
#include <stdlib.h>
void main(){
    int num = 1, maior = 0, menor = 99999999999;
    while(num != 0) {
        scanf("%d", &num);
        if (num > maior) {
            maior = num;
        }
        if (num < menor && num != 0) {
            menor = num;
        }
    }
    printf("%d, %d\n", maior, menor);
    system("pause");
}

Teste OnLine
Observação: foi feito algumas alterações no código.

Duvida sobre laço while em C?


Meaning of the default buffer size(8KB) of ' BufferedInputStream ' ? (JAVA)

Question: I was first curious about how the buffer size of 'BufferedInputStream' class is decided for each program. I found out in STACKOVERFLOW that the default buffer size is 8KB.
I wonder if there is profound meaning in the default buffer size of
'BufferInputStream' class, which is 8KB in size.
When I searched java docs for information about the 'BufferedInputStream' class,
I found out there are two forms of constructors for the class.
One constructor form offers users the ability to change the buffer size.
BufferedInputStream(InputStream in, int size)

Could the buffer size of this class be critical in deciding performance of some programs? I'm curious if anyone uses the above form of the constructor to change the buffer size to fit/optimize his/her program.
Is there any profound meaning to the default buffer size of 8KB?

Thank you for reading.
Answer:
Could the buffer size of this class be critical in deciding performance of some programs? I'm curious if anyone uses the above form of the constructor to change the buffer size to fit/optimize his/her program.

Probably not. Changing from a buffer size of 1 to 2 will about double your performance (by reducing system calls). Changing from 2 to 4 will double it again. Changing from 4 to 8, again. You get the idea. At some point this ceases being true, as the performance ceases being dominated by system calls and starts being dominated by transfer sizes. 8k is a good place to stop. Use more if you like but you won't notice much difference.

Is there any profound meaning to the default buffer size of 8KB?

There isn't. It is 8k in size. By default. That's the meaning. You can change it via a constructor. Nothing more to it.
Comment: there is a _profound meaning_ in 8KB: 4KB is the default and recommended block size for NTFS, it is also default with linux. 8KB is twice of it. you'd better choose a multiple of your block size in order to be efficient.


What combination of features should I look for an electric guitar to be as flexible as I can?

Question: I am an amateur guitar player for some time, and I have owned a couple of electric guitars. Now, I am looking to buy a new one.
I mostly play metal (Lamb of God, Godsmack, Metallica, Megadeth etc.), but sometimes I also want to play some smooth rock/blues (John Mayer, Eric Clapton, Jimi Hendrix, Joe Bonamassa etc.) Thus, I do not want to be limited by the guitar.
I am well aware that these two groups of artists/bands require two very different types of guitars to play properly. However, I am not expecting to play every song at a perfect level. What I am looking for is a guitar that allows me to play various genres with a decently proper tone.
So, my question is,

In other words, playing Master of Puppets with a Stratocaster is not very pleasing as well as playing Gravity with a King V.
  What combination of scale length, neck length, pickups and wood
  allows me to be flexible among different genres?

For the sake of completeness; I will not use an amp. I will use an amp simulator software and ordinary computer speakers to play.
Comment: Not posting as an answer, but you could have a look at the Line6 Variaxes; more guitars in one 'box' than you'd know what to do with.
Comment: You might consider a guitar with a pair of humbuckers with coil-tap switches; this way you can get either humbucker or single-coil sounds. The rest is really down to what you need. Do you want hotter pickups, do you need 24 frets, do you prefer longer scale lengths (like Fender) or shorter scale lengths (like Gibson), do you need to dive-bomb with your tremolo? For a more general purpose guitar you might want to avoid super low-action.
Answer: Honestly, I think a strat would fit the bill for what you described especially one fitted with a humbucker at the bridge. Otherwise, many people consider semi-hollowbody guitars to be among the most versatile guitars. Though if you mostly play metal, it may not be the best choice. (I personally use mostly a single semi-hollow for a wide variety of styles, but I don't really play much metal or high-gain music these days).
Pickups
In general I'd aim for a bridge humbucker for the metal stuff. A variety of pickups in the neck position could work for other styles or leads. The output/volume of the pickups is also a factor. For metal/modern tones you'd usually want a hot pickup but for cleaner and vintage tones you might want something a with a bit less output. So maybe a hot humbucker at the bridge and something with a little less output in the neck position?
Pickup Position
Another thing I'd consider is the position of the neck pickup. Many shredder-style guitars have 24 frets which requires the neck pickup to be slightly closer to the bridge than on a 21/22 fret guitar. This is actually nice for some kinds of shred leads because it will make the neck tone a bit brighter than it would be which usually helps it cut through the mix more.
But for an optimum thick, bluesy, neck tone, you want the pickup to be positioned about where that 24th fret would be and it can't be if the neck extends that far. So consider what type of neck tone you need and whether you'll actually use those extra few frets.
Scale Length
As far as scale length, longer scale lengths (ex. strat/tele) will have more tension using the same string gauge—affecting the feel for better or worse depending on preference—and will generally produce a clearer and more focused tone. Shorter scale lengths (ex. les paul) will have less string tension and sound a bit warmer. There's no best; they're just different.
Compromise or Compliment?
All that said, it's pretty hard to get a single guitar to cover a wide variety of styles well. You'll always be compromising somewhere. So I'd consider splitting your budget to get two cheaper but vastly different guitars to cover more ground. Or make your new guitar one that compliments the ones you already have rather than looking for one that does everything.
Answer: For me, the main thing is to have three pickups and at least a 3-way pickup selector (a 5-way is even better, since it lets you choose combinations of multiple pickups); in this way, you can drastically change your tone depending on the pickup(s) you're using (bridge, middle, neck). It's also good to have multiple types of pickups (single coils, humbuckers).
I also like using a short-scale guitar (like a Fender Mustang, for example)-- since the strings are not stretched as tightly as on a longer-scale guitar, you can do crazy bends with it!


pattern matching check if greater than symbol is not preceded by smaller than symbol

Question: i would like to check if the greater sign is preceded by the smaller than sign.
what i really need is to check i there are more than one word seprated by space between the > and <.
for example :

should be found because there are more than one "word" inside
and this :

should not
here is my python code
text = ' b'
if re.search('(?<!\<)[a-zA-Z0-9_ ]+>',text):   # search for '>'
   print "found a match"

for this text i dont want it to match because there is a smaller than sign before.
but it does find a match.
the Negative Lookbehind does not seem to be working.
solution(kindof):
this also finds smaller than symbol that is not preceded by a greater than symbol
match = re.search('<?[a-zA-Z0-9_ ]+>',text)
if ((match) and (match.group(0)[0] != '<')):
   print "found >"
match = re.search('<[a-zA-Z0-9_ ]+>?',text)
if ((match) and (match.group(0)[len(match.group(0))-1] != '>')):
   print "found <"

thanks homson_matt for the solution.
BETTER SOLUTION:
by replacing the string that causes the problem before looking for the greater and smaller symbols.
# replace all templates from source hunk ( <TEMPLATE> )
srcString = re.sub("<[ ]*[a-zA-Z0-9_\*:/\.]+[ ]*>", "TEMPLATE", srcString)
if re.search('[a-zA-Z0-9_ )]>',srcString): # search for '>'
    return True
if re.search('<[a-zA-Z0-9_ (]',srcString): # search for '<'
    return True

Comment: @ΤΖΩΤΖΙΟΥ: No, `(?` matches. Do you just want to verify that there is no `< >` sequence in your text?
Comment: yes but a sequence like this:  'x < 5 and y >5' is good tough
Comment: if there is only one word between them it should not find it, if more than one word than it should
Comment: Although this doesn't fix the issue, note that `'(?'` pattern should be `re.search('(?!<\<)[a-zA-Z0-9_ ]+>',text)` i.e. the `!` character goes before the `<` character.
Answer: The match is: a >.  This section matches your regex perfectly - it doesn't start with <, then it's got "a ", which matches the bit in square brackets, and then there's a >.
Are you trying to match the whole string? If you are, try re.match instead of re.search.
Or you might want to try this code.  It searches for a substring that might start with <, and then decides if it actually does.
text = ' b'
match = re.search('<?[a-zA-Z0-9_ ]+>',text)

if ((match) and (match.group(0)[0] != '<')):
  # Match found

Comment: yeah this one is pretty good. btw how do i check if the string dont end with a '>' sign
Comment: and how can i make sure i only check in current line if there is a < in the begining
Comment: The match is `'a >'` only because yossi entered an incorrect negative lookbehind assertion. If it was entered correctly as `'(?!<'`, then the match would be `' >'`.
Answer: I think this is what you're looking for:
r'<\s*\w+(?:\s+\w+)+\s*>'

\w+ matches the first word, then (?:\s+\w+)+ matches one or more additional words, separated by whitespace.  If you don't want the match to span multiple lines, you can change \s to a literal space:
r'< *\w+(?: +\w+)+ *>'

...or to a character class for horizontal whitespace only (i.e., TAB or space characters):
r'<[ \t]*\w+(?:[ \t]+\w+)+[ \t]*>'

Comment: thanks,but i need it to find even if only one is present like this: x> 5
Comment: Are you trying to parse Boolean expressions with regexes?
Comment: i just want to find if they are there. and ignore templates (C++)


mysql.proc has gone corrupt. How can I fix it?

Question: I have a server running Debian 5.0, and MySQL. Suddendly, MySQL stopped working, and after many attempts to fix it, I decided to reinstall it. I installed MySQL 5.1.63, and when started it goes to safe mode. I made some typing, and when I executed mysql_upgrade as root, it complained:
...
Running 'mysql_fix_privilege_tables'...
ERROR 1548 (HY000) at line 1111: Cannot load from mysql.proc. The table is probably corrupted
ERROR 1064 (42000) at line 1112: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'sqlstate 'HY000' set message_text='Unexpected content found in the performance_s' at line 1
ERROR 1548 (HY000) at line 1125: Cannot load from mysql.proc. The table is probably corrupted
FATAL ERROR: Upgrade failed

I checked the mysql.proc table, and it's comment column was slightly different from my backup.
-- My backup says:
`comment` char(64) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '',
-- But it were:
`comment` text CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,

So, I restored my mysql database backup, and now they all match, but mysql_upgrade still trigger the same errors. I also tried do check and repair the mysql.proc table, but got no success.
Answer: Have you tried to use the --force option:
mysql_upgrade --force -u root -p

Comment: Yes, and I've got the same results.
Comment: It's strange, I just restored another database, and it works. This error isn't preventing MyQL from working...


what is max-age property in HSTS security header?

Question: what is the purpose of max-age in HSTS ? such as:
Strict-Transport-Security: max-age=100

If the value exceeds 100, what will happen ?
is there any best practice of setting the max-age ?
thanks !
Answer: There are semantically distinct ways to send HSTS headers, as defined in RFC 6797:
Strict-Transport-Security: max-age=31536000

The HSTS policy is applied only to the domain of HSTS host issuing it and remains in effect for one year.
Strict-Transport-Security: max-age=31536000; includeSubDomains

The HSTS policy is applied to the domain of the issuing host as well as its subdomains and remains in effect for one year.
Strict-Transport-Security: max-age=0

Directs the browser to delete the entire HSTS policy.
HSTS Best Practices
There are a few simple best practices for HSTS:

The strongest protection is to ensure that all requested resources use only TLS with a well-formed HSTS header. Qualys recommends providing an HSTS header on all HTTPS resources in the target domain.
It is advisable to assign the max-age directive's value to be greater than 10368000 seconds (120 days) and ideally to 31536000 (one year). Websites should aim to ramp up the max-age value to ensure heightened security for a long duration for the current domain and/or subdomains.
RFC 6797, section 14.4 advocates that a web application must aim to add the includeSubDomain directive in the policy definition whenever possible. The directive's presence ensures the HSTS policy is applied to the domain of the issuing host and all of its subdomains, e.g. example.com and www.example.com.
The application should never send an HSTS header over a plaintext HTTP header, as doing so makes the connection vulnerable to SSL stripping attacks.
It is not recommended to provide an HSTS policy via the http-equiv attribute of a meta tag. According to HSTS RFC 6797, user agents don't heed http-equiv="Strict-Transport-Security" attribute on  elements on the received content.

This cheat sheet from OWASP might help you out in future too.


Filter nodes by today's date

Question: Following what described in Views filter criteria date field is greater than current date, I have used operator >= today with some success. I would like to create "future" nodes and they should be filtered out as well. What I need is for a date and time field to be filtered for today's date only. I have tried many things to include:

operator = today + either value type, machine readable or offset (returns no results)
operator = now + either value type, machine readable or offset (returns no results)
contextual filter: summary links (granularity not adjustable that I can find so returns multiple summary links for a single date & summary + a summary link is not a good UI for the application)
contextual filter: default value - "current date" (doesn't work; known issue with variably effective patch to core which I'd like to avoid) ref: https://www.drupal.org/project/drupal/issues/2325899
date only field (doesn't work due to UTC time & changes during daylight savings)
Answer: Figured this out.  Have to add the following 2 filters:
operator is "Is greater than or equal to" value is today
AND
operator is "Is less than" value is today +24 hours
Notes:
Must use "Is greater than or equal to" to include today at midnight and must use "Is less than" to filter out tomorrow at midnight.
It does not matter what value type you select, machine readable or offset.
The value "today" literally returns the time of midnight on today's date.  This means setting operator Is equal to "today" only returns results dated on exactly midnight of today, hence why zero results were returned.
SQL for "today" taken from Views query:
DATE_FORMAT(('2020-03-29T07:00:00' + INTERVAL -25200 SECOND), '%Y-%m-%d\T%H:%i:%s'))
"+ INTERVAL -25200 SECOND" is -7 hours correction for my time zone so time is T00:00:00 or midnight.

Filter nodes by today's date


Drupal commerce (Coupon & Discounts) - Alter rule condition

Question: I have a drupal commerce website on which I have add the discout module to make discounts and coupons.
I have in my backoffice a list of all the orders and I can modify them if I want.
The problem is the following :
If I create an order with a discount limited in the time, at the moment when I create the order the coupon is valid and it's added to my order.
But then, multiple days ago I have to modify this order for some reasons, but now the coupon is expired, and if I update my order then the coupon is recalculed but it's expired so the order doesn't have the discount now.
But I need to have the possibility to add / remove coupon after an order was done. How can I fix this ?
EDIT :
I think this is this one I need to modify :
/**
 * Rules condition: Check discount can be applied.
 */
 function commerce_discount_date_condition($discount_name) {
   $wrapper = entity_metadata_wrapper('commerce_discount', $discount_name);
   $time = time();

   return $time >= $wrapper->commerce_discount_date->value->value() && $time <=
   $wrapper->commerce_discount_date->value2->value();
 }

But how can I modify it without change the module files, I don't think that this function have a hook ?
And you say that I just have to add the uid 1, but I have some other person that are admin on the site and can modify orders, I think I can add a verification on the roles ?
EDIT 2 :
The function doesn't have a hook but the two functions that call it have one :
function commerce_discount_commerce_discount_rule_build($rule, $discount)

And
function commerce_discount_rules_condition_info()

I try to use these hooks in my module (with _alter and without) but they are not triggering, I don't know these functions maybe the rules function are called only certain times ?
Comment: You'll have to edit the coupon rule so it fired if coupon is not expired OR current user id is 1.
Comment: Can you look at my edit ? thanks.
Answer: If someone need to do the same thing as me, finally I compare the dates of the coupon with the order date, so if a user use a coupon on an order, when I edit it even if the coupon is expired the order still have it.
Here is how I proceed :
First I rewrite the condition 'commerce_discount_date_condition' :
  function mymodule_rules_condition_info_alter(&$conditions) {
      $conditions['commerce_discount_date_condition'] = array(
        'label' => t('Check discount dates'),
        'group' => t('Commerce Discount'),
        'parameter' => array(
          'commerce_discount' => array(
            'label' => t('Commerce Discount'),
            'type' => 'token',
            'options list' => 'commerce_discount_entity_list',
          ),
          'commerce_order' => array(
            'type' => 'commerce_order',
            'label' => t('Commerce order'),
            'description' => t('The order the discount would be applied to.'),
            'wrapped' => TRUE,
          )
        ),
        'base' => 'ga_registration_discount_date_condition',
      );
    }

I add in this condition the order on which the discount is, so I can use it in the 'base' function :
    function mymodule_discount_date_condition($discount_name, $order) {
      $wrapper = entity_metadata_wrapper('commerce_discount', $discount_name);
      dsm("cond");
      // Use the order time
      $time = $order->created->value();
      return $time >= $wrapper->commerce_discount_date->value->value() && $time <= $wrapper->commerce_discount_date->value2->value();
    }

This function use the order creation time to compare with the discount dates.
The last thing to do was to rewrite the whole commerce_discount_rule_build hook (The only thing that changes are in the end) :
function mymodule_commerce_discount_rule_build($rule, $discount) {
  $wrapper = entity_metadata_wrapper('commerce_discount', $discount);
  $discount_offer = $wrapper->commerce_discount_offer->value();
  $wrapper_discount_offer = entity_metadata_wrapper('commerce_discount_offer', $discount_offer);

  // Check if property is attached to commerce free shipping!
  if (isset($wrapper_discount_offer->commerce_free_shipping)) {
    if (!$shipping_service = $wrapper_discount_offer->commerce_free_shipping->value()) {
      // No need to change the rules event.
      return;
    }

    // Add missing parameter.
    foreach ($rule->actions() as $action) {
      if ($action->getElementName() == 'commerce_discount_free_shipping_service') {
        $action->settings['shipping_service'] = $shipping_service;
      }
    }
  }

  // Product level discounts must pass the line item's order.
  $map = array(
    'order_discount' => 'commerce-order',
    'product_discount' => 'commerce-line-item:order',
  );

  if (isset($map[$discount->type])) {
    // Add condition for per-person usage.
    if ($wrapper->discount_usage_per_person->value()) {
      $rule->condition(
        'commerce_discount_usage_max_usage_per_person',
        array(
          'commerce_discount' => $discount->name,
          'order:select' => $map[$discount->type],
          'usage' => $wrapper->discount_usage_per_person->value(),
        )
      );
    }
    // For normal usage.
    if ($wrapper->discount_usage_limit->value()) {
      $rule->condition(
        'commerce_discount_usage_max_usage',
        array(
          'commerce_discount' => $discount->name,
          'order:select' => $map[$discount->type],
          'usage' => $wrapper->discount_usage_limit->value(),
        )
      );
    }
  }

  if (!empty($discount->commerce_discount_date)) {

    $types = commerce_discount_types();
    $type = $types[$discount->type];
    // On désactive pas les règles des discounts
    $rule->active = TRUE;

    // Ajoute la condition
    $rule->condition('commerce_discount_date_condition', array(
      'commerce_discount' => $discount->name,
      'commerce_order:select' => $type['entity type'] == 'commerce_order' ? 'commerce-order' : 'commerce-line-item:order',
    ));

  }

}

What i change is all the things inside the last if, I always set the rule to active (normally rules are desactivated when the discount is expired), and I add to the rule the condition with the discount name and the order.
If I rewrite the whole hook it's because the $rule->condition add a condition, even if I add a condition with the same name it's added and not updated, so if I just use the hook without unset the base function I have the original condition and mine in the rule.
So, I unset the module only for this hook :
function mymodule_module_implements_alter(&$implementations, $hook)
{
  if ($hook == 'menu_alter') {
    // Move ga_registration_menu_alter() to the end of the list.
    $group = $implementations['ga_registration'];
    unset($implementations['ga_registration']);
    $implementations['ga_registration'] = $group;
  }
  if ($hook == 'commerce_discount_rule_build'){
    unset($implementations['commerce_discount']);
  }
}


Drupal web cluster with memcached. memcached failover?

Question: Running Drupal 7 sites (under Aegir) and I'm investigating a method to scale out the web boxes horizontally, so that any Apache server can process a request for any Drupal site. We're currently at ~50 Drupal sites on our platform. All sites also run through Varnish.
At the moment with our single-server setup I have memcached installed locally on the Apache box.
If we add further Apache boxes and each has their own memcached instance, it's likely that cached content in memcached will be different on each different host.
The way around this is to run memcached on our Varnish or database instance, though on our Varnish box makes most sense.
From the settings.php config I can presumably specify multiple memcached servers in the memcache_servers array:
// make MemCacheDrupal the default cache class
$conf['cache_default_class'] = 'MemCacheDrupal';

// Key Prefix: edit this for multisite use.
$conf['memcache_key_prefix'] = $databases['default']['default']['username'];

$conf['memcache_servers'] = array(
    '127.0.0.1:11211' => 'default',
);
How does Drupal choose which memcached server to use from this array?
What I'm looking for is the ability to specify a failover memcached server. So if the primary "shared" memcached instance is down, say we take our Varnish VM down for maintenance, then it starts using another cold memcached instance.
Or as an alternative is there a way for Drupal to failover to using the database cache instead of memcached?
Comment: memcached is distributed by nature, you don't need/want a shared central instance.
Comment: Nope, I don't want a shared central instance. I'd like a failover instance so our Drupal sites don't bork if they can't contact memcached. I'm not bothered about whether the standby instance is cold or not.
Comment: I was mainly wondering what the reason was for being able to specify an array of memcached servers in `settings.php`
Comment: That's because it's a distributed cache - [check out the memcache module's readme](http://cgit.drupalcode.org/memcache/tree/README.txt?id=HEAD) and [maybe something about consistent hashing](https://www.adayinthelifeof.nl/2011/02/06/memcache-internals/).
Comment: You may also consider `redis`.
Comment: You must specify all memcached servers in your settings in order for your cache to be consistent. There is a predictable hash algorithm used by all PHP instances.
Answer: If you might want to setup a memcache cluster, consisting of multiple servers. The idea is that you have more than one server in the cluster and if one of the servers is offline for some reason the others will be used.
This is fairly easy to setup and is documented in the memcache module as well, the config could look something like this:
$conf['memcache_servers'] = array(
  '10.0.0.1:11212' => 'default',
  '10.0.0.2:11212' => 'default',
  '10.0.0.3:11212' => 'default'
);
$conf['memcache_bins'] = array('cache' => 'default');

PHP will handle the clustering, so you wouldn't need to do anything. This means that if a server dies, that cache wont be available, but will automatically be generated on one of the other servers.
One of the ideas with memcache is that you can pool the memory of multiple servers to create a single shared pool.
In your example, you could also use your webservers as a memcache cluster, but that would require that the webservers can talk to each other. Usually when you require multiple servers, you also want to have separate memcache servers, so you can optimize the servers for their specific task.
Answer: Looks like you're wanting memcache replication. My recommendation is to use MySQL's memcache plugin to accomplish this replication. Also recommend using MySQL 5.7 if you're comfortable with using a non GA release for your caches.
Comment: Funnily enough I did think about that. I'm not really bothered about making sure the memcached content is persistent though. All I want to do is be able to have a cold failover memcached available should the primary go down. I think I will probably set it up through our haproxy load balancer and let haproxy take care of the failover to another instance.


how can I override a the textfield component in extjs and use it in multiple forms accross the app?

Question: I am thinking of creating a file called MyTextField.js in views and its contents are
Ext.define('MyTextField',
{

override: 'Ext.field.Input',
xtype: 'mytextfield',

    updateValue: function(newValue) {
        var input = this.input;
        if (input && input.dom.value != newValue) {
            input.dom.value = newValue;
        }
    }
});

And then use this in my other view FormView.js
Ext.define('AnotherScreen', {
    extend: 'Ext.form.Panel',
    xtype: 'anotherscreen',
    controller: 'controllerx',
    viewModel: 'viewmodelx',
     requires: [
        'MyTextField'
    ],
    layout: 'vbox',
    items: [
             { xtype : mytextfield}
    ]

});

But this is not working, it returns an error
**
Uncaught Error: [Ext.create] Unrecognized class name / alias:
MyTextField

**
Any idea is very welcome.
Answer: You have at least three issues, one of them is missing quotes around the xtype (should be xtype : 'mytextfield').
override tells Ext to override the old component. So Ext.field.Input is overridden with the updateValue function you defined. This changes every existing input field because they all derive from Ext.field.Input (e.g. textfield, combo etc.), but it does not create a new xtype by the name of "mytextfield". To create a new xtype, you extend an existing class (extend:'Ext.field.Input').
At last, the idea when using requires is that the path and name of the file and the qualified name of the view match. If you have an application called MyAppName, you define in app/view/MyTextField.js the component MyAppName.view.MyTextField. When you then use requires:['MyAppName.view.MyTextField'], the file path should be correctly resolved and you can reference the component by xtype from there on.
Comment: Thank you @Alexander, I thought you use the override but that did not work.
Comment: Thank you, this helped me modify my code. Now it works
Answer: I believe you should be using extend to create your custom class.
And in order for your class to be created using an xtype you should supply an alias.
Something like shown below should work:
Ext.define('MyTextField', {
    extend: 'Ext.field.Input',
    alias: 'widget.mytextfield',

    updateValue: function(newValue) {
        var input = this.input;
        if (input && input.dom.value != newValue) {
            input.dom.value = newValue;
        }
    }
});

Answer: I believe this should work. Whenever we are defining any class,
we should extend the parent class rather than overriding it.Please change the xxxx to the package names. when defining a class, it should always be a fully qualified name.
 Ext.define('xxx.xxxx.xxxx.MyTextField', {
            extend: 'Ext.field.Input',
            alias: 'widget.mytextfield',
            xtype: 'mytextfield',
            updateValue: function(newValue) {
                var input = this.input;
                if (input && input.dom.value != newValue) {
                    input.dom.value = newValue;
                }
            }
        });


Parseval's identity for Hilbert space-valued function.

Question: Let $\mathcal H$ be a (separable) Hilbert space on $\mathbb C$.
Suppose $f\in L^2([-\pi,\pi), \mathcal H)$ and $c_n(f)$ is n-th Fourier coefficient of $f$, i.e., $c_n(f)=\frac{1}{2\pi}\int_{-\pi}^\pi e^{-in x}\ f(x)dx.$
Then, I want to see why
$$\sum_{n\in\mathbb Z}\|c_n(f)\|_{\mathcal H}^2=\frac{1}{2\pi}\int_{-\pi}^{\pi}\|f(x)\|_{\mathcal H}^2dx.$$
(This is parallel with the Parseval's identity for complex-valued functions.)
My one idea is using Parseval for complex valued fct.
Let $\tilde f(x):=\|f(x)\|.$ Use Parseval to $\tilde f$, I get
$$\sum_{n}|c_n(\tilde f)|^2=\frac{1}{2\pi}\int_{-\pi}^\pi |\tilde f(x)|^2dx.$$
RHS=$\int_{-\pi}^\pi\|f(x)\|^2dx$ but I cannot see how I should handle LHS. If $|c_n(\tilde f)|=\|c_n(f)\|$ holds, I will come to conclusion but I cannot see $|c_n(\tilde f)|=\|c_n(f)\|$.
So parhaps this method doesn't work.
I would like you tell me how I can get the Parseval identity : $\sum_{n\in\mathbb Z}\|c_n(f)\|_{\mathcal H}^2=\frac{1}{2\pi}\int_{-\pi}^{\pi}\|f(x)\|_{\mathcal H}^2dx$, or tell me any effective reference.
Answer: Let $\{v_k\}_{k=1}^\infty$ be an orthonormal basis in $\mathcal{H}.$ For $f\in L^2([-\pi,\pi),\mathcal{H})$ consider the functionz $f_k$ defined by
$$f_k(x)=\langle f(x),v_k\rangle,\  -\pi\le x<\pi$$ Then
$f_k\in L^2([-\pi,\pi)).$ Moreover $c_n(f_k)=\langle c_n(f),v_k\rangle.$ By the Parseval identity we have
$$\sum_{n=-\infty}^\infty|\langle c_n(f),v_k\rangle|^2=\sum_{n=-\infty}^\infty |c_n(f_k)|^2\\ ={1\over 2\pi}\int\limits_{-\pi}^\pi |f_k(x)|^2\,dx={1\over 2\pi}\int\limits_{-\pi}^\pi |\langle f(x),v_k\rangle |^2\,dx$$ Thus, by the Parseval identity in $\mathcal{H}$ we get
$$\sum_{n=-\infty}^\infty\|c_n(f)\|^2=\sum_{n=-\infty}^\infty\sum_{k=1}^\infty |\langle c_n(f),v_k\rangle |^2\\ =\sum_{k=1}^\infty {1\over 2\pi}\int\limits_{-\pi}^\pi |\langle f(x),v_k\rangle |^2\,dx = {1\over 2\pi}\int\limits_{-\pi}^\pi  \|f(x)\|^2\,dx $$


Filter gridview

Question: I have a gridview which I am binding through code behind, I want to filter the gridview based on the value given by the user in textbox.
It would be great if I'll be able to filter the gridview without any postback.
PLease help!
Thanks in advance
Answer: you could run a filter expression
<asp:sqldatasource id="articles" runat="server"
   connectionstring="<%$ ConnectionStrings:aspa %>"
   selectcommand="SELECT title, url, added, updated FROM aspx_articles ORDER BY title"
   filterexpression="title LIKE '%{0}%' or url LIKE '%{0}%'">
   <filterparameters>
      <asp:controlparameter controlid="searchBox" propertyname="Text" />
   </filterparameters>
</asp:sqldatasource>

or this way
Do you have a TextBox outside the GridView, and when you enter data into it and press a button, the GirdView should be filter on that data?
If so, make sure your select command can taka a parameter with the value you want to filter on. Add a ControlParameter to the SelectParameters colelction of the DataSource control (if you use a DataSource control).
Here is an example that uses the Northwind database, maybe this will help you:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="Button" />
        <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"
            DataKeyNames="ProductID" DataSourceID="SqlDataSource1" ShowFooter="True">
            <Columns>
                <asp:CommandField ShowSelectButton="True" />
                <asp:BoundField DataField="ProductID" HeaderText="ProductID" InsertVisible="False"
                    ReadOnly="True" SortExpression="ProductID" />
                <asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName" />
                <asp:BoundField DataField="UnitsInStock" HeaderText="UnitsInStock" SortExpression="UnitsInStock" />
                <asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" SortExpression="UnitPrice" />
            </Columns>
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
            SelectCommand="SELECT [ProductID], [ProductName], [UnitsInStock], [UnitPrice] FROM [Alphabetical list of products] WHERE ([ProductName] LIKE '%' + @ProductName + '%')">
            <SelectParameters>
                <asp:ControlParameter ControlID="TextBox1" DefaultValue="%" Name="ProductName" PropertyName="Text"
                    Type="String" />
            </SelectParameters>
        </asp:SqlDataSource>

codes found here http://forums.asp.net/p/1034014/2904713.aspx
Comment: Hi Justin,
Thanks for your quick response, but I am binding gridview on server side and not with sql data source.
Comment: @Zerotoinfinite http://www.c-sharpcorner.com/UploadFile/khaledrawy/ICallBack05102008175418PM/ICallBack.aspx has a response to your problem with ajax update panel. how it is used im not sure, im still reading up on it. but sounds a lot like the post by MrGumbe
Answer: If you're using paging, I would recommend using something else (like the Microsoft Ajax Library's dataView).  Because gridview paging and client-side filtering wouldn't mesh too well.  But if you're not doing paging, you could do something similar to this or this.
Answer: The grid view is made for manipulation during post back. If you were to do this entirely on the client side, you'd use a JavaScript suite that would work on any table, not confined to the grid view. If it were me, I would simply use AJAX by wrapping the grid view and text box in an Update Panel. To the end user, the behavior is the same.
EDIT to include Sample code:
<asp:ScriptManager ID="ScriptManager1" AllowCustomErrorsRedirect="false"  runat="server"></asp:ScriptManager>

  <asp:UpdatePanel ID="UpdatePanel1"  runat="server">
    <ContentTemplate>

            <asp:TextBox runat="server" ID="txtFilterString" ></asp:TextBox>
            <asp:Button runat="server" ID="btnFilter" Text="FilterResults" onclick="btnFilter_Click" />

            <asp:GridView runat="server" ID="grdResults"
                DataKeyNames="Id"
                AllowSorting="true" AllowPaging="true" PageSize="20"
                PagerSettings-Mode="NumericFirstLast">
                    <Columns>
                        .....
                    </Columns>
                </asp:GridView>

  </asp:UpdatePanel>

Comment: Seems like a solution to me. Can you just briefly explain me what I have to do .

Filter gridview


Adding Server Block Breaks Subdomains NGINX

Question: I currently have all HTTP connections redirecting to HTTPS using the following server block:
server {
        listen 80 default_server;
        listen [::]:80 default_server;
        server_name _;
        return 301 https://$host$request_uri;
}

This works very well. I also have a webapp running on a subdomain using the following server block:
    server {
            listen 443 ssl;
            server_name gitea.pyrosoftsolutions.co.uk;
            ssl_certificate /etc/ssl/certs/gitea.pyrosoftsolutions.crt;
            ssl_certificate_key /etc/ssl/private/gitea.pyrosoftsolutions.key;
            ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
            ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';
            ssl_prefer_server_ciphers on;
            ssl_dhparam /etc/ssl/dhparam/gitea.dhparam.pem;
            proxy_cookie_domain ~(?P<secure_domain>([-0-9a-z]+\.)?[-0-9a-z]+\.[a-z]+)$ "$secure_domain; sec$
            location / {
                    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
                    add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inlin$
                    add_header X-Xss-Protection "1; mode=block" always;
                    add_header X-Content-Type-Options "nosniff" always;
                    proxy_pass http://localhost:3000/;
            }
    }

Which again, seems to work fine. However, I want to run a website on the default/www domains. The problem arises when I enable the following server block:
server {
        listen   443 ssl;
        server_name pyrosoftsolutions.co.uk www.pyrosoftsolutions.co.uk;
        root /var/www/pyrosoftsolutions.co.uk;
        index index.php index.html index.htm;
        location / {
                try_files $uri $uri/ /index.html;
        }

        error_page 404 /404.html;

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
                root /var/www/pyrosoftsolutions.co.uk;
        }

    location ~ \.php$ {
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            fastcgi_pass unix:/var/run/php7.0-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
        }
}

For some reason, when this block gets enabled, I can no longer access my subdomain, nor can I access any of the files/pages in the root directory. Any ideas?
Answer: It's not clear what the full configuration is, but seems to me that you need ssl_* directives in the problematic block.
Defining the SSL_CERTIFICATE and SSL_CERTIFICATE_KEY directives should solve your issues. It is not possible for nginx to serve HTTPS pages without a suitable certificate defined.


SQL UNION ALL only include newer entries from 'bottom' table

Question: Fair warning: I'm new to using SQL. I do so on an Oracle server either via AQT or with SQL Developer.
As I haven't been able to think or search my way to an answer, I put myself in your able hands...
I'd like to combine data from table A (high quality data) with data from table B (fresh data) such that the entries from B are only included when the date stamp are later than those available from table A.
Both tables include entries from multiple entities, and the latest date stamp varies with those entities.
On the 4th of january, the tables may look something like:
A____________________________          B_____________________________
entity  date     type   value           entity  date     type   value
X       1.jan    1      1               X       1.jan    1      2
X       1.jan    0      1               X       1.jan    0      2
X       2.jan    1      1               X       2.jan    1      2
Y       1.jan    1      1    (new entry)X       3.jan    1      1
Y       3.jan    1      1               Y       1.jan    1      2
                                        Y       3.jan    1      2
                             (new entry)Y       4.jan    1      1

I have made an attempt at some code that I hope clarify my need:
WITH
AA AS
(SELECT entity, date, SUM(value)
FROM table_A
GROUP BY
entity,
date),

BB AS
(SELECT entity, date, SUM(value)
FROM table_B
WHERE date > ALL (SELECT date FROM AA)
GROUP BY
entity,
date
)

SELECT * FROM (SELECT * FROM AA UNION ALL SELECT * FROM BB)

Now, if the WHERE date > ALL (SELECT date FROM AA)would work seperately for each entity, I think have what I need.
That is, for each entity I want all entries from A, and only newer entries from B.
As the data in table A often differ from that of B (values are often corrected) I dont think I can use something like: table A UNION ALL (table B MINUS table A)?
Thanks
Answer: Essentially you are looking for entries in BB which do not exist in AA. When you are doing date > ALL (SELECT date FROM AA) this will not take into consideration the entity in question and you will not get the correct records.
Alternative is to use the JOIN and filter out all matching entries with AA.
Something like below.
WITH
AA AS
(SELECT entity, date, SUM(value)
FROM table_A
GROUP BY
entity,
date),

BB AS
(SELECT entity, date, SUM(value)
FROM table_B
LEFT OUTER JOIN AA
   ON AA.entity = BB.entity
   AND AA.DATE = BB.date
WHERE AA.date == null
GROUP BY
entity,
date
)

SELECT * FROM (SELECT * FROM AA UNION ALL SELECT * FROM BB)

Answer: Use UNION instead of UNION ALL , it will remove the duplicate records
   SELECT * FROM (
                   SELECT *
                   FROM AA
                    UNION
                   SELECT *
                   FROM BB   )

Comment: The problem with this, I think, is that the old entries in A are not identical with the old ones in B (data in A is reviewed for errors and whatnot). How will UNION know to ignore changes..?
Comment: @Kjetil If the old entries in B are not same as A, then we should consider it as a new entry.. right?
Answer: I find your question confusing, because I don't know where the aggregation is coming from.
The basic idea on getting newer rows from table_b uses conditions in the where clause, something like this:
select . . .
from table_a a
union all
select . . .
from table_b b
where b.date > (select max(a.date) from a where a.entity = b.entity);

You can, of course, run this on your CTEs, if those are what you really want to combine.
Comment: The aggregation is over all values for one entity on a single date. Using table A, X has SUM(value) = 2 on 1. jan. More to the point: Doesn't the 'select max(a.date) from...' return a single max_date? I would like one for each entity...
Comment: @Kjetil . . . As I say in the answer, just run this using the CTEs you have defined.
Comment: I feel a bit sheepish as I didn't know that max() could return multiple values. Thanks so much for putting up with a noob.


Finding a recurrence relation for the Josephus problem if we're looking at the person before the person who lives

Question:
Consider the Josephus problem. Let $L(n)$ be the number of the next to
  last person left standing. Find $L(12)$ and $L(13)$. Derive a recurrence
  for $L(n)$.

I know that the Josephus problem is solved with the recurrence relation $f(2j) = 2(f(j)) - 1$.
But if the problem, as seen above, it switched to the person before the last person standing, how would I go about solving it? This question is really confusing me.
Comment: I think this is in Chapter 1 of *Concrete Mathematics* by Knuth, Graham, & Patashnik.
Answer: HINT: This is Problem $1.15$ of Graham, Knuth, & Patashnik, Concrete Mathematics. $L(1)$ is undefined, but otherwise $L$ satisfies the same recurrence as the Josephus function $f$:
$$\left\{\begin{align*}
&L(2)=2\\
&L(3)=1\\
&L(2n)=2L(n)-1&&\text{if }n\ge 2\\
&L(2n+1)=2L(n)+1&&\text{if }n\ge 2\;.
\end{align*}\right.$$
Break the integers into blocks of the form
$$\left[2^m+2^{m-1},2^{m+1}+2^m\right)\cap\Bbb Z\;:$$
$[11_{\text{two}},110_{\text{two}})$, $[110_{\text{two}},1100_{\text{two}})$, and so on. Each $n\ge 3$ can then be written in the form $$n=2^m+2^{m-1}+k\;,$$ where $$0\le k<2^{m+1}+2^m-\left(2^m+2^{m-1}\right)=2^m+2^{m-1}\;.$$
Now show that when $n$ is written in this fashion, $L(n)$ is a simple function of $k$.


How do I get a node by its ID?

Question: Using <code>{{ drupal_entity('node', '123', 'body') }}</code> in a template file, I can get the node body and title.
Is there a way to get all the available node properties?
Comment: The last parameter is a view mode, not a field name.
Answer: The general solution is to preprocess the node.
If you want to avoid coding PHP, you can use Twig Tweak, which has a handy list of twig commands it adds:
Drupal Entity
<code>{# Print a content block which ID is 1. #}
{{ drupal_entity('block_content', 1) }}

{# Print a node's teaser. #}
{{ drupal_entity('node', 123, 'teaser') }}

{# Print Branding block which was previously disabled on #}
{# admin/structure/block page. #}
{{ drupal_entity('block', 'bartik_branding', check_access=false) }}
</code>
Drupal Field
<code>{{ drupal_field('field_image', 'node', 1) }}

{{ drupal_field('field_image', 'node', 1, 'teaser') }}

{{ drupal_field('field_image', 'node', 1, {type: 'image_url', settings: {image_style: 'large'}}) }}
</code>
Comment: One more way is using `view` filter as follows
`{{ node.body|view }}`

How do I get a node by its ID?


Use different comment template for replies-to-top-comment

Question: I tried to make StackExchange-like comment section with different template for the comment replies. I create two template for both top-level comment and its replies. This is the result of the two comment.tpl.php file rendered and then collated in GIMP.

This is comment.tpl.php used for top comment contained in cyan box.

  <div<?php print $attributes; ?>>

      <?
        print render($avatar) . "
";
        print $commenter_name . "
";
        print $creation_date;
      ?>

    <?php
      hide($content['links']);
      print render($content['comment_body']);
      print render($content['links']);
    ?>

While this is comment.tpl.php used for comment reply contained in yellow box.

  <div<?php print $attributes; ?>>
  <?php
    print render($content['comment_body']);
    print " - " . $commenter_name;
    print render($content['links']);
   ?>

If i use one of these template, it will effect ALL the comments as shown below.

I know I can change the style rudimentarily via theme css as suggested in this question, but going by this route means that I have to create one-size-fit-all template for both case that won't be pretty.
My question is: Is there any template file I missed or any other strategy that I can employ to make separate template that will target only the replies-to-top-comment?
Answer: I manage to solve this problem by exploiting the pid (parent ID) value in the $comment variable. First, I check if the corresponding comment is a top-level comment. It is a top level comment if the pid value is 0. The code inside comment.tpl.php so far is:
if ($comment->pid == 0) {
  // Top level comments code here
} else {
  // Replies to comments code here
}

The code above will split the template programatically already, but it will be better if I worked at two separate files for the two cases. To do this, I used drupal_get_path function to point every case inside comment.tpl.php to their corresponding template.
In my case, I create these two templates inside my theme folder:

/templates/comment/comment-top.tpl.php for the top comment
/templates/comment/comment-reply.tpl.php for the replies

The code inside comment.tpl.php then become:
if ($comment->pid == 0) {
  include drupal_get_path('theme', 'mytheme') .
    '/templates/comment/comment-top.tpl.php';
} else {
  include drupal_get_path('theme', 'mytheme') .
    '/templates/comment/comment-reply.tpl.php';
}

Of course change the mytheme in the code to your theme name.
To finish off, I pasted the template I posted above in the question to the corresponding template. It will render the template properly with all the variables you define inside the preprocesses function working.


Some special tests for convergence.

Question: Please, I need some explanations on some special tests for convergence of a series.
For example, the ratio test, comparison test and root test.
Ratio test: let the limit as $n$ tends to $\infty$ of $\frac{|U_{n+1}|}{|U_{n}|}=L$, now if $L<1$, the series converges and if $L>1$, it diverges. If $L=1$, The test is inconclusive.
Comparison test: Is also a test for convergence of a series by considering a series that converges already in such a way that $U_n\le V_n $. Where $\sum U_n$ is the series that we are to test its convergence while $\sum V_n$ is a convergent series already.
Root Test: let the limit as n tends to $\infty$ of $\sqrt[n]{|U_{n}|}=L$, now if $L<1$, the series converges and if $L>1$, it diverges. If L=1, The test is inconclusive.

What is confusing me is when to make use of this test when a series is given, I mean which one to use.
  For example, consider the series $\frac{n}{(2n+1)(2n-1)}$. Here, we can use the comparism test and also the ratio test but one diverges and  while the other test fails. So, in this case and some other cases too, how am I going to know the series required?
Comment: You must have done something wrong with your example. The ratio test is inconclusive for that series.
Comment: Oops! Sorry, that was a mistake. The ratio test fails when I tried it but the comparison test diverges.
Answer: It is not easy to give an effective answer but here are some ideas.
1) The ultimate test is comparison. All others are particular cases of it. So, in terms of power this is the one. But it is not easy to guess with what to compare.
2) The ratio test (in the form you wrote them) is slightly more powerful than the root test. This is because $\lim \frac{a_{n+1}}{a_n}=L$ implies $\lim \sqrt[n]{a_n}=L$. But this is only about the existence of the limit. If you replace $\lim$ by $\limsup$ then both are equivalent.
3) Both the ratio and the ratio test are equivalent to using comparison with the series $\sum_n q^n$ for some $q$. So comparing with geometric series is as good as ratio and root test.
4) To use the comparison test it is good to have a good collection of series that we know about. Geometric $\sum_n q^n$, Harmonic, $\sum_n \frac{1}{n^r}$, and maybe some slower convergent/divergent series $\sum_n \frac{1}{n^r\ln(n)}$, $\sum_n \frac{1}{n^r\ln(n)\ln\ln(n)}$, ...
5) Finally, in the ratio and root test one must compute a limit. Since the two methods are essentially equivalent one chooses according to what resulting limit is more comfortable to compute.
In your example, there are mainly multiplications in the term, and constant exponents. Let us use ratio test (just because the limit is probably simple to compute and because maybe we don't know with what to compare. After all, applying ratio test is kind of mechanic).
We compute $\lim \frac{\frac{n+1}{(2(n+1)+1)(2(n+1)-1)}}{\frac{n}{(2n+1)(2n-1)}}=1$.
Therefore the ratio test is inconclusive. There is no need to bother with the root test, as we know it will give the same answer. There is no need to compare with a geometric series as we know it will also give the same answer. So, checking the ratio test might not be a waste of time after all since it is telling us a few other techniques that will not work. So we go to compare with slowed converging/diverging series. the next in the collection are $\sum_n \frac{1}{n^r}$. Compare with them, maybe use the limit form of the comparison test. Enforce that the limit exists and is not zero. This will tell you that the right value for $r$ is $1$. So comparing with $\sum \frac{1}{n}$ gives us the answer. We should get that $\sum \frac{1}{n}$ and our series both converge or diverge. Since $\sum\frac{1}{n}$ diverges so does our series.
So, although in general it is not possible to tell an algorithm, for text-book examples and exam questions the methodology is rather mechanic. Most books and teachers don't point it out, thought. I think it is because they think exposing the mechanics of the process may subtract from the self-proclaimed beauty of mathematics. But the truth is that successful students are those that manage to grasp the mechanics of it.

The ultimate goal in mathematics is to eliminate any need for intelligent thought.
Alfred N. Whitehead

Some special tests for convergence.


Equivalence of norms in finite-dimensional spaces

Question: Assume we have a separable, reflexive Banach space $X$ such that $\{e_{i}\}$ is a basis.
Let $X_{n} = \text{span}\{e_{1},\ldots,e_{n}\}$ be finite-dimensional subspaces where we define members $u_{n} \in X_{n}$
by $u_{n} = \sum_{k=1}^{n}c_{k}^{n}e_{k}$ where $c^{n} = (c^{n}_{1},...,c^{n}_{n}) \in \mathbb{R}^{n}$. What I want to know is if it is true that for all $R_{o} > 0$
there exists a $S \in \mathbb{R}$ such that for all $c^{n} \in \mathbb{R}^{n}$ where $|c^{n}|=S$(using the usual norm in $\mathbb{R}^{n}$) it follows that
$\Vert u_{n} \Vert_{X} = R_{o}$(using the norm of $X_{n}$)? (the reals are denoted as $\mathbb{R}$)
I am trying to use this idea in a larger proof.
The proof that I am referring to is the Browder and Minty Theorem. It uses the following Lemma:

The First step of the proof of the Theorem is as follows:

The part of the proof of the Theorem I don't follow is how you can apply Lemma 1.11 directly by considering '$c^{n} \in \mathbb{R}^{n}$ with $\Vert u_{n} \Vert_{X} = R_{o}$' instead of $\forall x \in \mathbb{R}^{n}$ with $|x| = R$ as is the requirement of the Lemma 1.11. I thought my idea above would resolve this.
Comment: Perhaps I'm missing something here, but I think this gives you a counter example: Suppose that $X_n = X = \Bbb{R}^2$ endowed with the Euclidean norm, $e_1 = (1,1)$, and $e_2 = (0,1)$. Then for any $S > 0$, $\| Se_1 \| = \sqrt{2}S$ and $\|S e_2 \| = S$.
Comment: @Tom I don't quite see how this is a counter-example. Maybe you could label it in line with my notation?
Comment: It seems that you want $\Vert u_{n} \Vert_{X}=f(|c^{n}|)$ for some function $f$. That is certainly false: the norm from $X$ may restrict to $\max_k|c_k^{n}|$ on $X_n$, and that is certainly not a function of $|c^{n}|$ since you can have vectors with the same Euclidean length but different max coordinates.
Comment: @Conifold Yes I think that is a good way stating what I was looking for. Could you see the updated question, I have added attachments which show the Lemma and Theorem that inspired the question. Any insight would be much appreciated.
Answer: You should reconsider the idea. Nothing like this is true in general. A few remarks:

The complicated condition $\forall R_0\ \exists S$ is redundant. Norms respect the scaling of vectors. (If you know which vectors have norm $1$, you know everything about the norm.) So, if the  condition $\forall R_0\ \exists S$ holds, you can state is more simply: there is $k>0$ such that $\|u_n\|_X = k\, |c^n|$.
The equivalence of two norms (denoted $\|\cdot\|$ and $\|\cdot\|_*$) is usually understood as the existence of $C$ such that for every vector $v$, $\|x\|\le C\|x\|_*$ and $\|x\|_*\le C\|x\|$. This is substantially weaker than 1.
But even the condition stated in item 2 will fail, unless your $X$ is a Hilbert space in disguise. Take $\ell_p$ for $p\ne 2$, with the standard basis. The $\ell_p$ norm of $(1,1,\dots,1)\in X^n$   is $n^{1/p}$, while the Euclidean norm is $n^{1/2}$. Since $n$ can be arbitrarily large, the ratio of two norms is not controlled as in item 2.
Comment: Thanks for your response. I have updated the question to show the Browder and Minty Theorem that inspired the question. Can you see how to resolve this problem?


How many times is a view used

Question: Recently i'been assigned to a drupal project already in development. I need to change a view but the site is quite complex. Is there a way to know how many times is a view being used?
Thank you all
Answer: Views Usage Audit
From project page:

This module can help you refactor a Drupal codebase by locating redundant views and displays or simply improving your understanding of what views are used where.
  It achieves this by logging where views get executed. You can then run reports from drush or through the UI
Answer: when you say "how many times" you probably mean "in how many 'places' in the site" the view is being used to display data...Right?
Well, an easy way to do this is to check how many and what kind of displays this view has. You can see this in the edit page of the view, it is the bar above the main view "frame", with each tab denote a different display. These displays can be of different type, such as "page", "block", "context" etc.
In case of pages, you just check the corresponding view "frame window". There you can find the node number (url) or the alias.
In case of blocks, go to the block page, find the corresponding (produced) block (it's name can be found on the views edit page) , go to it's edit page, and there you can see various information about the "places" (regions, zones etc) where the block is being displayed. Also you can find in which nodes, for which roles etc.

How many times is a view used


Continuous proof question

Question: Let f : [0, ∞) → R be a continuous function and let g : [0, ∞) → R be the function
defined by
g(x) = sup{f(y) | y ∈ [0, x]}.
Prove that g is also continuous.
I tried using the Intro to Real Analysis text to complete this proof but I am unsure of how to manipulate the supermum.
I know that I need to show that g is increasing, but then I do not know where to go from there.
Any help would be appreciated.
Answer: I would prove the contrapositive: if $g$ is discontinuous at $x_0$, then so is $f$. Indeed, showing $g$ is increasing is of great help because discontinuities in increasing functions need to be jump discontinuities. In particular (with the exception of the special case $x_0 = 0$) we must have
$$\lim_{x \to x_0^-} g(x) < \lim_{x \to x_0^+} g(x).$$
These one-sided limits exist essentially by the continuous version of the monotone convergence theorem. From the left, the function is increasing and bounded above by $g(x_0 + 1)$. From the right, the function is decreasing, bounded below by $g(x_0/2)$ (I didn't choose $x_0 - 1$, just in case $x_0 \in (0, 1)$).
On the other hand if $x_0 = 0$, then the only way that we can have a discontinuity is if
$$f(0) = g(0) < \lim_{x \to 0^-} g(0).$$
This needs to be dealt with as a separate case.
If $x_0 > 0$, then let the left limit of $g$ be $L$ and the right limit be $R$. I would suggest proving that $f(x) \le L$ for all $x \in [0, x_0]$, implying that $\lim_{x \to x_0} f(x) \le L$ if such a limit exists. But, on the other hand, for any $n \in \Bbb{N}$, there must exist some $x_n \in [0, x_0 + 1/n]$ such that $f(x_n) \ge R$. This implies that $\lim_{x \to x_0} f(x) \ge R$ if it exists. Thus, the limit cannot exist, hence $f$ cannot be continuous at $x_0$.
I'll leave the $x_0 = 0$ case to you, as well as filling in the blanks! Let me know if you need more help.

Continuous proof question


How to display body content in custom text?

Question: How to display body content in this line?
I had tried "content_body" and "field_body" but doesn't work.
The script below is inserted in "Configure field: Global: Custom text"

            [field_image]

[title]

[field_categories]

[content_body]

Answer: Under the custom text box, if you click on "Replacement Patterns" it will show you all the patterns you can use.
Should be [body]
Also, make sure all the other fields are arranged above the Global: Custom text or else the pattern will not work.


Question on greatest integer function.

Question: If $ y = [2x-1] = 3[x-6] $
Find the possible values of $ [3x+y] $.
My attempt :
$y = [2x]-1 = 3[x]-18 $.
Now I don't understand what to do with [2x] as I can't take 2 out of the greatest integer function. I tried writing x = [x] + {x} but that does not work.
Pls help me.
Comment: @SakethMalyala it is.
Comment: @HAMIDINESOUMARE oops just realized
Comment: Is it clear now, @Md Masood?
Answer: Try to write $x = [x] + \{x\}$, where $0\le\{x\}<1$ is the "fractional part" of $x$.
So, you'll have $[2x-1] = [2[x] + 2\{x\}-1] = 2[x]-1+ [2\{x\}]$,
and $3[x-6] = 3[[x] + \{x\} -6] = 3[x] -18+ 3[\{x\}] = 3[x] -18$.
Now you can consider the cases $[2\{x\}] = 0$ or $1$.

Question on greatest integer function.


I'm trying to generate a random word from my array with a button click

Question: So far I get a random word from the list every time I refresh the page, however I want to be able to generate a random word in the textbox with the "show" button. How do I do that? I suppose I should switch out document.write with something else? I've tried onclick instead but it did not work.

var words = [
  'Hello',
  'No',
  'Hi',
  'Banana',
  'Apple'
];

function randomWord(words) {
  return words[Math.floor(Math.random() * words.length)];
}

for (var x = 0; x < 1; x++)
  document.write(randomWord(words));
<form name="f1">
  <input type="text" value="" name="textbox" id="textbox" />
  <input type="button" value="show" onclick="randomWord()" />

</form>

Answer: These are a few things you need to follow.

Never use document.write().
Don't self close
 tags.
Use event listeners.
Use the scoping correctly. Remove the var here.
Use the parameters wisely. You don't need the parameter here, which makes the global variable, a local one and you aren't passing the value too.

You aren't clear where to show the words. So, I assumed that you wanna show it in the <input />.

words = [
  'Hello',
  'No',
  'Hi',
  'Banana',
  'Apple'
];

function randomWord() {
  document.getElementById("textbox").value = words[Math.floor(Math.random() * words.length)];
}
* {font-family: 'Segoe UI';}
<form name="f1">
  <input type="text" value="" name="textbox" id="textbox" />
  <input type="button" value="show" onclick="randomWord()" />

</form>

Answer: You should avoid adding event handlers in view. Instead, use addEventListener.
You should avoid document.write reason
You should also not pass words array as parameter. That can be a part of function that return randomWord

function getRandomWord() {
  var words = [
    'Hello',
    'No',
    'Hi',
    'Banana',
    'Apple'
  ];
  var randomIndex = Math.floor(Math.random() * 10) % words.length;
  return words[randomIndex];
}

function print(str) {
  document.getElementById('new').innerHTML = str;
}

function process(){
  var word = getRandomWord();
  print(word)

}
process()
document.getElementById('btnShow').addEventListener('click', process);
<form name="f1">
  <input type="text" value="" name="textbox" id="textbox" />
  <input type="button" value="show" id="btnShow" />

</form>


Logic Pro: can't see the loop checkbox in track info

Question: please see attachment. Can't see the loop checkbox under the 'mute' one: how to?
Answer: Just found out: cycle mode was active. When active, no loop checkbox.


How can the mAP metric be meaningful for non-exhaustively labeled datasets (such as YouTube BoundingBox)?

Question: I am interested in reproducing the object detection results found in the whitepaper describing the YouTube BoundingBox dataset (https://arxiv.org/pdf/1702.00824.pdf). What I don't understand is how the authors can use the Mean Average Precision (mAP) metric to evaluate/train their network when using YouTube BoundingBox? As I understand it, precision is evaluated for object detection as:
precision = true_positives / (true_positives + false_positives)
While this makes a lot of sense for exhaustively labeled datasets like COCO, YouTube BoundingBox only tracks a single object over a few frames. To see an example of this, observe the zebra example in Figure 1 of the paper I link to above. While there are 5+ visible zebras in the frame, only one has a labeled bounding box. This means that even if the detection network was working exactly as a human would (observing and marking all of the zebras as zebras), it would have a low mAP as all of the non-labeled zebras would be considered as false positives.
Am I misunderstanding mAP, the training/evaluation method the paper used, or something else? If I am correct then it is pretty weird that Faster-RCNN can learn to recognize only the labeled object and ignore non-labeled objects. Perhaps this means that it learns the kind of objects that the human annotators were initially drawn to.
Answer: Basically, when calculating metrics, it pretends those unlabeled zebra no exist. (assuming COCO might also misses a 90% hidden zebra).
Eventually, the model might predict some unlabeled zebra as zebra, while the metrics think it's wrong. (which is not ideal) The hope is that, most frames are single object, hence labeled correctly. And the model, like human, learns to ignore some wrong knowledge.
Comment: But my point is that COCO is exhaustively labeled. That means that it would not miss the existing zebras in the frame, and therefore is correct in contrast to YouTube BoundingBox. The point about most frames containing a single object is well taken since that might mean that the model wouldn't be constantly presented with false-false-positives (incorrect false positives from unlabeled objects), but still the lack of exhaustive labeling fundamentally is a weakness in this dataset it sounds like.


Proof by induction: $(1+\alpha)^n\ge 1+n\alpha +\frac{n(n-1)}{2}\alpha ^2$

Question: so I have this problem. It asks me to prove an expression by induction.

Let $n$ be a positive integer, and $\alpha$ any nonnegative real
number. Prove by induction that$$(1+\alpha)^n\ge 1+n\alpha
 +\frac{n(n-1)}{2}\alpha ^2$$

So I let $G(n) = (1+\alpha)^n\ge 1+n\alpha +\frac{n(n-1)}{2}\alpha ^2$. I showed the initial case when $n=0$ and got $1=1$. I then assume $G(k)$ is true $G(k) = (1+\alpha)^k\ge 1+k\alpha +\frac{k(k-1)}{2}\alpha ^2$. I then try to prove $G(k+1)$ is also true. $G(n) = (1+\alpha)^{k+1}\ge 1+(k+1)\alpha +\frac{(k+1)k}{2}\alpha ^2$. However, this is where I am stuck. I'm not sure where to go from here. Thanks.
Comment: Hint: $(1+\alpha)^{k+1}=(1+\alpha)^k(1+\alpha) \geq ?$
Comment: @Asydot $1+(k+1)\alpha + \frac{(k+1)k}{2}\alpha ^2$ ?
Comment: Yes, just by induction hypothesis.
Answer: You have
$$\begin{align}
(1+\alpha)^{k+1}&=(1+\alpha)(1+\alpha)^k\\\\
&\ge (1+\alpha)\left(1+k\alpha+\frac{k(k-1)}{2}\alpha^2\right)\\\\
&=1+(k+1)\alpha+\frac{k(k+1)}{2}\alpha^2+\frac{k(k-1)}{2}\alpha^3\\\\
&\ge 1+(k+1)\alpha+\frac{k(k+1)}{2}\alpha^2
\end{align}$$
since $\alpha\ge 0$ and $k\ge 1$.
Answer: Here's a proof by induction
showing that
the inequality is true
for any fixed size initial part
of the binomial theorem.
Theorem:
For fixed $m$
and $n \ge m$,
if $x \ge 0$ then
$(1+x)^n
\ge \sum_{k=0}^m x^k\binom{n}{k}
$.
Initial case:
Expand
$(1+x)^m$
manually.
You will get
$(1+x)^m
=\sum_{k=0}^m x^k\binom{n}{k}
$.
Suppose true for $n$.
Then
$\begin{array}\\
(1+x)^{n+1}
&=(1+x)(1+x)^{n}\\
&\ge(1+x)\sum_{k=0}^m x^k\binom{n}{k}\\
&=\sum_{k=0}^m x^k\binom{n}{k}+\sum_{k=0}^m x^{k+1}\binom{n}{k}\\
&=\sum_{k=0}^m x^k\binom{n}{k}+\sum_{k=1}^{m+1} x^{k}\binom{n}{k-1}\\
&=1+\sum_{k=1}^m x^k(\binom{n}{k}+\binom{n}{k-1})+x^{m+1}\binom{n}{m}\\
&=1+\sum_{k=1}^m x^k\binom{n+1}{k}+x^{m+1}\binom{n}{m}\\
&=\sum_{k=0}^m x^k\binom{n+1}{k}+x^{m+1}\binom{n}{m}\\
&\ge\sum_{k=0}^m x^k\binom{n+1}{k}\\
\end{array}
$


Python - how to convert a 24-bit PNG image to 32-bit using Open-cv or PIL

Question: I want to convert a 24-bit PNG image to 32-bit so that it can be displayed on the LED matrix. Here is the code which I have used, but it converted 24-bit to 48-bit
import cv2
import numpy as np
i = cv2.imread("bbb.png")
img = np.array(i, dtype = np.uint16)
img *= 256
cv2.imwrite('test.png', img)

Comment: Can you explain what is the LED matrix you're speaking about. The conversion will mostly depend on the 32bits representation that this hardware expects as input.
Comment: Right, right. Then the problem may be the constant.. should multiply by `2 ** 2` or `2 ** 4` per channel instead of `2 ** 8` per channel. But then I am puzzled by the `32-bit` representation, not divisible by 3. Perhaps all he needs to do is to add an `alpha` channel?
Comment: What make/model is this LED matrix please? 32-bit data normally means 8 bits each of RGBA, and it seems unlikely that an LED would display an alpha channel. Or 32-bits means CMYK which is also pretty unlikely for an LED. Please also share your image.
Comment: LED matrix is a 32X18 RGB leds matrix, everything is already setup, I am stuck at converting the image to a compatible so that it can work
Comment: If we can somehow convert the image from 24-bit to 32-bit, then it can be shown on Led matrix
Comment: To clarify, do you have an array of LEDs that is 32 wide by 18 tall?
Comment: I am a bit doubtful that the above code converts from 24-bit to 48-bit. Anyway, you would probably need an appropriate container. Have you tried just changing dtype to `dtype=np.uint32`? The `256` constant should be OK, if the input is 24-bit.
Comment: @norok2 3-channel images of 8-bits per code value are commonly referred to as 24-bit color. It's less common to refer to a 3-channel image of 16-bits per code value as a 48-bit image. I think the OP wants 10-12 bits per code value packed into a 16 bit container, but it's unclear.
Comment: @NateTheGrate yes it is an array of 32 width and 18 height
Comment: After trying dtype = np.uint32 I have got this error "cv2.imwrite('test.png', img)
TypeError: img data type = 8 is not supported"
Comment: I have used this script for LED matrix: http://aoakley.com/articles/2015-11-18-raspberry-pi-christmas-led-matrix.php
Comment: I don't see any reference to a 32bit color depth requirement for this hardware. I looked [here](https://learn.adafruit.com/neopixels-on-raspberry-pi/software) and [here](http://aoakley.com/articles/ledmatrix.py.php). Their code uses a Color class that takes 3 channels with value ranging from 0 to 255, so 24bits.
Answer: I looked at the christmas.png image in the code you linked to, and it appears to be a 624x8 pixel image with a palette and an 8-bit alpha channel.
Assuming the sample image works, you can make one with the same characteristics by taking a PNG image and adding a fully opaque alpha channel like this:
#!/usr/local/bin/python3
from PIL import Image

# Load the image and convert to 32-bit RGBA
im = Image.open("image.png").convert('RGBA')

# Save result
im.save("result.png")

I generated a gradient image and applied that processing and got this, so maybe you can try that:
Answer: I think you have confused the color bit-depth with the size of the input image/array.  From the links posted in the comments, there is no mention of 32 as a bit depth. The script at that tutorial link uses an image with 3-channel, 8-bit color (red, green, and blue code values each represented as numbers from 0-255). The input image must have the same height  as the array, but can be a different width to allow scrolling.
For more on bit-depth: https://en.wikipedia.org/wiki/Color_depth
Comment: Actually, I have tried christmas.png and it worked but I have converted another picture into any width but 18 height just like christmas.png but it didn't work
Comment: Then I have checked its details and one thing I have got is that both pics had different bit depths, so I thought, may be it can be solved if pics have bit depth like the working pic
Comment: Oops! I had the wrong answer then. Mark Setchell's answer will probably work for you then. You should edit those details / your debugging steps / the specific error into the question, for future reference.


Prove that the longest chord in an ellipse is its major axis.

Question: It is easy to prove this by taking point $(a\cos\theta, b\sin\theta)$ on $\dfrac{x^2}{a^2} + \dfrac{y^2}{b^2} = 1$. But I am looking for purely geometric proof without using trigonometry or coordinates.
It tried it by using triangle inequality: I took an arbitrary point $P$ on the ellipse with foci $S_1$, $S_2$ and centre $C$. Then we get (by using triangle inequalities two times)
$$
CP < a + ae,
$$
where $a$ is major axis and $e$ eccentricity. But it is not exactly that I want. If somehow I could show $CP < a$, then I would be done.
Please help.
Answer: Let $PQ$ be any chord of the ellipse.
From triangle inequality we have:
$$
S_1P+S_1Q\ge PQ\quad\text{and}\quad S_2P+S_2Q\ge PQ,
$$
where equality holds only if $PQ$ passes through $S_1$ or $S_2$.
If $PQ$ doesn't pass through both foci we have then:
$$
S_1P+S_2P+S_1Q+S_2Q> 2PQ,\quad\text{that is:}\quad 2a> PQ,
$$
Q.E.D.


How can I tell when a Mac switches access points?

Question: I want to be able to tell when a MacBook (running OS 10.5) switches from one wireless access point to another.
In the building I am in, with several wireless access points (all Airport Extremes, all with the same SSID), the computer shows that it is connected in a certain room but does not act as though it is.  [I'm still verify that it acts as though it is on the network in other locations.]
When I do
ping -a a_local_ip

then I expect to get a steady metronome of audible pings (and do, in some areas), but in the suspect room, instead of getting beep ... beep ... beep ... beep, I get .........beeep......beep...beep.beep.beep........  Looking at the ping times, they go from 3 ms to 82466.303 ms.    (I've also got a 15% packet loss).
Is there a log I can tail or any other way to determine when I change wireless access points, so I can determine if it is the computer's wireless card, or something wrong with the access point?
Answer: Hold down the option key and click on the wireless icon on the menu bar.  It should show you the SSID, channel, and Hardware address of the access point you are connected to. Source
Comment: Very cool.  I wish it would update in real time, though.
Comment: +1 for the Hardware Address
Answer: I got some mileage out of doing this:
while true ; do /System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -I | grep BSSID ; sleep 1 ; done

or
while true ; do clear ; /System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -I ; sleep 1 ; done


ListView com JSON + PHP

Question: Quero que apareça numa ListView todas as informações de um select que dei. Consigo fazer apenas com o txt aparecendo uma informação:
public void sendjsonrequest() {
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, HOST, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {

            try {

                contrato = response.getString("contrato");
                tipo = response.getString("tipo");
                horario = response.getString("horario");

                //txtContrato.setText(contrato);
                //txtTipo.setText(tipo);
                //txtHorario.setText(horario);
            } catch (
                    JSONException e)

            {
                e.printStackTrace();

            }
        }

Estou com dúvida de como inserir essas informações em um ListView.
contrato = response.getString("contrato");
tipo = response.getString("tipo");
horario = response.getString("horario");

Comment: Poderia esclarecer melhor onde o PHP entra nessa história e qual a relação dele com o problema?
Comment: Faço uma conexão do Json com o PHP onde no servidor tem um arquivo PHP com o SELECT. Minha duvida e como pegar as String "contrato, tipo e horário" e colocar numa ListView para aparecer mais de 1 dado na tela. Atualmente estou usando uma TextView para mostrar o resultado mas aparece so 1.
Comment: a tag php não faz sentido pra essa pergunta
Answer: Para aparecer esses três dados, crie um objeto e preencha ele com esse retorno do seu código php.
public class MeuObjeto {
    private String Contrato, Tipo, Horario;
}

A seguir, crie uma lista com esses objetos; utilize o conceito de Recyclerview pra criar um listview com esses dados.
Comment: Obrigado funcionou !
Comment: Pode marcar como resposta :)

ListView com JSON + PHP


FormJSON PHP para CURL ,

Question: Como passar de ...

file_get_contents()

para CURL ou Guzzle
<code>$content = http_build_query(array(
'oid' => '00SH1000000ASZF',
'retURL' => 'https://www.site.com.br/',
'first_name' => $nome,
'last_name' => $sobrenome,
'cpf__c' => rmCaracter($f['cpf']),
'mobile' => rmCaracter($f['phone']),
'email' => $f['email'],
'type__c' => 'HAB',
'Lead_Source' => 'Website Concessionaria',
'sub_source_media__c' => 'Site',
'dealer_code_interest__c' => '137492',
'opt_in_email__c' => '1',
'opt_in_phone__c' => '1',
'model_interest__c' => $f['model'],
));

$context = stream_context_create(array(
'http' => array(
'method'  => 'POST',
'content' => $content,
)
));

$result = file_get_contents('https://webto.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8', null, $context);
</code>
Estou recebendo um erro em $result .::

Warning:
  file_get_contents(https://webto.salesforce.com/servlet/servlet.WebToLead…):
  failed to open stream: HTTP request failed! HTTP/1.1 400 TLS 1.1 or
  higher required in
  /home/storage/9/8e/3d/teste1124/public_html/tpl/site.php on line 124

Acredito ser a Solução pois, ... Se eu ponho a url desse webservice no action de um form e envio os mesmos dados, não tenho o erro,  mas da forma que montei meu json , sim tenho esse erro ai.
Meu Form + Json = https://pastebin.com/mvai8JP7

A maioria dos alojamentos agora bloqueia o parâmetro furl_open que
  permite usar file_get_contents() para carregar dados de um URL
  externo. Acho que posso usar CURL ou uma biblioteca de clientes PHP
  como Guzzle, como solução.
Comment: [Edite](https://pt.stackoverflow.com/posts/256314/edit) sua pergunta e esclareça seu problema, pois da maneira como está não da para entender.
Comment: @Wéllingthon M. de Souza Preciso mudar o meu JSON para CURL  pois ... Acredito ser a Solução pois, ... Se eu ponho a url desse webservice no action de um form e envio os mesmos dados, não tenho o erro, mas da forma que montei meu json , sim tenho esse erro ai.
Comment: @Articuno   Pode ajudar sabe ........  Não estou conseguindo !
Answer: Utilizando cURL ficaria assim:
<code>$content = array(
  'oid' => '00SH1000000ASZF',
  'retURL' => 'https://www.site.com.br/',
  'first_name' => $nome,
  'last_name' => $sobrenome,
  'cpf__c' => rmCaracter($f['cpf']),
  'mobile' => rmCaracter($f['phone']),
  'email' => $f['email'],
  'type__c' => 'HAB',
  'Lead_Source' => 'Website Concessionaria',
  'sub_source_media__c' => 'Site',
  'dealer_code_interest__c' => '137492',
  'opt_in_email__c' => '1',
  'opt_in_phone__c' => '1',
  'model_interest__c' => $f['model'],
);

$context = http_build_query($content);
$url = 'https://webto.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8';

// Abre a conexão
$ch = curl_init();

// Seta a URL, método como POST, e os dados a ser enviado
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $context);

// Executa
$result = curl_exec($ch);
echo $result;

// Fecha a conexão
curl_close($ch);
</code>

Obs.: Não foi possível fazer o teste, pois no momento não estou em um computador adequado.

Referência

cURL
Comment: o echo $result;  veio =  1   ,  sinal que deu certo  ?
Comment: Se esse é o retorno que o site da quando recebe as informações com sucesso, sim, pois esta retornando `TRUE`, não tem como você verificar no site no qual esta fazendo a requisição se ele recebeu ?
Comment: @Wéllingthon M. de Souza  Não entrou nos leads Não !
Comment: @PauloMaia o que tem em `$nome` ? como você está recebendo o valores dessas variáveis?
Comment: @Wéllingthon M. de Souza Veja =   https://pastebin.com/mvai8JP7
Comment: @Wéllingthon M. de Souza  Não esta recebendo não  !
Comment: Esse link é o mesmo que está na pergunta, como ficou usando o código da resposta? Você pode ver o retorno quando você faz por formulário ? O formulário é submetido via *Ajax* ? Se sim, vai em *Ferramentas do desenvolvedor > Network*
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/68918/discussion-between-wmsouza-and-paulomaia).

FormJSON PHP para CURL ,


Product of binomial coefficient and fraction is integer

Question: While deriving a elementary argument for the inverse of the Hilbert Matrix, I encountered the following quantity

If $n \in \mathbb Z_+$ and $i \in \{0,\dots,n-1\}$, then
  $$ \frac{2n+1}{n-i} \binom{n+i}{n-1-i} = \frac{2n+1}{2i+1} \binom{n+i}{n-i}$$
  is an integer.

Numerical evidence seems to suggest that it is true (verified for $n$ up to $1024$). But there are several subtleties:

If the $2n+1$ coefficient is removed, this statement is no longer true.
It might be tempting to separate the binomial coefficient into two using the Pascal Triangle: $$ \binom{n+i}{n-1-i} = \binom{n-1+i}{n-2-i} + \binom{n-1+i}{n-1-i}$$ but each component after separating is not an integer.
By the substitution $n + i = a,n - i = b$,
$$ \frac{2n+1}{2i+1} \binom{n+i}{n-i} = \frac{a+b+1}{a-b-1} \binom{a}{b}
$$
Comment: Your integer is $\dbinom{n+i}{2i} + 2 \dbinom{n+i}{2i+1}$.
Answer:
Recalling the  binomial identity $\binom{n}{k}=\frac{n}{k}\binom{n-1}{k-1}$ we obtain
  \begin{align*}
\color{blue}{\frac{2n+1}{n-i}\binom{n+i}{n-i-1}}&=\frac{(n-i)+(n+i+1)}{n-i}\binom{n+i}{n-i-1}\\
&=\left(1+\frac{n+i+1}{n-i}\right)\binom{n+i}{n-i-1}\\
&\color{blue}{=\binom{n+i}{n-i-1}+\binom{n+i+1}{n-i}\in\mathbb{Z}}
\end{align*}


What is the interval from C double flat to E double sharp called?

Question: What is this interval called in terms of relative scale degrees?
Comment: This is a lot like asking, "How do I render an acute, a grave, a circumflex and a tilde above the same vowel?". A guru for some typesetting engine might be able to give you an answer, but it's a quite useless feat except for displaying "mad typesetting skillz". The thing you want to achieve simply doesn't occur in any reasonable text.
Comment: Just as a side-note, you might be better off writing this as a Bb and an F#, if you want people to actually play it. That's an augmented fifth.
Comment: @KilianFoth: That actually would be useful if you're in a metal band (though you'd probably want them over a consonant, rather than a vowel).
Answer: When you come across something like this, you should remove all the accidentals and add them one at a time:

C- E: major 3rd
C- E#:augmented 3rd
C -Ex: double augmented 3rd
Cb- Ex: triple augmented 3rd
Cbb-Ex: quadruple augmented 3rd.

Which I doubt you'll ever meet, even if it exists. Most likely it'll be Bb -F# which is a augmented 5th interval or Bb - Gb which is a minor sixth.
Comment: This is a great approach. Also helps with oddities such as E# to B  which was confusing me to try and count on a piano…
Answer: It would be a quadruply augmented 3rd and would be written as AAAA3.
C to E alone is obviously a major third (M3). From there realize that by adding a double sharp to the E you increase the distance by two semitones the and the resulting interval C to E♯♯ is a doubly augmented third (AA3). From there you can see by lowing the C two semitones results in  the interval being increased by two more semitones resulting in the quadruply augmented 3rd.
Doubly augmented intervals in general are rare as seen in this question, so I doubt you'll see it outside a theoretical context.


Melhor forma de se aplicar o conceito de Orientação a objetos

Question: Eu possuo uma classe Usuario
class Usuario{

}

Digamos que esse usuario precise acessar alguns Web Services diferentes para obter recursos e informações. Pensei então em criar uma classe chamada WebService e agrupar todos os métodos com acesso a API e serviços externos lá.
class WebService {

}

A minha dúvida é. O usuário não é um WebService, por isso, não posso e nem devo extender essa class. Sendo assim. Qual é a melhor forma de utilizá-la em Usuário? Devo criar seus métodos como abstratos e simplesmente usá-los. Ou existe uma melhor abordagem para este caso?
Comment: `$webservice = new WebService()` ?
Comment: @CaioFelipePereira essa é a minha dúvida. Se eu devo tratar assim, utilizando métodos abstratos, ou se existe alguma outra abordagem melhor.
Answer: Uma forma é utilizar o conceito de composicão. Se o seu WebService necessita de um usuário para utilizar a API, poderá fazer algo como:
class Usuario {...}

class WebService {
    private $user;

    public function __construct(Usuario $user) {
        $this->user = $user;
    }
}

E utilizar, em WebService, $this->user para acessar o usuário em questão. A instância do WebService seria algo como:
$webService = new WebService(new Usuario());

Nota sobre interfaces
Para ficar ainda mais conciso com os conceitos de OOP, ao invés de definir o parâmetro de WebService como sendo da classe Usuario, você pode criar uma interface:
interface UsuarioInterface
{
    public function getUsername();
    public function setUsername($username);
    public function getPassword();
    public function setPasswrod($passwrod);
}

E na classe WebService:
class WebService {
    private $user;

    public function __construct(UsuarioInterface $user) {
        $this->user = $user;
    }
}

O que isso muda? Na primeira solução o parâmetro do construtor deve, obrigatoriamente, ser uma instância de Usuario (da classe em si ou de qualquer outra que extenda a classe), mas dependendo da dimensão de sua aplicação, esta limitação pode ser um problema. Na segunda solução, qualquer classe que implemente a interface UsuarioInterface pode servir de parâmetro. Esta prática é bastante útil quando for integrar sua aplicação com códigos de terceiros (se for o caso).
Comment: Excelente @Anderson. Era algo assim q eu estava procurando.
Comment: Acho meio estranho um webservice receber um usuário. Talvez o contrário fosse melhor, até porque quem usa algo deve receber esse algo para usar.
Comment: @Piovezan não necessariamente. A lógica que deve ser analisada é quem é composto pelo quê. Um usuário não é composto por um WebService, mas este tem em sua composicão um usuário para efetuar a autenticacão.
Comment: Ah sim, tem razão. Não tinha relacionado usuário à autenticação.


Taking the derivative of a conditional expectation.

Question: My text claims that the following is obvious given a Markov chain $Z_{n}$ defined by the sum $Z_{n+1}=\sum_{j=0}^{Z(n)} X^{n+1}_{j}$, given a double infinite sequence $X_{s,t}$ of iid rvs
$E(Z_{n+1}\mid Z_{n})=\mu Z_{n}$
The following motivation, which I cannot follow is given,
"confirm by differentiating the formula $ E(\theta^{Z_{n+1}}\mid Z_{n})=f(\theta)^{Z_{n}}$ $(1)$ and let $\theta =1$, where $f$ is the probability generating function"
I understand the identity given in the hint, but I dont know how to interpret the LHS of $(1)$ in a way which makes me able to take the derivatite w.r.t $\theta$. The book does not presuppose any measure thoery, hence the answer is not suppposed to contain any Radon-Nikodym derivative.
Comment: Can you differentiate $$\theta^{Z_{n+1}}$$ with respect to $\theta$?
Comment: The RHS is $$f(\theta)^{Z_n}=\sum_{k=0}^\infty f(\theta)^k\mathbf 1_{Z_n=k}$$ and you are supposed to differentiate this with respect to $\theta$. Sorry but what is there to "interpret" here?
Comment: @Did I am sorry I ofc mean LHC , the one with the expectation. The RHS is clear to me.
Comment: @Did ofc, the problem is that I am thinking of the conditional as an rv $g(Z_{n})$. I dont even know how to start differentiating anything.
Comment: 1. What is $\mu$? 2. Do you have assumptions on the integrability of $X_{j,n}$?
Comment: @saz 1 and 2, $\mu$ is the expectation of $X$ and they are iid.
Comment: You need some additional assumptions on the intgrability of $X$ to ensure that $\mathbb{E}(\theta^{Z_n})$ is well-defined for $\theta$ (sufficently) close to $1$.
Comment: @saz oh, you wanna suggest something suitable?
Comment: As @Did mentioned, the LHS of (1) is a function $g(\theta)=\int \theta^{Z_{n+1}(\omega)}\ \mathrm{d}P(\omega)$, for some measure $P$. If the function inside the integral is well behaved, you should be able to interchange the order of differentiation and integration.
Comment: @Ron That's not technically right since the expectation is w.r.t. a sub-sigma algebra, however the general idea of "differentiating under the expectation" is indeed correct.
Answer: I wouldn't say it is obvious, but I think this is more or less the argument.  First, prove the assertion that $E(\theta^{Z_{n+1}}\rvert Z_n)=f(\theta)^{Z_n}$
\begin{align}
f(\theta)^{Z_n}=\left(\sum_{x=0}^\infty p(x)\theta^x\right)^{Z_n}=\sum_{x_0,\ldots,x_{Z_n}}p(x_0,\ldots,x_{Z_n})\theta^{\sum_{i=0}^{Z_n} x_i}=\sum_{Z_{n+1}=0}^{\infty}p(Z_{n+1})\theta^{Z_{n+1}}=E(\theta^{Z_{n+1}}\rvert Z_n),
\end{align}
where the penultimate equality follows because all of the sequences are i.i.d.  This requires some thought to understand, but I think it makes sense, because almost by definition $p(\sum_{i=0}^{Z_n}x_i=Z_{n+1})=p(Z_{n+1})$.
Now perform the differentiation
\begin{align}
\frac{\partial}{\partial \theta}E(\theta^{Z_{n+1}}\rvert Z_n)=\frac{\partial}{\partial \theta}\sum_{Z_{n+1}=0}^{\infty}p(Z_{n+1}\rvert Z_n)\theta^{Z_{n+1}}=\sum_{Z_{n+1}=0}^{\infty}Z_{n+1}p(Z_{n+1}\rvert Z_n)\theta^{Z_{n+1}-1}.
\end{align}
Setting $\theta=1$ yields
\begin{align}
\frac{\partial}{\partial \theta}E(\theta^{Z_{n+1}}\rvert Z_n)\rvert_{\theta=1}=\sum_{Z_{n+1}=0}^{\infty}Z_{n+1}p(Z_{n+1}\rvert Z_n)=E(Z_{n+1}\rvert Z_n).
\end{align}
Plugging in the formula for $E(\theta^{Z_{n+1}}\rvert Z_n)$ derived previously, we find
\begin{align}
\frac{\partial}{\partial \theta}E(\theta^{Z_{n+1}}\rvert Z_n)\rvert_{\theta=1}=Z_n f(\theta)^{Z_n-1}f'(\theta)\rvert_{\theta=1}=\mu Z_n,
\end{align}
where the last equality follows from properties of the generating function.


Load a common component in named outlet

Question: I have a requirement where I have a login page which has just the login component. Once a person logs in, the user gets to page having a left navigation and a component on the right. With the help of this left navigation, a person can navigate to different components.
So the thing is, the left navigation component should be available on all the pages once logged-in and not on the login page.
I tried to replicate the same at https://stackblitz.com/edit/angular-common-component-in-named-router-outlet but it just loads the navigation component. The router configuration looks like
[
    { path: "", component: HomeComponent },
    {
        path: "messages",
        component: NavComponent,
        children: [{ path: "", component: MessagesComponent, outlet: "content" }]
    },
    {
        path: "users",
        component: NavComponent,
        children: [{ path: "", component: UsersComponent, outlet: "content" }]
    }
];

Comment: IMO named outlets are a mistake for this (and a mistake in general tbh). just structure your app so you've got your login component then a main component that has the nav and a regular primary outlet
Comment: you need to check if the user is loggedin. and maybe add `*ngIf="user$ | async"` something like this on the components that you don't want to show unless on condition. if you don't want to go to that page, you can use the `canActivate` option in the router.
Answer: Named outlets are a PITA and not worth the trouble, especially for this, you could just do this:
[
    { path: "", component: HomeComponent },
    {
        path: "messages",
        component: NavComponent,
        children: [{ path: "", component: MessagesComponent}]
    },
    {
        path: "users",
        component: NavComponent,
        children: [{ path: "", component: UsersComponent }]
    }
];

and stick a normal <router-outlet></router-outlet> in your nav component... no real need for the name in this structure. But I think you'd be better served with a structure like:
[
    { path: "", component: HomeComponent },
    {
        path: "main",
        component: NavComponent,
        children: [
          { path: "messages", component: MessagesComponent},
          { path: "users", component: UsersComponent }
        ]
    }
];

and the same router-outlet in your nav component. the only difference here is you're prefixing your logged in paths with "main" so you don't need to repeat your routes over and over for them to be matched

Load a common component in named outlet


How do you write a consistent UI Automation for MS? MSAA & UI Automation don't seem to overlap

Question: Working on a general Automation tool, considering moving from Win32 Message hooks to .net UI Automation, however the feature set of UI Automation doesn't cover all we have in Win32 and still doesn't seem to support all the GUI on Windows.
One such example is Windows Live Messenger.
Windows Live messenger 2009 is still using the older DirectUIHwnd to draw the gui.  This means that you can't use windows messages to send to the controls, because the controls don't have their own HWND.  It also seems to defeat the new .net UI Automation framework though the documentation seems to make out as if it can be joined in the UI Automation and Microsoft Active Accessibility document.
Looking at MS Accessibility pointed to Active Accessibility 2.0 SDK Tools which showed that MSAA can interact with the contents.
Is there some trick to getting the older MSAA technology that UI Automation seems to be trying to replace to actually work with UI Automation?
I'd rather not have multiple solutions trying to automate the same windows for windows unlike Windows Live Messenger where each of these techniques is valid and will work.
Answer: You might want to have a look at version 3 of the UIAutomation API, first released as part of Windows 7, but now available for XP and Vista. I believe it has improved support for interacting with MSAA-enabled targets.
This new API is COM-based, rather than managed; but have a look at UI Automation COM-to .Net Adapter on CodePlex. This takes the COM Api and adapts it to have the same "shape" as the current managed UIAutomation API.